Explore Courses
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Birla Institute of Management Technology Birla Institute of Management Technology Post Graduate Diploma in Management (BIMTECH)
  • 24 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Popular
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science & AI (Executive)
  • 12 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
University of MarylandIIIT BangalorePost Graduate Certificate in Data Science & AI (Executive)
  • 8-8.5 Months
upGradupGradData Science Bootcamp with AI
  • 6 months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
OP Jindal Global UniversityOP Jindal Global UniversityMaster of Design in User Experience Design
  • 12 Months
Popular
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Rushford, GenevaRushford Business SchoolDBA Doctorate in Technology (Computer Science)
  • 36 Months
IIIT BangaloreIIIT BangaloreCloud Computing and DevOps Program (Executive)
  • 8 Months
New
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Popular
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
Golden Gate University Golden Gate University Doctor of Business Administration in Digital Leadership
  • 36 Months
New
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
Popular
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
Bestseller
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
IIIT BangaloreIIIT BangalorePost Graduate Certificate in Machine Learning & Deep Learning (Executive)
  • 8 Months
Bestseller
Jindal Global UniversityJindal Global UniversityMaster of Design in User Experience
  • 12 Months
New
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in AI and Emerging Technologies (Blended Learning Program)
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
ESGCI, ParisESGCI, ParisDoctorate of Business Administration (DBA) from ESGCI, Paris
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration From Golden Gate University, San Francisco
  • 36 Months
Rushford Business SchoolRushford Business SchoolDoctor of Business Administration from Rushford Business School, Switzerland)
  • 36 Months
Edgewood CollegeEdgewood CollegeDoctorate of Business Administration from Edgewood College
  • 24 Months
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with Concentration in Generative AI
  • 36 Months
Golden Gate University Golden Gate University DBA in Digital Leadership from Golden Gate University, San Francisco
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA by Liverpool Business School
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA (Master of Business Administration)
  • 15 Months
Popular
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Business Administration (MBA)
  • 12 Months
New
Deakin Business School and Institute of Management Technology, GhaziabadDeakin Business School and IMT, GhaziabadMBA (Master of Business Administration)
  • 12 Months
Liverpool John Moores UniversityLiverpool John Moores UniversityMS in Data Science
  • 18 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityMaster of Science in Artificial Intelligence and Data Science
  • 12 Months
Bestseller
IIIT BangaloreIIIT BangalorePost Graduate Programme in Data Science (Executive)
  • 12 Months
Bestseller
O.P.Jindal Global UniversityO.P.Jindal Global UniversityO.P.Jindal Global University
  • 12 Months
WoolfWoolfMaster of Science in Computer Science
  • 18 Months
New
Liverpool John Moores University Liverpool John Moores University MS in Machine Learning & AI
  • 18 Months
Popular
Golden Gate UniversityGolden Gate UniversityDBA in Emerging Technologies with concentration in Generative AI
  • 3 Years
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (AI/ML)
  • 36 Months
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDBA Specialisation in AI & ML
  • 36 Months
Golden Gate University Golden Gate University Doctor of Business Administration (DBA)
  • 36 Months
Bestseller
Ecole Supérieure de Gestion et Commerce International ParisEcole Supérieure de Gestion et Commerce International ParisDoctorate of Business Administration (DBA)
  • 36 Months
Rushford, GenevaRushford Business SchoolDoctorate of Business Administration (DBA)
  • 36 Months
Liverpool Business SchoolLiverpool Business SchoolMBA with Marketing Concentration
  • 18 Months
Bestseller
Golden Gate UniversityGolden Gate UniversityMBA with Marketing Concentration
  • 15 Months
Popular
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Corporate & Financial Law
  • 12 Months
Bestseller
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Intellectual Property & Technology Law
  • 12 Months
Jindal Global Law SchoolJindal Global Law SchoolLL.M. in Dispute Resolution
  • 12 Months
IIITBIIITBExecutive Program in Generative AI for Leaders
  • 4 Months
New
IIIT BangaloreIIIT BangaloreExecutive Post Graduate Programme in Machine Learning & AI
  • 13 Months
Bestseller
upGradupGradData Science Bootcamp with AI
  • 6 Months
