Blog_Banner_Asset
    Homebreadcumb forward arrow iconBlogbreadcumb forward arrow iconFull Stack Developmentbreadcumb forward arrow iconTop 13 String Functions in Java | Java String [With Examples]

Top 13 String Functions in Java | Java String [With Examples]

Last updated:
19th Feb, 2021
Views
Read Time
6 Mins
share image icon
In this article
Chevron in toc
View All
Top 13 String Functions in Java | Java String [With Examples]

String functions are the backbone of any coding language, and the versatile nature of these functions provided by Java is the best. So let us discuss the common string functions and their applications.

How to read a line from the console:  use nextLine method

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

Scanner in = new Scanner(System.in);

Ads of upGrad blog

String line = in.nextLine();

1. Indexing

We can access the character of a string using charAt(int pos) method.

ex:

String h = “hello world”;

System.out.println(h.charAt(4));

Check out upGrad’s Advanced Certification in Cyber Security

2. Getting a Position

This is the most frequent operation performed during string manipulation.

1. If you need position of any symbol, use indexOf(). It returns a numeric value (position) of a symbol.

ex: 

String para=”Batman is protector of gotham”;

int pos1 = para.indexOf(‘a’); //  1

int pos2 = para.indexOf(‘z’) // -1

Check out upGrad’s Advanced Certification in Blockchain

2. The java string lastIndexOf() method returns the last index of the given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

ex:

String para=”Batman is protector of gotham”;

int pos = para.lastIndexOf(‘a’); // 27

int pos2 = para.indexOf(‘z’) // -1

3. Pattern Matching

The java string contains() method searches the sequence of characters in the string. It returns true if a sequence of char values are found in this string otherwise returns false.

ex:

String name=”Batman is protector of gotham”;  

System.out.println(name.contains(“man is”));  // true

System.out.println(name.contains(“of gotham”));  // true

System.out.println(name.contains(“protector of metropolis”)); // false

Explore our Popular Software Engineering Courses

4. Checking Prefix and Suffixes

1. startsWith()  :

String s=”Optimus Prime”;

System.out.println(s.startsWith(“Op”));//true

2. endsWith() :

String s=”Optimus Prime”;

System.out.println(s.endsWith(“me”));//true

Explore Our Software Development Free Courses

5. Converting Other Data Types to String

This can be done by Java String valueOf() method. It converts given types such as int, long, float, double, boolean, char and char array into string.

ex:

int number=100;  // similarly we can convert another data types too

String str=String.valueOf(number);

System.out.println(str+10);

6. If Length of a String is Needed

Use the length() method of the string. It returns a count of the total number of characters.

ex:

String h = “hello world”;

int size = h.length()

7. To Check Whether a String is Empty

The java string isEmpty() method checks if this string is empty or not. It returns true, if the length of string is 0 otherwise false.

ex:

String s1=””;

String s2=”coding is divine”;

System.out.println(s1.isEmpty());  // print true

System.out.println(s2.isEmpty());  // print false

In-Demand Software Development Skills

8. Getting Substring

If you need a subpart of String then java provides an elegant way of doing this by the following methods.

1. substring(int beginIndex): This method returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

ex:

String str = “Hello World”;

String firstPart = str.substring(4);

2. substring(int beginIndex, int endIndex): The substring begins at the specified beginIndex and extends to the character at index endIndex – 1. Thus the length of the substring is (endIndex – beginIndex).

ex:

String str = “Hello World”;

String new_string = str.substring(1,6); // remember [ firstindex,lastindex )

9. If Want to Compare Two Different Strings

1. equals() method: It compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true.

ex:

String s1=”Freelancer”;

String s2=”Freelancer”;

String s3=”freelancer”;

String s4=”java”;

System.out.println(s1.equals(s2));//true because content and case is same

System.out.println(s1.equals(s3));//false because case is not same

System.out.println(s1.equals(s4));//false because content is not same

2. String.equalsIgnoreCase(): The String.equalsIgnoreCase() method compares two strings irrespective of the case (lower or upper) of the string. This method returns true if the argument is not null and the contents of both the Strings are the same ignoring case, else false.

ex:

String s1=”Freelancer”;  

String s2=”Freelancer”;  

String s3=”freeLancer”;  

String s4=”java”;  

System.out.println(s1.equalsIgnoreCase(s2));//true because content and case is same  

System.out.println(s1.equalsIgnoreCase(s3));//true because content same but cases are not same  

System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same

10. If We Want to Join Two Different Strings

Java provides the best method to join different strings by using concat method.

ex:

String s1=”love is immortal”;

String s2=” and coding is divine “;

String joined_string = s1.concat(s2);

System.out.println(joined_string); // prints love is immortal and coding is divine

Read our Popular Articles related to Software Development

11. If We Want to Change and Modify a String by Using Another String

We can use the replace() method using two ways.

1. replacing characters of string by another string’s character

ex:

String s1=”Every human can be extraordinary”;

