Introduction to Java strings
A String is defined as a sequence or an array of characters. We know that String in Java is not a primitive data type as we have discussed in our data types tutorial, rather it is an object type. Java Strings are one of the most common and widely used classes in Java programming. The String is an array of characters, and since arrays are immutable in nature, a String is an immutable object, which means they are constant, and we cannot change them after creating the objects.
In this tutorial, we will learn about java strings. We will see how we can create strings in the java programming language and will cover some of the important methods that are used to perform different operations on Java strings. All in all, this tutorial will cover all the important concepts regarding strings that you need to know.
Getting started with Java Strings
In Java programming language, strings are objects. The String class represents character strings. All string literals in Java programs, such as “abcdef”
, are implemented as instances of this class. The String class is immutable so that once it is created it cannot be changed. Java Strings are the only class where operator overloading is supported which means we can concat two strings using the +
operator.
For example "a"+ "b" = "ab"
. Now let us see how we can create strings in the Java programming language.
Method-1 Creating Java strings
The most simple and easy method to create java strings is using string literals. In this method, we need to enclose a string literal with double quotes. See the simple syntax below:
String name_of_string = "String Expression"
Now let us take a real example and create java strings using this method and then prints out those strings. See the example below:
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = "Bashir";
String string2 = "UCA";
// printing the strings
System.out.println("My name is : "+string1);
System.out.println("My university is: "+string2);
}
}
Output:
My name is : Bashir
My university is: UCA
Method-2 Creating Java strings
The second method to create java strings is to use the "new" keyword. It actually creates a new object of type Strings. The simple syntax looks like this:
String name_of_string = new String("string expression");
Now let us take an example and see how we can create java strings using this method. See the example below.
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("Bashir");
String string2 = new String("UCA");
// printing the strings
System.out.println("My name is : "+string1);
System.out.println("My university is: "+string2);
}
}
Output:
My name is : Bashir
My university is: UCA
Various methods of Java strings
The methods of the Java strings class are used to obtain information about objects and are known as accessor methods. The String class provides many accessor methods that are used to perform operations on a string. Some of which are listed below:
length()
: Returns the length of the string.charAt(index)
: return a character value at a specified position (index) of a String.concat()
: used for concatenating or adding two strings into a single string.substring(beginIndex)
: used to create new objects or instances of String class from existing instances of String.compareTo()
: returns an integer that indicates the lexicographic (alphabetical) comparison of the two strings.toUpperCase()
: converts all the characters of a given string to uppercase.toLowerCase()
: converts all the characters of a given string to lowercase.
Now let us see each of the above java string method and solve related examples:
Example-1 Find length of String
Sometimes we might want to find the length of the string in order to find the indexing or to iterate over the string. Manual counting of each character might not be the best option when we have a large string. So, in such a case, we may want some function or method to find the length of a string in one go. Fortunately, java provides us length()
a method, which returns the total length of the string. The simple syntax of the java lenght()
method is as follows:
StringName.lenght();
Now, let us solve real examples using this method and find out the length of various java strings. See the example below:
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("Bashir");
String string2 = new String(" ");
// Applying java length() method
System.out.println("Length of first string is : "+string1.length());
System.out.println("Length of second string is: "+string2.length());
}
}
Output:
Length of first string is : 6
Length of second string is: 3
Notice that for the first string, we get 6 which is fine because it contains six characters but the second string does not contain any characters, why do we get 3? It is because whitespaces are considered to be characters in a java programming language, and this string contains three whitespaces.
Example-2 Index and positioning of Java strings
Sometimes we might want to know which character is at the specific position and again going through the string manually is not a good option because it takes too much time if we have a large string. So, for such cases, we need some direct method to find the character at the specified position. Fortunately, Java provides us charAt()
method which is used to find the character at the specified position. The simple syntax looks like this:
StringName.charAt(postition);
Now let us take a practical example and see how we can use the charAt()
method to find the character at the specified position.
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("Bashir");
String string2 = new String("*$&*%)$&%23542");
// Applying java charAt() method
System.out.println("character at position 4 is : "+string1.charAt(4));
System.out.println("character at position 7 is : "+string2.charAt(7));
}
}
Output:
character at position 4 is : i
character at position 7 is : &
Notice that we get the character of the specified position. And also remember one thing that the indexing starts from 0, not from 1.
Example-3 Concatenate Java strings
While dealing with strings we might come across a situation where we need to concatenate the java strings together. Java provides us simple way to add strings together. The method concat()
is used for concatenating or adding two strings into a single string. This method appends its String argument to the indicated string argument and returns a new instance of the String class. The simple syntax looks like this:
String1Name.concat(String2Name);
Now let us take an example and see how we can add strings together. See the following example.
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("My name is ");
String string2 = new String("Bashir Alam");
// Applying java concat() method
System.out.println(string1.concat(string2));
}
}
Output:
My name is Bashir Alam
Notice that we had successfully added two different java strings together.
Example-4 Substring method in java strings
The substring method with a single argument is used to create new objects or instances of the String class from existing instances of String. The method returns the substring from the index which is passed as an argument to the method. While the substring with two arguments method is used to create new objects or instances of String class from existing instances of String. The method returns the new String by using the required index range (including the start index and excluding the end index). The simple syntax of the substring method is as follows:
StringName.substring(startingIndex, endingIndex);
Now let us take an example and see how the substring method with single and double parameters works. See the example below:
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("My name is Bashir Alam");
// Applying java substring method
System.out.println(string1.substring(10));
System.out.println(string1.substring(10, 16));
}
}
Output:
Bashir Alam
Bashi
Notice that in the first one, we get the whole string after the starting index while in the second one the substring is within the specified range.
Example-5 Comparing Java strings
Sometimes we might want to compare two java strings but unlike other programming languages, the compare method does not return true or false if strings are the same or different. The compareTo()
method in Java returns an integer that indicates the lexicographic (alphabetical) comparison of the two strings. The result is negative if the relative alphabetic value of the particular letter of the first string is smaller than that of the second string’s letter on the same location. And it is positive if the first string is lexicographically larger than the second string. And if both strings are the same, it will return zero. The simple syntax of the java compare method looks like this:
String1Name.compareTo(String2Name);
Now let us take an example and see how it works. See the example below:
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("My name is Bashir Alam");
String string2 = new String("Bashir Alam");
String string3 = new String("Bashir Alam");
// Applying java strings compare method
System.out.println(string1.compareTo(string2));
System.out.println(string2.compareTo(string3));
System.out.println(string3.compareTo(string1));
}
}
Output:
11
0
-11
Example-6 change Java strings to upper case
In Java, we have a built-in method to covert all the characters of a string to the upper case. The following is the simple syntax of the java upper case method.
stringName.toUpperCase();
Now let us take an example and see how we can convert a string to upper case. See the following example.
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("My name is Bashir Alam");
String string2 = new String("123456");
// Applying toUpperCase() method
System.out.println(string1.toUpperCase());
System.out.println(string2.toUpperCase());
}
}
Output:
MY NAME IS BASHIR ALAM
123456
Notice that it only converts the alphabets to upper case and prints out digits as it is without any error<.
Example-7 change Java strings to lower case
Java has a built-in function to convert a string into lower case. The following is the simple syntax to convert Java string to lower case.
StringName.toLowerCase();
Now let us take an example and convert the string to lower case using the above method. See the example below:
// class
public class Main {
// main method
public static void main(String[] args) {
// creating java strings
String string1 = new String("My NAMe is BASHIR Alam");
String string2 = new String("&&%*$&#%#");
// Applying toLowerCase() method
System.out.println(string1.toLowerCase());
System.out.println(string2.toLowerCase());
}
}
Output:
my name is bashir alam
&&%*$&#%#
Notice that we had successfully converted the string to lower case and it prints the special characters as it is without any error.
Summary
Java Strings are Objects that are backed internally by a char array. Since arrays are immutable, Strings are also immutable. Whenever a change to a String is made, an entirely new String is created. In this tutorial, we learned about java strings. We discussed different ways to create java strings taking examples. Moreover, we came across various strings methods that are used in java programming and which help us to interact with java strings. All in all, this tutorial covers each and everything that you need to learn in order to start working with java strings.
Further Reading
java string methods
java strings documentation
string methods