Version without JavaScript, read-only: workshops, quizzes and running code are not available here. Full version · Catalogue · Sign in
Lecture notes · chapter 10
Strings
String is an object, not a primitive type, and that changes everything.
Strings are enclosed in double quotes ("), whereas characters are enclosed in single quotes (').
11 Common operations
The associated type is String. You can perform assignments and concatenations (= and +); new is optional in the declaration.
- The length of a string is returned by
chaine.length(), with parentheses, unlike arrays. - Equality is tested with
equals(orequalsIgnoreCaseif you do not care about case). - The n-th character is obtained with
charAt.
String maChaine = "Hello dear students!";
for (int i = 0; i < maChaine.length(); i++) {
System.out.println(maChaine.charAt(i));
}
== compares references, equals compares contents
public class Demo {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println("a == b : " + (a == b)); // true: same cached object
System.out.println("a == c : " + (a == c)); // false: two different objects
System.out.println("a.equals(c) : " + a.equals(c)); // true: same contents
System.out.println("equalsIgnoreCase : " + a.equalsIgnoreCase("JAVA"));
System.out.println("length : " + a.length());
System.out.println("3rd character: " + a.charAt(2));
System.out.println("upper case : " + a.toUpperCase());
System.out.println("concatenation : " + a + " " + 8);
}
}