Java Strings
A String is a sequence of characters, like a name or a sentence. It is an object (not a primitive) and it is used in almost every program.
Create a string
public class Main {
public static void main(String[] args) {
String a = "Hello"; // string literal
String b = new String("Hello"); // a new object
String empty = "";
System.out.println(a + " " + b + " [" + empty + "]");
System.out.println(a.length());
}
}
Hello Hello []
5
Join strings (concatenation)
public class Join {
public static void main(String[] args) {
String first = "Riya";
String last = "Sharma";
System.out.println(first + " " + last);
System.out.println(first.concat(" ").concat(last));
System.out.println("Age: " + 25 + 1); // text + number: joined as text
System.out.println(25 + 1 + " is the age"); // number + number first
}
}
Riya Sharma
Riya Sharma
Age: 251
26 is the age
Comparing strings: equals, not ==
== checks if two variables point to the same object. equals() checks if the text is the same. Always use equals() for text.
public class Compare {
public static void main(String[] args) {
String a = "java";
String b = "java";
String c = new String("java");
System.out.println(a == b); // true: same pooled object
System.out.println(a == c); // false: different object
System.out.println(a.equals(c)); // true: same text
System.out.println("JAVA".equalsIgnoreCase(a)); // true
System.out.println("apple".compareTo("banana")); // negative: apple comes first
}
}
true
false
true
true
-1
Java keeps all string literals in a special area called the string pool, so two equal literals are the same object. A string made with new is a separate object.
Strings are immutable
You can not change a string after it is created. Methods like toUpperCase() give a new string:
public class Immutable {
public static void main(String[] args) {
String s = "java";
s.toUpperCase(); // result is thrown away
System.out.println(s);
s = s.toUpperCase(); // keep the new string
System.out.println(s);
}
}
java
JAVA
Special characters
| Escape | Meaning |
|---|---|
| \n | New line |
| \t | Tab |
| \” | Double quote |
| \’ | Single quote |
| \\ | Backslash |
public class Escape {
public static void main(String[] args) {
System.out.println("Line 1\nLine 2");
System.out.println("Name:\tRiya");
System.out.println("She said \"Hello\"");
System.out.println("C:\\temp");
}
}
Line 1
Line 2
Name: Riya
She said "Hello"
C:\temp
Null and empty
public class Null {
public static void main(String[] args) {
String empty = "";
String nothing = null;
System.out.println(empty.isEmpty()); // true
System.out.println(nothing == null); // true
System.out.println(" ".isBlank()); // true: only spaces
}
}
true
true
true
Calling a method on null, like nothing.length(), throws a NullPointerException.
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |