Differentiation of Java String with Examples

If you are interested to learn about the Java Operators

Strings are used for storing text. string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object. A String variable contains a collection of characters surrounded by double quotes:

Example

Create a variable of type String and assign it a value:

String greeting = "Hello";

The java.lang.String class implements SerializableComparable and CharSequence interfaces.

String in Java

CharSequence Interface

The Char Sequence interface is used to represent the sequence of characters. String, String Bufferand String Builder classes implement it. It means, we can create strings in Java by using these three classes.

CharSequence in Java

The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes.

How to create a string object?

There are two ways to create String object:

  1. By string literal
  2. By new keyword

1) String Literal

Java String literal is created by using double quotes. For Example:

String s="welcome";  

Each time you create a string literal, the JVM checks the “string constant pool” first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string doesn’t exist in the pool, a new string instance is created and placed in the pool. For example:

String s1="Welcome";  
String s2="Welcome";//It doesn't create a new instance  
Java String

In the above example, only one object will be created. Firstly, JVM will not find any string object with the value “Welcome” in string constant pool that is why it will create a new object. After that it will find the string with the value “Welcome” in the pool, it will not create a new object but will return the reference to the same instance.

Note: String objects are stored in a special memory area known as the “string constant pool”.

Why Java uses the concept of String literal?

To make Java more memory efficient (because no new objects are created if it exists already in the string constant pool).

2) By new keyword

String s=new String("Welcome");//creates two objects and one reference variable  

In such case, JVM will create a new string object in normal (non-pool) heap memory, and the literal “Welcome” will be placed in the string constant pool. The variable s will refer to the object in a heap (non-pool).

Java String Example

StringExample.java

public class StringExample{    
public static void main(String args[]){    
String s1="java";//creating string by Java string literal    
char ch[]={'s','t','r','i','n','g','s'};    
String s2=new String(ch);//converting char array to string    
String s3=new String("example");//creating Java string by new keyword    
System.out.println(s1);    
System.out.println(s2);    
System.out.println(s3);    
}}    

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the String objects s1, s2, and s3 on console using println() method.

String Length

A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method:

Example

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());

More String Methods

There are many string methods available, for example toUpperCase() and toLowerCase():

Example

String txt = "Hello World";
System.out.println(txt.toUpperCase());   // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase());   // Outputs "hello world"

Finding a Character in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

Example

String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7

Java String Concatenation

The + operator can be used between strings to combine them. This is called concatenation:

Example

String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);

Note that we have added an empty text (” “) to create a space between firstName and lastName on print. You can also use the concat() method to concatenate two strings:

Example

String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));

Java Numbers and Strings

Java uses the + operator for both addition and concatenation. Numbers are added. Strings are concatenated. If you add two numbers, the result will be a number:

Example

int x = 10;
int y = 20;
int z = x + y;  // z will be 30 (an integer/number)

If you add two strings, the result will be a string concatenation:

Example

String x = "10";
String y = "20";
String z = x + y;  // z will be 1020 (a String)

If you add a number and a string, the result will be a string concatenation:

Example

String x = "10";
int y = 20;
String z = x + y;  // z will be 1020 (a String)

Java Special Characters

Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

String txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character. The backslash (\) escape character turns special characters into string characters:

Escape characterResultDescription
\’Single quote
\”Double quote
\\\Backslash

The sequence \"  inserts a double quote in a string:

Example

String txt = "We are the so-called \"Vikings\" from the north.";

The sequence \'  inserts a single quote in a string:

Example

String txt = "It\'s alright.";

The sequence \\  inserts a single backslash in a string:

Example

String txt = "The character \\ is called backslash.";

Other common escape sequences that are valid in Java are:

CodeResult
\nNew Line
\rCarriage Return
\tTab
\bBackspace
\fForm Feed
Differentiation of Java String with Examples
Show Buttons
Hide Buttons