Handling String in Java

Last updated on Dec 24 2022
Prabhas Ramanathan

In Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example:
1. char[] ch={‘j’,’a’,’v’,’a’,’t’,’p’,’o’,’i’,’n’,’t’};
2. String s=new String(ch);
is same as:
1. String s=”tecklearn”;
Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
The java.lang.String class implements Serializable, Comparable and CharSequenceinterfaces.

java 40

Table of Contents

CharSequence Interface

The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in java by using these three classes.

java 41

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.
We will discuss immutable string later. Let’s first understand what is String in Java and how to create the String object.

What is String in java

Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.

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:
1. 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:
1. String s1=”Welcome”;
2. String s2=”Welcome”;//It doesn’t create a new instance

java 42

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

1. 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

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

 

java
strings
example

 

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of char values.

No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 static String format(String format, Object… args) returns a formatted string.
4 static String format(Locale l, String format, Object… args) returns formatted string with given locale.
5 String substring(int beginIndex) returns substring for given begin index.
6 String substring(int beginIndex, int endIndex) returns substring for given begin index and end index.
7 booleancontains(CharSequence s) returns true or false after matching the sequence of char value.
8 static String join(CharSequence delimiter, CharSequence… elements) returns a joined string.
9 static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) returns a joined string.
10 booleanequals(Object another) checks the equality of string with the given object.
11 booleanisEmpty() checks if string is empty.
12 String concat(String str) concatenates the specified string.
13 String replace(char old, char new) replaces all occurrences of the specified char value.
14 String replace(CharSequence old, CharSequence new) replaces all occurrences of the specified CharSequence.
15 static String equalsIgnoreCase(String another) compares another string. It doesn’t check case.
16 String[] split(String regex) returns a split string matching regex.
17 String[] split(String regex, int limit) returns a split string matching regex and limit.
18 String intern() returns an interned string.
19 int indexOf(int ch) returns the specified char value index.
20 int indexOf(int ch, int fromIndex) returns the specified char value index starting with given index.
21 int indexOf(String substring) returns the specified substring index.
22 int indexOf(String substring, int fromIndex) returns the specified substring index starting with given index.
23 String toLowerCase() returns a string in lowercase.
24 String toLowerCase(Locale l) returns a string in lowercase using specified locale.
25 String toUpperCase() returns a string in uppercase.
26 String toUpperCase(Locale l) returns a string in uppercase using specified locale.
27 String trim() removes beginning and ending spaces of this string.
28 static String valueOf(int value) converts given type into string. It is an overloaded method.

Do You Know?
• Why are String objects immutable?
• How to create an immutable class?
• What is string constant pool?
• What code is written by the compiler if you concatenate any string by + (string concatenation operator)?
• What is the difference between StringBuffer and StringBuilder class?

What will we learn in String Handling?
• Concept of String
• Immutable String
• String Comparison
• String Concatenation
• Concept of Substring
• String class methods and its usage
• StringBuffer class
• StringBuilder class
• Creating Immutable class
• toString() method
• StringTokenizer class

Immutable String in Java

In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can’t be changed but a new string object is created.
Let’s try to understand the immutability concept by the example given below:

1. class Testimmutablestring{ 
2. public static void main(String args[]){ 
3. String s="Sachin"; 
4. s.concat(" Tendulkar");//concat() method appends the string at the end 
5. System.out.println(s);//will print Sachin because strings are immutable objects 
6. } 
7. }

 

Output:Sachin

java 43

As you can see in the above figure that two objects are created but s reference variable still refers to “Sachin” not to “Sachin Tendulkar”.
But if we explicitely assign it to the reference variable, it will refer to “Sachin Tendulkar” object.For example:

1. class Testimmutablestring1{ 
2. public static void main(String args[]){ 
3. String s="Sachin"; 
4. s=s.concat(" Tendulkar"); 
5. System.out.println(s); 
6. } 
7. }

 

Output:Sachin Tendulkar
In such case, s points to the “Sachin Tendulkar”. Please notice that still sachin object is not modified.

Why string objects are immutable in java?

Because java uses the concept of string literal.Suppose there are 5 reference variables,allreferes to one object “sachin”.If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

Java String compare

java 44

We can compare string in java on the basis of content and reference.
It is used in authentication (by equals() method), sorting (by compareTo() method), reference matching (by == operator) etc.
There are three ways to compare string in java:
1. By equals() method
2. By = = operator
3. By compareTo() method

1) String compare by equals() method

The String equals() method compares the original content of the string. It compares values of string for equality. String class provides two methods:
• public booleanequals(Object another) compares this string to the specified object.
• public booleanequalsIgnoreCase(String another) compares this String to another string, ignoring case.

1. class Teststringcomparison1{ 
2. public static void main(String args[]){ 
3. String s1="Sachin"; 
4. String s2="Sachin"; 
5. String s3=new String("Sachin"); 
6. String s4="Saurav"; 
7. System.out.println(s1.equals(s2));//true 
8. System.out.println(s1.equals(s3));//true 
9. System.out.println(s1.equals(s4));//false 
10. } 
11. }

 

Output:true
true
false

1. class Teststringcomparison2{ 
2. public static void main(String args[]){ 
3. String s1="Sachin"; 
4. String s2="SACHIN"; 
5. 
6. System.out.println(s1.equals(s2));//false 
7. System.out.println(s1.equalsIgnoreCase(s2));//true 
8. } 
9. }

 

Output:
false
true

 

2) String compare by == operator

The = = operator compares references not values.

1. class Teststringcomparison3{ 
2. public static void main(String args[]){ 
3. String s1="Sachin"; 
4. String s2="Sachin"; 
5. String s3=new String("Sachin"); 
6. System.out.println(s1==s2);//true (because both refer to same instance) 
7. System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool) 
8. } 
9. }

 

Output:true
false

3) String compare by compareTo() method

The String compareTo() method compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.
Suppose s1 and s2 are two string variables. If:
• s1 == s2 :0
• s1 > s2 :positive value
• s1 < s2 :negative value

1. class Teststringcomparison4{ 
2. public static void main(String args[]){ 
3. String s1="Sachin"; 
4. String s2="Sachin"; 
5. String s3="Ratan"; 
6. System.out.println(s1.compareTo(s2));//0 
7. System.out.println(s1.compareTo(s3));//1(because s1>s3) 
8. System.out.println(s3.compareTo(s1));//-1(because s3 < s1 ) 
9. } 
10. }

 

Output:0
1
-1

String Concatenation in Java

In java, string concatenation forms a new string that is the combination of multiple strings. There are two ways to concat string in java:
1. By + (string concatenation) operator
2. By concat() method

1) String Concatenation by + (string concatenation) operator

Java string concatenation operator (+) is used to add strings. For Example:

1. class TestStringConcatenation1{ 
2. public static void main(String args[]){ 
3. String s="Sachin"+" Tendulkar"; 
4. System.out.println(s);//Sachin Tendulkar 
5. } 
6. }

 

Output:Sachin Tendulkar

The Java compiler transforms above code to this:
1. String s=(new StringBuilder()).append(“Sachin”).append(” Tendulkar).toString();
In java, String concatenation is implemented through the StringBuilder (or StringBuffer) class and its append method. String concatenation operator produces a new string by appending the second operand onto the end of the first operand. The string concatenation operator can concat not only string but primitive values also. For Example:

1. class TestStringConcatenation2{ 
2. public static void main(String args[]){ 
3. String s=50+30+"Sachin"+40+40; 
4. System.out.println(s);//80Sachin4040 
5. } 
6. }

 

80Sachin4040
Note: After a string literal, all the + will be treated as string concatenation operator.

2) String Concatenation by concat() method

The String concat() method concatenates the specified string to the end of current string. Syntax:
1. public String concat(String another)
Let’s see the example of String concat() method.

