A string is a sequence of characters surrounded by double quotations. In a java programming language, a string is the object of a built-in class String.
In the background, the string values are organized as an array of a character data type.
The string created using a character array can not be extended. It does not allow to append more characters after its definition, but it can be modified.
Example
char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r',
'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
System.out.println(name);
The String class defined in the
package java.lang package
Creating String object in java
In java, we can use the following two ways to create a
string object.
- Using
string literal
- Using
String constructor
String title = "Java Tutorials"; // Using literals
String siteName = new String("www.mybcaclassnotes.blogspot.com"); // Using constructor
1. length()Returns the number of characters in the string.
String str = "Hello";
System.out.println(str.length()); // Output: 5
2. charAt(int index)
Returns the character at the specified index (0-based).
String str = "Java";
System.out.println(str.charAt(2)); // Output: v
Returns a part of the string.
String str = "Programming";
System.out.println(str.substring(3)); // Output: gramming
System.out.println(str.substring(3, 7)); // Output: gram
Checks if two strings are exactly equal (case-sensitive).
String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.equals(s2)); // Output: false
Checks equality, ignoring case.
String s1 = "Hello";
String s2 = "hello";
System.out.println(s1.equalsIgnoreCase(s2)); // Output: true
6. toUpperCase() and toLowerCase()
String name = "Prasanjeet";
System.out.println(name.toUpperCase()); // Output: PRASANJEET
System.out.println(name.toLowerCase()); // Output: prasanjeet
Appends the specified string to the end.
String s1 = "Hello";
String s2 = "World";
System.out.println(s1.concat(" " + s2)); // Output: Hello World
Replaces characters in a string.
String str = "apple";
System.out.println(str.replace('p', 'b')); // Output: abble
Removes whitespace from the beginning and end.
String s = " Java ";
System.out.println(s.trim()); // Output: Java
Checks if a string contains a sequence.
String str = "I love Java";
System.out.println(str.contains("love")); // Output: true
String str = "filename.txt";System.out.println(str.startsWith("file")); // Output: trueSystem.out.println(str.endsWith(".txt")); // Output: true
12. indexOf(char ch) and lastIndexOf(char ch)
Returns the index of the first/last occurrence of the character.
String str = "banana";
System.out.println(str.indexOf('a')); // Output: 1
System.out.println(str.lastIndexOf('a')); // Output: 5