String replacedString=s1.replace(‘a’,’e’);//replaces all occurrences of ‘a’ to ‘e’

System.out.println(replacedString);

2. replace words of a string with words of another string

ex:

String s1=” java can be replaced by python and it can lose its charm”;

String replaceString=s1.replace(“can”,”cannot”);//replaces all occurrences of “can” to “cannot”

System.out.println(replaceString);

12. Changing Cases of a String

1. string toLowerCase(): method returns the string in the lowercase letter. In other words, it converts all characters of the string into lower case letters.

ex:

String temp=”This is Uppercase And Lower Case String “;

String temp_lower=temp..toLowerCase();

System.out.println(temp_lower); //  “this is uppercase and lower case string “

2. Java string toUpperCase()  : method returns the string in uppercase letter. In other words, it converts all characters of the string into upper case letters.

ex:

String temp=”This is Uppercase And Lower Case String “;

String temp_upper=temp.toUpperCase();

System.out.println(temp_upper);   // “THIS IS UPPERCASE AND LOWER CASE STRING”

13. Eliminates Leading and Trailing Spaces

The java string trim() method eliminates leading and trailing spaces. Note: The string trim() method doesn’t omit middle spaces.

ex:

String s1=”  hello string   “;

System.out.println(s1+”coder”);//without trim()

String trimmed_string = s1.trim();

Ads of upGrad blog

System.out.println(trimmed_string+”coder”);//with trim()

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

Conclusion

If you’re interested to learn more about Java, OOPs & full-stack software development, check out upGrad & IIIT-B’s Executive PG Program 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 are strings in Java?

Strings in Java are used to store and manipulate text, They are represented by String class which is defined in java.lang package. String literals are enclosed between double quotes for example, String s = Hi;. String objects are created when you assign a String literal to a String variable, for example, String str = abc;. There are several methods of String class which are used for manipulating String objects. These methods are concat, substring, replace, length, toLowerCase, toLowerCase, toUpperCase, toUpperCase and split.

2Why are strings immutable in Java?

Strings are immutable because they're objects, while references are immutable because they're values, and that difference is meaningful. Being an object, a string is a collection of behaviors METHODS and fields DATA. Once you create a string, you need to do some work to make it do something else. In this case, you'd create a new string by allocating a new object, then copying the object's data fields into the new object. In this context, the new object would be mutable, since you can change it. But holding a reference to the new object is not, since you can't change the object.

3What is the toString method in Java?

The toString method in Java is used to convert objects into string form. This is a very commonly used method. Without using this, you cannot convert your object into string form. String class in Java already have a toString method and it returns the String representation of the given object. You can also use the toString method to convert a variable into a string. It is used to get the string representation of any object. For example: System.out.println o.toString;.

Explore Free Courses

Suggested Blogs

Top 40 MySQL Interview Questions & Answers For Beginners & Experienced [2023]
118095
Have a Data engineering or data science interview coming up? Need to practice some of the most asked MySQL interview questions? The article compiles t
Read More

by Rohan Vats

07 Nov 2023

Literals In Java: Types of Literals in Java [With Examples]
5969
Summary: In this article, you will learn about Literals in Java. Literals in Java Integral Literals Floating-Point Literals Char Literals String Lit
Read More

by Rohan Vats

29 Oct 2023

10 Interesting HTML Project Ideas & Topics For Beginners [2023]
392907
Summary In this article, you will learn 10 Interesting HTML Project Topics. Take a glimpse below. A tribute page A survey form Technical documentati
Read More

by Rohan Vats

04 Oct 2023

15 Exciting SQL Project Ideas & Topics For Beginners [2023]
285341
Summary: In this Article, you will learn 15 exciting SQL project ideas & topics for beginners. Library Management System Centralized College Dat
Read More

by Rohan Vats

24 Sep 2023

17 Interesting Java Project Ideas & Topics For Beginners 2023 [Latest]
35386
Summary: In this article, you will learn the 17 Interesting Java Project Ideas & Topics. Take a glimpse below. Airline reservation system Data v
Read More

by Rohan Vats

24 Sep 2023

9 Exciting Software Testing Projects & Topics For Beginners [2023]
8319
Software testing might constitute 50% of a software development budget but it is viewed as a lethargic and unnecessary step by most students. Even edu
Read More

by Rohan Vats

21 Sep 2023

Top 10 Skills to Become a Full-Stack Developer in 2023
218264
In the modern world, if we talk about professional versatility, there’s no one better than a Full Stack Developer to represent the term “versatile.” W
Read More

by Rohan Vats

21 Sep 2023

Java Free Online Course with Certification [2023]
57066
The PYPL Popularity of Programming Language Index maintains that Java is the second most popular programming language in the world, after Python.  Alt
Read More

by Rohan Vats

20 Sep 2023

Salesforce Developer Salary in India in 2023 [For Freshers & Experienced]
903234
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

20 Sep 2023

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