String
You've used String objects since your very first "Hello, World!" program.
- A
Stringobject encapsulates a sequence ofchars.
Once created, the char values stored inside a String cannot be changed - that is, each String is immutable.
immutable¶
In Java, an object is considered immutable if its state cannot change after it is constructed.1
String is Special¶
- We can construct a
Stringusing a String literal: double-quoted text.
String firstName = "Barb";
Strings using +;
System.out.println(firstName + " Dobbs");
String representation.
Sphere s = new Sphere(3.0);
System.out.println(s); // println() converts Sphere object to String and prints result.
String Constructors¶
String provides many constructors for creating a String from...
- Another
String.
String fullName = new String(firstName + " " + lastName);
- An array of
char,byte, orintin which the array elements are characters.
char[] greet = new char[5];
greet[0] = 'H'; greet[1] = 'e'; greet[2] = 'l'; greet[3] = 'l'; greet[4] = 'o';
String greeting = new String(greet);
- No argument.
String emptyString = new String();
[1] https://docs.oracle.com/javase/tutorial/essential/concurrency/immutable.html