Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconString Functions In Java | Java String [With Examples]

String Functions In Java | Java String [With Examples]

Last updated:
1st Dec, 2020
Views
Read Time
8 Mins
share image icon
In this article
Chevron in toc
View All
String Functions In Java | Java String [With Examples]

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.

Ads of upGrad blog

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

Explore our Popular Software Engineering Courses

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.

Explore Our Software Development Free Courses

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.

In-Demand Software Development Skills

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?

Read our Popular Articles related to Software Development

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       ;

Ads of upGrad blog

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.

Profile

Rohan Vats

Blog Author
Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming engineers into leaders.

Frequently Asked Questions (FAQs)

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

From the first idea to the finished product, design encompasses all phases required to develop a product or service. Research, planning, drawing, prototyping, and testing are all part of the process. Design abilities are vital in software development because they enable developers to create user interfaces and interactivity that are both simple to use and pleasing to the eye. Good design skills can also assist developers in writing more efficient code, which can improve the software's overall quality. Design skills can be thought of as the user interface for software development. Design skills contribute to a more user-friendly and efficient software development process.

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

Web developers are in charge of website design, development, and upkeep. They collaborate with designers and content producers to develop an aesthetically appealing and user-friendly website. Web developers must be well-versed in both front-end and back-end development, as well as the integration of several technologies into a cohesive website. In today's economy, web developers are in high demand. The key reason for this is that companies are increasingly using the internet to reach out to new clients and market their goods and services. As a result, the demand for web developers who can construct and manage websites is increasing.

3How can AI replace real developers?

AI refers to a computer program's ability to learn and work independently, making decisions based on data it has analyzed. Artificial Intelligence is employed in the business world for a variety of reasons. It can be used to automate processes, saving both time and money. It can also be used to examine data to aid in decision-making. AI won't be able to take the job of professional developers, but it can help automate some of the work they do. This frees up developers’ time to work on more sophisticated or human-interactive jobs. AI can also assist in identifying potential issues and faults in code and recommending fixes.

Explore Free Courses

Suggested Tutorials

View All

Suggested Blogs

Top 7 Node js Project Ideas & Topics
31536
Node.JS is a part of the famous MEAN stack used for web development purposes. An open-sourced server environment, Node is written on JavaScript and he
Read More

by Rohan Vats

05 Mar 2024

How to Rename Column Name in SQL
46895
Introduction We are surrounded by Data. We used to store information on paper in enormous file organizers. But eventually, we have come to store it o
Read More

by Rohan Vats

04 Mar 2024

Android Developer Salary in India in 2024 [For Freshers & Experienced]
901296
Wondering what is the range of Android Developer Salary in India? Software engineering is one of the most sought after courses in India. It is a reno
Read More

by Rohan Vats

04 Mar 2024

7 Top Django Projects on Github [For Beginners & Experienced]
51948
One of the best ways to learn a skill is to use it, and what better way to do this than to work on projects? So in this article, we’re sharing t
Read More

by Rohan Vats

04 Mar 2024

Salesforce Developer Salary in India in 2024 [For Freshers & Experienced]
909100
Wondering what is the range of salesforce salary in India? Businesses thrive because of customers. It does not matter whether the operations are B2B
Read More

by Rohan Vats

04 Mar 2024

15 Must-Know Spring MVC Interview Questions
34710
Spring has become one of the most used Java frameworks for the development of web-applications. All the new Java applications are by default using Spr
Read More

by Arjun Mathur

04 Mar 2024

Front End Developer Salary in India in 2023 [For Freshers & Experienced]
902362
Wondering what is the range of front end developer salary in India? Do you know what front end developers do and the salary they earn? Do you know wh
Read More

by Rohan Vats

04 Mar 2024

Method Overloading in Java [With Examples]
26101
Java is a versatile language that follows the concepts of Object-Oriented Programming. Many features of object-oriented programming make the code modu
Read More

by Rohan Vats

27 Feb 2024

50 Most Asked Javascript Interview Questions & Answers [2024]
4312
Javascript Interview Question and Answers In this article, we have compiled the most frequently asked JavaScript Interview Questions. These questions
Read More

by Kechit Goyal

26 Feb 2024

Schedule 1:1 free counsellingTalk to Career Expert
icon
footer sticky close icon