Skip to content

String

You've used String objects since your very first "Hello, World!" program.

  • A String object encapsulates a sequence of chars.

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 String using a String literal: double-quoted text.

String firstName = "Barb";
* We can concatenate Strings using +;

System.out.println(firstName + " Dobbs");
* Every object can be converted to its 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, or int in 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


Prev -- Up -- Next