1. class TestStringConcatenation3{ 
2. public static void main(String args[]){ 
3. String s1="Sachin "; 
4. String s2="Tendulkar"; 
5. String s3=s1.concat(s2); 
6. System.out.println(s3);//Sachin Tendulkar 
7. } 
8. }

 

Sachin Tendulkar

Substring in Java

A part of string is called substring. In other words, substring is a subset of another string. In case of substring startIndex is inclusive and endIndex is exclusive.
Note: Index starts from 0.
You can get substring from the given string object by one of the two methods:
1. public String substring(int startIndex): This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
2. public String substring(int startIndex, int endIndex): This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
In case of string:
• startIndex: inclusive
• endIndex: exclusive
Let’s understand the startIndex and endIndex by the code given below.
1. String s=”hello”;
2. System.out.println(s.substring(0,2));//he
In the above substring, 0 points to h but 2 points to e (because end index is exclusive).

Example of java substring

1. public class TestSubstring{ 
2. public static void main(String args[]){ 
3. String s="SachinTendulkar"; 
4. System.out.println(s.substring(6));//Tendulkar 
5. System.out.println(s.substring(0,6));//Sachin 
6. } 
7. }

 

Tendulkar
Sachin

 

Java String class methods

The java.lang.String class provides a lot of methods to work on string. By the help of these methods, we can perform operations on string such as trimming, concatenating, converting, comparing, replacing strings etc.
Java String is a powerful concept because everything is treated as a string if you submit any form in window based, web based or mobile application.
Let’s see the important methods of String class.
Java String toUpperCase() and toLowerCase() method
The java string toUpperCase() method converts this string into uppercase letter and string toLowerCase() method into lowercase letter.
1. String s=”Sachin”;
2. System.out.println(s.toUpperCase());//SACHIN
3. System.out.println(s.toLowerCase());//sachin
4. System.out.println(s);//Sachin(no change in original)

SACHIN
sachin
Sachin

Java String trim() method

The string trim() method eliminates white spaces before and after string.
1. String s=” Sachin “;
2. System.out.println(s);// Sachin
3. System.out.println(s.trim());//Sachin

Sachin
Sachin

Java String startsWith() and endsWith() method

1. String s=”Sachin”;
2. System.out.println(s.startsWith(“Sa”));//true
3. System.out.println(s.endsWith(“n”));//true

true
true

Java String charAt() method

The string charAt() method returns a character at specified index.
1. String s=”Sachin”;
2. System.out.println(s.charAt(0));//S
3. System.out.println(s.charAt(3));//h

S
h

Java String length() method

The string length() method returns length of the string.
1. String s=”Sachin”;
2. System.out.println(s.length());//6

6

Java String intern() method

A pool of strings, initially empty, is maintained privately by the class String.
When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.
1. String s=new String(“Sachin”);
2. String s2=s.intern();
3. System.out.println(s2);//Sachin

Sachin

Java String valueOf() method

The string valueOf() method coverts given type such as int, long, float, double, boolean, char and char array into string.
1. int a=10;
2. String s=String.valueOf(a);
3. System.out.println(s+10);
Output:
1010

Java String replace() method

The string replace() method replaces all occurrence of first sequence of character with second sequence of character.
1. String s1=”Java is a programming language. Java is a platform. Java is an Island.”;
2. String replaceString=s1.replace(“Java”,”Kava”);//replaces all occurrences of “Java” to “Kava”
3. System.out.println(replaceString);
Output:
Kava is a programming language. Kava is a platform. Kava is an Island.

So, this brings us to the end of blog. This Tecklearn ‘Handling String in Java’ blog helps you with commonly asked questions if you are looking out for a job in Java Programming. If you wish to learn Java and build a career Java Programming domain, then check out our interactive, Java and JEE Training, that comes with 24*7 support to guide you throughout your learning period. Please find the link for course details:

Java and JEE Training

Java and JEE Training

About the Course

