STring and char

Strings

What is a String

  • Java String is a sequence of characters

  • Example:

    • "Java"

    • "1365"

    • ""

    • "    " 

    • "?"

Creating String (1)

  • Many ways of constructing a string:

Creating String (2)

  • Many ways of constructing a string:

Creating String (3)

  • Many ways of constructing a string:

String Creation

  • Does Java create 2 String objects internally?

  • Without “new” operator for String creation:

    • Java looks into the String pool (Collection of Strings)

      • Try to find objects with same String value

    • If object exists new variable points to existing object
    • If object does not exist new object is created
    • For efficiency ...

 

String Creation

String Creation

String methods

  • Advantage of String class:

    • many built-in methods for String manipulation

Methods: valueof

  • String.valueOf(x) – returns String

    representation of x.

  • x: char, int, double, float

  • Useful for converting different types to String

You can also use x+"", which is shorter.

Methods: substring

 

  • str.substring(i, k)
    • Returns substring of characters from index i to k-1
  • str.substring(i)
    • Returns substring of characters from the index i to the end

 

Methods: concat

  • Method 1: plus “+” operator

 

 

  • Method 2: Using String’s “concat” method  

 

String immutability

  • Strings in Java are immutable
  • Meaning: cannot change its value, once created

 

String immutability

  • With frequent modifications of Strings:

    • Create many new objects – uses up memory

    • Destroy many unused ones – increase workload

    • Overall: can slow down performance

 

String equality

String equality

  • Checking if two Strings contain same value

characters

Binary vs. text

  • All data are in the end binary

    • (10001110110001) in base 2

  • Bits represent encoded information,, executable instructions, or numeric data
  • In order to store text files we need binary representation for all characters

 

text encoding

  • In ASCII encoding, one byte

    represents one character

  • Encoding is a rule where you map

    characters to integers:

    • ‘a’ = 97 (01100001) in base 2

Ascii Table

Resource: http://www.asciichars.com

DUE SOon

  • zybooks Chapter 6 due Monday at noon
  • lab 3 next Thursday
  • program 2 (in zybooks - 3 parts) next Friday

Copy of Strings and char

By Narges Norouzi

Copy of Strings and char

  • 31