View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

String Functions In Java | Java String [With Examples]

By Rohan Vats

Updated on Nov 16, 2022 | 8 min read | 8.4k views

Share:

Introduction

Java has gained a lot of respect among programmers because of its object-oriented programming support and pre-defined functions for data types provided. Strings are one of the impressing data types provided by java.

They are immutable and stored on the heap area in a separate memory block called String Constant Pool. There are many pre-defined functions for strings in java, let’s explore them!

Check out our free courses to get an edge over the competition.

Functions

charAt()

To access the character at a particular position we don’t need a loop for iterating to that index, charAt() function does the hard work for you!. The charAt() function returns the character at a particular position in the string, remember that the index starts from 0 in java.

This function is defined with access modifier as public and it returns a char. This method expects an integer as the parameter and accessing the function with a parameter greater than the string length returns an IndexOutOfBounds Exception, which is a runtime exception.

Check out upGrad’s Java Bootcamp

String str = “hey there“;
char first = str.charAt(0);

char second = str.charAt(1);

System.out.println(first+“ “+second);

The above snippet will give ‘h e’ as output because the variable first is assigned with the character ‘h’ and the variable second is assigned with the character ‘e’.

compareTo() and compareToIgnoreCase()

Comparing two strings will not work with a == operator in java, because it checks if the address of both the variables and returns true if both the variables have the same address. So a == operator fails to compare the content of the strings, here comes the compareTo() method into action.

Check out upGrad’s Advanced Certification in Blockchain

This public method expects a string or an object as a parameter which is to be compared and returns an integer value after a lexicographic comparison, remember that this method is case sensitive. But we can use compareToIgnoreCase() for a comparison ignoring the lower case and upper case of characters.

String str1 = “Hello“;
String str2 = “Hello“;

String str3 = “hello“;

int i1 = str1.comapreTo(str2);

int i2 = str2.compareTo(str3);

int i3 = str2.compareToIgnoreCase(str3);

System.out.println(i1+“ “i2+“ “+i3);

The above snippet will print ‘1 0 1’ as output because the variable i1 is assigned with 1 since both the strings are equal, variable i2 is assigned with 0 since we are comparing strings by case sensitivity. Similarly, variable i3 is assigned with 1 since we are comparing the strings by ignoring the upper and lower cases.

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

concat()

Since strings are immutable we cannot edit the value of a string instead we can just reassign the updated value to the same variable. We can use the concat() method for concatenating both strings. This method expects a string as a parameter which is to be concatenated and returns a new concatenated string.

String s1 = “first “;
String s2 = “second“;

System.out.println(s1.concat(s2));

The above snippet prints a string “first second”.

Read: JavaBeans Properties & Benefits: How Should You Utilize?

contains()

Checking if a string is present as a subsequence of another string is now a cakewalk. contains() method in java is a boolean public function and returns true if a sequence of characters is present in a string and false if not. This method expects a character sequence as the parameter and returns a NullPointerException if a null object is passed as a parameter.

String s1 = “Hey there“;
System.out.println(s1.contains(“the“)); //line1  

System.out.println(s1.contains(“”));    //line2

System.out.println(s1.contains(null));  //line3

The above snippet prints True for line 1 because the sequence “the” is present in the string, similarly line 2 prints True because an empty sequence returns True by default. And line 3 throws a NullPointerException since a null is passed a parameter.

upGrad’s Exclusive Software Development Webinar for you –

SAAS Business – What is So Different?

indexOf()

We have seen a java function which returns the character present at a given index, but what if we want the index of the first occurrence of a given character. Relax, indexOf() function does the job. This function is internally overridden with four different signatures, let’s walk through them.

String s1 = “Hey there, hey There, Hey There, hey there“;
System.out.println(s1.indexOf(“there“));   //line 1

System.out.println(s1.indexOf(“there“,5)); //line 2

System.out.println(s1.indexOf(‘T‘));       //line 3

System.out.println(s1.indexOf(‘T‘,16));    //line 4

In the above snippet, the function called in line1 expects a string and this returns the starting index of the first occurrence of a given string, it prints 4 in this case. The function called in line2 expects a string along with an integer as the parameters, now this integer refers to the starting index where the searching for a given string starts from that index, it prints 37 in this case.

The function called in line3 expects a character as the parameter, it returns the first occurrence of the given character, it prints 15 in this case. Similarly, the function present in line4 expects a character and an integer.

Where the integer represents the starting index and then searching for the given character starts from that character, it prints 26 in this case. Remember that this function is completely case sensitive, which we can see in the above snippet.

Get Software Development Course from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

isEmpty()

This function does a simple task but a very useful one from the programmer’s point of view. This boolean function returns True if the string is empty and False if not. This function helps to check if a string is empty before performing any tasks on the string because few of the functions throw an exception for empty strings which interrupts the flow of execution.

String s1 = “Hey there“;
String s2 = “”;

System.out.println(s1.isEmpty()); //line1

System.out.println(s2.isEmpty()); //line2

Above snippet prints False for line1, and True for line2.

length()

Finding out the length of a string is no more a tedious task, the length() function in java returns the length of the given string. This returns zero if an empty string is passed as a parameter.

String s1 = “abcdefghijklmnopqrstuvwxyz“;
System.out.println(s1.length());

The above code prints 26.

replace()

Unlike the indexOf() function, where it returns only the first occurrence of the sequence, The replace() function replaces all the specified characters with the given new character and returns a new string. This public function expects two characters, say c1 and c2 as the parameters. Where it searches for all characters equal to c1 and replaces them with c2.

String s1 = “helloHELLO“;
System.out.println(s1.replace(‘l‘, ‘p‘));

Remember this function is case sensitive, so the above snippet prints “heppoHELLO”.

toLowerCase() and toUpperCase()

Converting a string to lower case or vice versa is a fun task in java, which just needs the art of a single line of code, and toLowerCase(), toUpperCase() functions are the artists.

These public functions expect no parameters and return a new string with the updated lower and upper case of characters.

String s1 = “Hey There“;
System.out.println(s1.toUpperCase());  //line1

System.out.println(s1.toLowerCase());  //line2

In the above snippet line2 prints “hey there” and line1 prints “HEY THERE”.

Learn: Event Handling in Java: What is that and How Does it Work?

trim()

A naive approach to remove the trailing and leading white spaces in a string is to loop over the string and remove the character if it is a white space, but there’s an optimal way. The trim() function removes all the leading and trailing spaces of the string and returns a new string. This public function doesn’t expect any parameter.

String s1 = “       Hey There       “;

System.out.println(s1.trim());

The above snippet prints “Hey There” which is the new string after trimming the trailing and leading white spaces.

Conclusion

We’ve walked through a few of the string functions in java, understood how they work, what they expect, and what they return. Explored the overridden signatures of few functions, walked through a sample code snippet for a proper understanding. Now that you are aware of a few functions, start utilizing them whenever it is required. 

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s PG Diploma in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects, and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.

 

Frequently Asked Questions (FAQs)

1. What is the importance of design skills in software development?

2. What is the demand for web developers in the current market?

3. How can AI replace real developers?

Rohan Vats

408 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

AWS | upGrad KnowledgeHut

AWS Certified Solutions Architect - Associate Training (SAA-C03)

69 Cloud Lab Simulations

Certification

32-Hr Training by Dustin Brimberry

upGrad KnowledgeHut

upGrad KnowledgeHut

Angular Training

Hone Skills with Live Projects

Certification

13+ Hrs Instructor-Led Sessions

upGrad

upGrad KnowledgeHut

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks