Some Misc Notes
← prev | next →     Top-level ToC     /java/examples/strings.html     (printable version)

Java strings are immutable.

Unicode (but only up to 0xffff) in strings is fine:

String s = "my 2¢";
String s = "my 2\u00a2";  // same

Other common operations:

String s = "rhu" + "barb";  // rhubarb
s.length();                 // 7
s.substring(0, 2);          // rh
s.charAt(1);                // h
s + 12;                     // rhubarb12

String s1 = "Hello";
String s2 = "hello";      // note, lowercase
s1.equals(s2);            // false
s1.equalsIgnoreCase(s1);  // true
s1.endsWith("ello");      // true
"jello".endsWith("ello")  // true

"jello".toCharArray();    // splits string into chars.

Note: don’t use == to test string equality — that only checks if two strings are actually the same string.

See docs for java.lang.String for lots of methods.

1 String Formatting

Full docs in java.util.Formatter.

String.format("hi, %s.", name);

String.format("Foo: %.2f", 1.231);  // Foo: 1.23
String.format("Foo: %04d", 23);     // Foo: 0023

String date_1 = String.format("%ts", new Date());  // epoch time
String date_1 = String.format("%tc", new Date());  // full date & time

See also System.out.printf.