• String is a class so when we make a new string we’re actually creating an object
  • String is immutable!
    • If you want String to be immutable, you want to use StringBuffer

Basics

// same thing
String myString = new String("aBc");
String myString = "aBc";
 
// returns new string
System.out.println(myString.toUpperCase()) // ABC
System.out.println(myString.toLowerCase()) // abc
System.out.println(myString)               // aBc
String test = "Leejun";
String test2 = "Leejun";
  • They will point to the same place in memory!

In memory

  • Using normal String class (not StringBuffer)
String test = "hello";
String test = "hello!!";
  • When you change the value like this, the value 1 itself is STILL STORED in memory!
  • This is what happens in the JVM
(before)
stack 
-----------
| s | 101 |
-----------

heap memory
| 101 | hello |
| 103 |       |
-----------

(after)
-----------
| s | 103 |
-----------

heap memory
| 101 | hello   |
| 103 | hello!! |
-----------

StringBuffer

StringBuffer s = new StringBuffer("hello");
s.append("!"); //s = "hello!"

Comparison

String myString = "aBc";
System.out.println(myString.toLowerCase() == "abc"); // comparing instances (addresses)
System.out.println(myString.toLowerCase().equals("abc")); // comparing values
  • If you compare 2 primitives types, you compare the value
  • If you compare 2 reference types, you compare if they point to the same instances

string concatenation

System.out.println(a + "+" + b " = " + (a + b));
System.out.println("데카르트는 \"나는 생각한다. 고로 존재한다.\"라고 말했다.");