Java Strings: A comprehensive

Tanisha Gupta
6 min readJan 25, 2022

Strings in JAVA

A String in java can be defined as an object that represents a sequence of characters enclosed within double quotes.

Basic Syntax:

public class Main {
public static void main(String[] args) {
String s=”Good”;
// For ex: here “4” is a sequence of 6 characters.
}
}

A String is a Datatype as well as a class in java.

String as DataType

A Java String is a non-primitive data type which is also referred to as Reference Data Types because unlike primitive data types like int, float, long, etc, reference data types store reference of the objects or in the other words, they store the address of the objects in the memory.

String as an Object

It is an Immutable object of java. lang.String class means it is constant and can not be changed after it has been created.

To summarize: What is String in java?

A String in java is an immutable object of java.lang.String class and a non-primitive Datatype represent a sequence of characters enclosed within double-quotes.

Creating a String

There are two ways to create a String in Java :

  • String literal: A java string can be created by using double quotes.

For example:

String s=”Good”;
  • Using new keyword: Java String can also be created by using the “new” keyword.

For example:

String s=new String(“Good Morning”);

Point to Remember: S of String should be capital while creating a String object as it is a class.

Create String using literals vs new keyword

// String object created using String Literal
String r = new String(“Good”);
String r1 = new String(“Good”);
System.out.println(r == r1); //false
// String object created using the new keyword
String s = “Morning”;
String s1 = “Morning”;
System.out.println(s == s1); //true

As shown in the above code snippet:

Every time an object is created with the new keyword, a new object is created even if the same value is already being referenced by a string variable,

When String objects are created using String literal, it searches the String pool and returns the same reference if the same value is found.

Take reference from the image below for better understanding -

String Pool: A string pool is a storage area in Java heap memory where string literals are stored. It is also known as String Intern Pool or String Constant Pool. It is privately maintained by the java String class.

Methods of Strings in Java

  1. int length() : It returns the string length.

For ex:

String s=”You gonna love Strings”;
System.out.println(s.length());

Output :

22

2. char charAt(int index): It concatenates the specified string.

For ex:

System.out.println(s.charAt(5));

Output :

o

3. String substring(int beginIndex): It returns a substring for the given begin index.

For ex:

System.out.println(s.substring(2));

Output :

u gonna love Strings
  1. String substring(int beginIndex, int endIndex) : It returns substring for given begin index and end index where endIndex is not included.

For ex:

System.out.println(s.substring(4,6));

Output :

go
  1. String concat(String str): It concatenates the specified string.

For ex:

String r= “Welcome to “;String s=”the blog”;

System.out.println(r.concat(s));

Output :

Welcome to the blog
  1. int compareTo(String string1, String string2): In the method, it compares the given string with the current string lexicographically and returns a positive number, negative number, or 0.
  • if s1 > s2, it returns positive number
  • if s1 < s2, it returns negative number
  • if s1 == s2, it returns 0

For ex:

String s1=”good”;String s2=”good”;String s3=”means”;String s4=”heaven”;String s5=”empire”;System.out.println(s1.compareTo(s2));//0 because both are equalSystem.out.println(s1.compareTo(s3));//-6 because “g” is 6 lower than “m”System.out.println(s1.compareTo(s4));//-1 because “g” is 1 lower than “h”System.out.println(s1.compareTo(s5));//2 because “g” is 2 times greater than “e”

Output :

0-6-12
  1. String toUpperCase(): It returns a string in uppercase.

For ex: String s=”Hello There”;

System.out.println(s.toUpperCase());

Output :

HELLO THERE
  1. String toLowerCase(): It returns a string in lowercase.

For ex:

System.out.println(s.toLowerCase());

Output :

hello there
  1. String trim(): It removes the beginning and ending spaces of this string.

For ex:

String t =” Good Morning “;System.out.println(t.trim());

Output :

Good Morning
  1. String replace(char old, char new): It replaces all occurrences of the specified char value.

