Java Strings
A String stores text, such as a name, a message or an address.
Creating a String
Example
String greeting = "Welcome to Workownix";Strings are objects, so they come with many useful methods you can call with a dot.
Common String Methods
| Method | What it returns |
|---|---|
length() | Number of characters |
toUpperCase() | The text in capital letters |
toLowerCase() | The text in small letters |
charAt(i) | The character at position i |
indexOf("x") | Position of the first match, or -1 |
substring(a, b) | Part of the text from a up to (not including) b |
contains("x") | true if the text is found |
trim() | The text without spaces at the start and end |
replace("a", "b") | The text with every "a" changed to "b" |
Example
public class Main {
public static void main(String[] args) {
String city = "Karachi";
System.out.println(city.length());
System.out.println(city.toUpperCase());
System.out.println(city.charAt(0));
System.out.println(city.indexOf("chi"));
System.out.println(city.substring(0, 4));
}
}7 KARACHI K 4 Kara
Positions (indexes) in a string start at 0, not 1. In "Karachi", K is at index 0 and the last i is at index 6.
Joining Strings
You can join strings with + or with concat():
Example
public class Main {
public static void main(String[] args) {
String first = "Ayesha";
String last = "Khan";
System.out.println(first + " " + last);
System.out.println(first.concat(last));
int roll = 42;
System.out.println("Roll no: " + roll);
}
}Ayesha Khan AyeshaKhan Roll no: 42
When you join a string and a number, Java turns the number into text. Be careful: "1" + 2 + 3 gives "123", but 1 + 2 + "3" gives "33", because Java works from left to right.
Comparing Strings
Use equals() to check if two strings have the same text. Do not use == for strings, because it checks whether they are the same object in memory.
Example
public class Main {
public static void main(String[] args) {
String password = "pak123";
String typed = "PAK123";
System.out.println(password.equals(typed));
System.out.println(password.equalsIgnoreCase(typed));
}
}false true
Special Characters
Use a backslash \ to put special characters inside a string:
| Code | Result |
|---|---|
\" | Double quote |
\\ | Backslash |
\n | New line |
\t | Tab |
Example
System.out.println("He said \"Shukriya\"\nand left.");He said "Shukriya" and left.
Exercise
Exercise
What does "Lahore".length() return?
