Data
String
Java
String name = "Sam";
You can literally specify a string by wrapping it inside double-quotes (""
).
String text1 = "Sam's age:\t21"; // Sam's age: 21
To specify special characters or characters that make ambiguity for compiling String Literals, you need to escape them. This is a list of escaping characters:
\'
Single quote\"
Double quote\\
Backslash\n
Newline\r
Carriage return\t
Tab\b
Backspace\f
Form feed\XXX
Octal character code (0-377)\uXXXX
Unicode character (0000-FFFF)
String str1 = "Hello World!";
int length = str1.length(); // 12
The length()
method returns the number of characters inside a string.
String str1 = "Hello World!";
char firstCh = str1.charAt(0); // H
You can get a character at any zero-based index using the charAt()
method.
String str1 = "Hello World!";
String str2 = str1.substring(0,1)+'3'+str1.substring(2);
// H3llo World!
Strings are immutable in Java, so you can only get a character on an index, and not setting it.
To replace a character in a string, you need to create a new string.
String str1 = "Hello";
String str2 = "World!";
String str3 = str1 + " " + str2; // Hello World!
You can concatenate strings using the +
operator.
String str1 = "Hello World";
int index = str1.indexOf("llo"); // 2
The indexOf()
method searches for the index of the first occurrence of some string inside another one.
If the substring does not exist, it returns -1.
String str1 = "Hello World!";
String substr1 = str1.substring(6); // World!
String substr2 = str1.substring(6, 8); // Wo
The substring()
method gets the starting index (inclusive) and ending index (exclusive) and returns the substring for those parameters.
If you don't specify the ending index, substring()
will return the substring from the starting point to the end of the string.