Strings
Useful methods, comparing with equals, and StringBuilder.
A String cannot be changed once created: methods return a new one.
Java
public class Main {
public static void main(String[] args) {
String s = "Internship";
System.out.println(s.length());
System.out.println(s.charAt(0));
System.out.println(s.substring(0, 5));
System.out.println(s.toUpperCase());
System.out.println(s.contains("ship"));
}
}Output
10 I Inter INTERNSHIP true
Compare with equals, not ==
== checks whether two variables point at the same object. equals() checks the text. Interviewers often ask about this.
Java
public class Main {
public static void main(String[] args) {
String a = "java";
String b = new String("java");
System.out.println(a == b);
System.out.println(a.equals(b));
}
}Output
false true
StringBuilder
Building a long string in a loop with + creates a new object each time. StringBuilder changes one buffer instead.
Java
public class Main {
public static void main(String[] args) {
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= 3; i++) {
sb.append(i).append(",");
}
System.out.println(sb.reverse());
}
}Output
,3,2,1