Lecture 6

fall 2018

Narges Norouzi

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

Methods: substring

  • String.substring(x) – returns a new String by copying characters from an existing String.
  • 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

5 minutes break

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

Assignment 2 review

  • Zybooks chapters we covered

  • Chapter 2:

    • section 2.14

    • section 2.15

  • Zybooks chapters we'll cover next

  • Chapter 7: Objects and Classes

Questions?

Copy of CMPS12A - Lecture 6

By Narges Norouzi

Copy of CMPS12A - Lecture 6

  • 273