New
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
KnowledgeHut upGradKnowledgeHut upGradSAFe® 6.0 Certified ScrumMaster (SSM) Training
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutCertified ScrumMaster®(CSM) Training
  • 16 Hours
upGrad KnowledgeHutupGrad KnowledgeHutLeading SAFe® 6.0 Certification
  • 16 Hours
KnowledgeHut upGradKnowledgeHut upGradPMP® certification
  • Self-Paced
upGrad KnowledgeHutupGrad KnowledgeHutAWS Solutions Architect Certification
  • 32 Hours
upGrad KnowledgeHutupGrad KnowledgeHutAzure Administrator Certification (AZ-104)
  • 24 Hours
KnowledgeHut upGradKnowledgeHut upGradAWS Cloud Practioner Essentials Certification
  • 1 Week
KnowledgeHut upGradKnowledgeHut upGradAzure Data Engineering Training (DP-203)
  • 1 Week
MICAMICAAdvanced Certificate in Digital Marketing and Communication
  • 6 Months
Bestseller
MICAMICAAdvanced Certificate in Brand Communication Management
  • 5 Months
Popular
IIM KozhikodeIIM KozhikodeProfessional Certification in HR Management and Analytics
  • 6 Months
Bestseller
Duke CEDuke CEPost Graduate Certificate in Product Management
  • 4-8 Months
Bestseller
Loyola Institute of Business Administration (LIBA)Loyola Institute of Business Administration (LIBA)Executive PG Programme in Human Resource Management
  • 11 Months
Popular
Goa Institute of ManagementGoa Institute of ManagementExecutive PG Program in Healthcare Management
  • 11 Months
IMT GhaziabadIMT GhaziabadAdvanced General Management Program
  • 11 Months
Golden Gate UniversityGolden Gate UniversityProfessional Certificate in Global Business Management
  • 6-8 Months
upGradupGradContract Law Certificate Program
  • Self paced
New
IU, GermanyIU, GermanyMaster of Business Administration (90 ECTS)
  • 18 Months
Bestseller
IU, GermanyIU, GermanyMaster in International Management (120 ECTS)
  • 24 Months
Popular
IU, GermanyIU, GermanyB.Sc. Computer Science (180 ECTS)
  • 36 Months
Clark UniversityClark UniversityMaster of Business Administration
  • 23 Months
New
Golden Gate UniversityGolden Gate UniversityMaster of Business Administration
  • 20 Months
Clark University, USClark University, USMS in Project Management
  • 20 Months
New
Edgewood CollegeEdgewood CollegeMaster of Business Administration
  • 23 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
The American Business SchoolThe American Business SchoolMBA with specialization
  • 23 Months
New
Aivancity ParisAivancity ParisMSc Artificial Intelligence Engineering
  • 24 Months
Aivancity ParisAivancity ParisMSc Data Engineering
  • 24 Months
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGrad KnowledgeHutupGrad KnowledgeHutData Engineer Bootcamp
  • Self-Paced
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
KnowledgeHut upGradKnowledgeHut upGradBackend Development Bootcamp
  • Self-Paced
upGradupGradUI/UX Bootcamp
  • 3 Months
upGradupGradCloud Computing Bootcamp
  • 7.5 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 5 Months
upGrad KnowledgeHutupGrad KnowledgeHutSAFe® 6.0 POPM Certification
  • 16 Hours
upGradupGradDigital Marketing Accelerator Program
  • 05 Months
upGradupGradAdvanced Certificate Program in GenerativeAI
  • 4 Months
New
upGradupGradData Science Bootcamp with AI
  • 6 Months
Popular
upGradupGradFull Stack Software Development Bootcamp
  • 6 Months
Bestseller
upGradupGradUI/UX Bootcamp
  • 3 Months
PwCupGrad CampusCertification Program in Financial Modelling & Analysis in association with PwC India
  • 4 Months
upGradupGradCertificate Course in Business Analytics & Consulting in association with PwC India
  • 06 Months
upGradupGradDigital Marketing Accelerator Program
  • 05 Months

String Functions In Java | Java String [With Examples]

Updated on 16 November, 2022

8.3K+ views
8 min read

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.

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?

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.

2. What 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.

3. How 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.

RELATED PROGRAMS