For ex:

String h=”hello”;System.out.println(h.replace(‘h’,’m’));

Output :

mello

String Concatenation in JAVA

In java, String concatenation i.e; joining two strings together to form a string can be done in two ways.

  1. By using the + operator.
String s=”Hello”;
String t =”There!”;
System.out.println(s+t);

Output:

HelloThere!
  1. Using concat() method.
String r= “This is “;String s=”amazing”;System.out.println(r.concat(s));

Output :

This is amazing

Creating Format Strings

String format(): The java string format() method returns the formatted string by given locale, format, and arguments.

Syntax:

public static String format(String format, Object… args) // orpublic static String format(Locale locale, String format, Object… args)

Parameters passed in the format() function represents -

locale: specifies the locale to be applied on the format() method.

format: Format of the string of the output string

args: arguments for the format string. It may be zero or more.

Examples of java format() method.

String s = String.format(“Welcome at %s”, str);
String str2 = String.format(“Formatted string with 8 decimal places is %.8f”, 45.65734);
String str3 = String.format(“Formatted string with 15 spaces is %15.8f”,45.65734);

int num = 7503;
String str4 = String.format(“%07d”, num);
// Print formatted strings
System.out.println(s);
System.out.println(str2);
System.out.println(str3);
System.out.println(str4);

Escape character in Java Strings

Earlier in the blog, we studied ways of creating strings, but how will we create a String which requires characters like double-quotes as a string.

For ex :

String s= “The book was written by J K Rowling is “Harry Potter” “;

This throws an error as the compiler is not able to understand where is the string ends due to extra double quotes within the string.

To prevent such situations and make the compiler understand, we use Escape characters for specific characters to be treated as normal characters or strings.

In Java, if a character is preceded by a backslash (\) is known as Java escape sequence or escape characters. It may include letters, numerals, punctuations, etc. Remember that escape characters must be enclosed in quotation marks (“ ”). These are the valid character literals. The Java compiler interprets these characters as a single character that adds a specific meaning to the compiler.

System.out.println(“The book written by J K Rowling is \”Harry Potter\” .”);

Output:

The book written by J K Rowling is “Harry Potter”.

Why are Java Strings are Immutable?

Strings in java are Immutable because java uses the concept of String Literal, String objects are cached in the String pool. Since cached String literals are shared between multiple clients there is always a risk, because of the security, synchronization, concurrency, caching, and class loading where one client’s action would affect all other clients. The reason for making string final is to restrict multiple users to extend and using it.

Conclusion:

  • A String in java is an immutable object of java.lang.String class and a non-primitive Datatype that represents a sequence of characters enclosed within double-quotes.
  • There are two ways to create string objects:
  • Using String Literal
  • Using new Keyword
  • Using String Literal V/S new keyword: Every time the object is created with the new keyword, a new object is created even though the same value is already referenced by a string variable,

When String objects are created using String literal, it searches the String pool and returns the same reference if the same value is found.

  • There are various inbuilt methods in String class like length(), charAt(), indexOf(), compareTo(), replace() etc.
  • There are two ways to concatenate the strings:
  • Using + operator
  • Using concat() method
  • The java string format() method returns the formatted string by given locale, format, and arguments. Parameters passed are:
  • locale: specifies the locale to be applied on the format() method.
  • format: Format of the string of the output string
  • args: arguments for the format string. It may be zero or more.
  • Escape Sequences: Escape sequences are used to signal an alternative interpretation of a series of characters. In Java, a character preceded by a backslash (\) is an escape sequence
  • Why are Strings Immutable? : Strings in java are Immutable because java uses the concept of String Literal, String objects are cached in the String pool, and any change there even by one client in the String’s value could affect other users accessing the string pool.
  • The immutable nature of Strings prevents security risks to the data stored in the string pool.

--

--

Tanisha Gupta

Wandering over the troughs and lows of Tech and Business.