Java and JEE Certification Training is designed by professionals as per the industrial requirements and demands. This training encompasses comprehensive knowledge on basic and advanced concepts of core Java & J2EE along with popular frameworks like Hibernate, Spring & SOA. In this course, you will gain expertise in concepts like Java Array, Java OOPs, Java Function, Java Loops, Java Collections, Java Thread, Java Servlet, and Web Services using industry use-cases and this will help you to become a certified Java expert.

Why Should you take Java and JEE Training?

• Java developers are in great demand in the job market. With average pay going between $90,000/- to $120,000/- depending on your experience and the employers.
• Used by more than 10 Million developers worldwide to develop applications for 15 Billion devices.
• Java is one of the most popular programming languages in the software world. Rated #1 in TIOBE Popular programming languages index (15th Consecutive Year)

What you will Learn in this Course?

Introduction to Java

• Java Fundamentals
• Introduction to Java Basics
• Features of Java
• Various components of Java language
• Benefits of Java over other programming languages
• Key Benefits of Java

Installation and IDE’s for Java Programming Language

• Installation of Java
• Setting up of Eclipse IDE
• Components of Java Program
• Editors and IDEs used for Java Programming
• Writing a Simple Java Program

Data Handling and Functions

• Data types, Operations, Compilation process, Class files, Loops, Conditions
• Using Loop Constructs
• Arrays- Single Dimensional and Multi-Dimensional
• Functions
• Functions with Arguments

OOPS in Java: Concept of Object Orientation

• Object Oriented Programming in Java
• Implement classes and objects in Java
• Create Class Constructors
• Overload Constructors
• Inheritance
• Inherit Classes and create sub-classes
• Implement abstract classes and methods
• Use static keyword
• Implement Interfaces and use it

Polymorphism, Packages and String Handling

• Concept of Static and Run time Polymorphism
• Function Overloading
• String Handling –String Class
• Java Packages

Exception Handling and Multi-Threading

• Exception handling
• Various Types of Exception Handling
• Introduction to multi-threading in Java
• Extending the thread class
• Synchronizing the thread

File Handling in Java

• Input Output Streams
• Java.io Package
• File Handling in Java

Java Collections

• Wrapper Classes and Inner Classes: Integer, Character, Boolean, Float etc
• Applet Programs: How to write UI programs with Applet, Java.lang, Java.io, Java.util
• Collections: ArrayList, Vector, HashSet, TreeSet, HashMap, HashTable

Java Database Connectivity (JDBC)

• Introduction to SQL: Connect, Insert, Update, Delete, Select
• Introduction to JDBC and Architecture of JDBC
• Insert/Update/Delete/Select Operations using JDBC
• Batch Processing Transaction
• Management: Commit and Rollback

Java Enterprise Edition – Servlets

• Introduction to J2EE
• Client Server architecture
• URL, Port Number, Request, Response
• Need for servlets
• Servlet fundamentals
• Setting up a web project in Eclipse
• Configuring and running the web app with servlets
• GET and POST request in web application with demo
• Servlet lifecycle
• Servlets Continued
• Session tracking and filter
• Forward and include Servlet request dispatchers

Java Server Pages (JSP)

• Fundamentals of Java Server Page
• Writing a code using JSP
• The architecture of JSP
• JSP Continued
• JSP elements: Scriptlets, expressions, declaration
• JSP standard actions
• JSP directives
• Introduction to JavaBeans
• ServletConfig and ServletContext
• Servlet Chaining
• Cookies Management
• Session Management

Hibernate

• Introduction to Hibernate
• Introduction to ORM
• ORM features
• Hibernate as an ORM framework
• Hibernate features
• Setting up a project with Hibernate framework
• Basic APIs needed to do CRUD operations with Hibernate
• Hibernate Architecture

POJO (Plain Old Java Object)

• POJO (Plain Old Java Object)
• Persistent Objects
• Lifecycle of Persistent Object

Spring

• Introduction to Spring
• Spring Fundamentals
• Advanced Spring

Got a question for us? Please mention it in the comments section and we will get back to you.

 

 

0 responses on "Handling String in Java"

Leave a Message

Your email address will not be published. Required fields are marked *