Today's Offer - Java Certification Training - Enroll at Flat 10% Off.

- Java Blogs -

Java String Functions & Methods with Examples

Introduction of Java String

Java String library is one of the most used Java libraries. In Java, the String class is encapsulated under java lang package. All the strings created in Java are of String type. Java string functions objects are immutable which means that the objects created once cannot be altered. This article discusses:

  1. String an immutable object
  2. Ways to create a String Object
  3. Why avoid string literal method for string object creation?
  4. A few of the popular string class functions
  5. Some important points about the string class

Java String an Immutable Object

The state of the immutable objects cannot be changed and that’s why they are known as immutable objects. In Java language, the immutable classes are String, Byte, Short, Double, Integer, Float, and wrapper classes. Following example shows the way to create an immutable object of String Class: [code lang="js"]Public final class TestString { Final String str; TestString(String s) this.str=s; public String get() return str; } [/code] In the above example, the TestString class is called the immutable class as the state of the class cannot be changed, once it will be created. Read More: Java Tutorial Guide For Beginners

Ways to Create a Java String Object

In Java a String object can be created by a number of ways, following are a few of them:

1). Using the new keyword

[code lang="js"]String str=new String ("Java").[/code]

Read: How to Call a Method in Java?

2). By using another String object

[code lang="js"]String str=new String(str1);[/code]

3). By using String literal

Literal means a simple string, written within the double quotes "" and a String literal itself is a String object: [code lang="js"]String str="Hello";[/code]

4). By using concatenation concept or + symbol

[code lang="js"]String str=str0+str1; or String str="hello" + "world";[/code] String objects inJava are stored in a string constant pool inside the heap memory. Whenever a String literal is created, JVM checks for its existence in the pool and if it already exists then a reference to the pool is created and returned.

Why avoid String literal method for String object creation?

As listed above that a String object in Java can be created with and without using the new keyword. In the below example the literals are assigned to the String class instances: [code lang="js"]String str1="Rest"; String str2="Rest";[/code] Above you can see, no String class object is created and so the new keyword is not used. Here the compiler will create only a single String object which will store the assigned literal or it will assign the literal to the provided string instance. If the object already exists in the memory then the new object of String class will not be created instead the value will be assigned to the existing object. So, whenever we need to create two different objects with same string then we should use the new keyword. Like in the following example the String objects are created with the help of new keyword. In this approach, the compiler will not create the single instance of the string object instead two objects will be created with the same string. [code lang="js"]String str1=new String ("Welcome"); String str2=new String ("Welcome");[/code] Here the two different String objects str1 and str2 will have the same value as “Welcome" and it will be stored in the memory.

Read: Java Collections Framework in Depth with Example for Beginners

A few of the Popular String Class Functions

In String class of Java, there are a number of methods or functions defined which can be directly used by the user. A few functions are an argument based and return values as well. These functions are called pre-defined functions and the user can use them directly. Following are a few of those functions with example and the concepts associated with them.  You can check the Java string methods library to check all possible pre-defined functions of the String class

  1. String Concatenation
  2. String length
  3. Compare to method
  4. Lowercase to uppercase conversion
  5. Ends with method

String Concatenation

It is one of the most used pre-defined String function. The function is used to join or concatenate the two Java strings. Like if you have two strings say str1 and str2 then you can add these two strings using concatenation function and as a result, you will get str3. Let us suppose that we have two strings say str1="welcome" and str2="back" to add these two strings we can use the string concatenation function as a result of which you will get the third string str3=welcomeback can be created by concatenating the two strings str1 and str2. [code lang="js"] Public class Sample_Concate{ Public static void main (String args[]) { String str1="welcome" String str2="back"; String str3=str1.concat(str2); System.out.println(str3); }} [/code] The output of the above program will be: "WelcomeBack"

String "Length" Method

String Length method is used to determine the length of the given string. Whenever you have to find the length of any string you can use this method. An example is given below: [code lang="js"]Public class sample_length { Public static void main (String args[]) String str="Welcome"; System.out.println("Length of the given string is" + str.length()); }[/code] The output of the above program will be: Length of the given string is 7 Read More: Java Spring Tutorial Guide for Beginner

CompareTo Method

To compare the value of the two strings the comparison method can be used directly. For this, the two strings can be passed to the method and the result of the comparison will be displayed. In this method, the result can be case sensitive, while if you don’t want to get the case-sensitive comparison result then you can use “compareToIgnoreCase" method. [code lang="js"]Public class sample_comparison {public static void main(String args[]) String str="Welcome" System.out.println(“Compare to Welcome" + str.compareTo(welcome)); System.out.println(“Compare to welcome where case is ignored" + str.compareToIgnoreCase(“WELCOME))); }[/code] The output of the above program will be: Compare to Welcome –ve value Compare to welcome where the case is ignored  0

Read: Top 30 Core Java Interview Questions and Answers for Fresher, Experienced Developer

String Java Method for conversion from lowercase to uppercase letters

If you want any of the lowercase string to be shown in uppercase then you can use the pre-defined method of conversion. For this, the methods used in Java are "ToLowerCase" and "ToUpperCase". The example is listed below: [code lang="js"]Public static void main(String args[]) { String str=welcome; System.out.println("Convert to Lowercase:" + str.toLowerCase"()); System.out.println("Convert to Uppercase" + str.toUpperCase()); }[/code] The output of the above program will be: Convert to Lowercase: welcome Convert to Uppercase: WELCOME

Method “Ends With"

To know that whether a string is ending with a particular suffix you can use this method. You can use this method directly and pass the suffix which you want to check that whether a string is having that particular suffix at the end or not. The method returns a TRUE value if the suffix is found at the end of string otherwise it returns FALSE. Following example shows the use of this method: [code lang="js"]Public class Sample_Suffix { Public static void main (String args[]) { String str="welcome"; System.out.println(“Ends with character ‘e’:" + str,endsWith(“e")); } }[/code] The output of the above program will be Ends with character ‘e’: true You May Like: 

Some Important Points about String Class

Apart from the above-listed characteristics and methods there are some other facts associated with the String class like it is a final class and that’s why the String class objects are called immutable objects. For String objects, a special memory area is reserved by JVM, which is called String constant pool. You can find the String class of Java in java.lang. In the String library, you can override the String references but the content or literals are not copied.  Any number closed in double quotes also becomes a string and multiple references can be created for the same string.  The String is one of the most used and dynamic classes of Java. There are many functions in the String class which is beneficial for the developers of Java.

Read: How to Convert Char to Int in Java

    Janbask Training

    JanBask Training is a leading Global Online Training Provider through Live Sessions. The Live classes provide a blended approach of hands on experience along with theoretical knowledge which is driven by certified professionals.


Trending Courses

AWS

  • AWS & Fundamentals of Linux
  • Amazon Simple Storage Service
  • Elastic Compute Cloud
  • Databases Overview & Amazon Route 53

Upcoming Class

2 days 14 Dec 2019

DevOps

  • Intro to DevOps
  • GIT and Maven
  • Jenkins & Ansible
  • Docker and Cloud Computing

Upcoming Class

3 days 15 Dec 2019

Data Science

  • Data Science Introduction
  • Hadoop and Spark Overview
  • Python & Intro to R Programming
  • Machine Learning

Upcoming Class

3 days 15 Dec 2019

Hadoop

  • Architecture, HDFS & MapReduce
  • Unix Shell & Apache Pig Installation
  • HIVE Installation & User-Defined Functions
  • SQOOP & Hbase Installation

Upcoming Class

4 days 16 Dec 2019

Salesforce

  • Salesforce Configuration Introduction
  • Security & Automation Process
  • Sales & Service Cloud
  • Apex Programming, SOQL & SOSL

Upcoming Class

-1 day 11 Dec 2019

QA

  • Introduction and Software Testing
  • Software Test Life Cycle
  • Automation Testing and API Testing
  • Selenium framework development using Testing

Upcoming Class

8 days 20 Dec 2019

Business Analyst

  • BA & Stakeholders Overview
  • BPMN, Requirement Elicitation
  • BA Tools & Design Documents
  • Enterprise Analysis, Agile & Scrum

Upcoming Class

4 days 16 Dec 2019

SQL Server

  • Introduction & Database Query
  • Programming, Indexes & System Functions
  • SSIS Package Development Procedures
  • SSRS Report Design

Upcoming Class

4 days 16 Dec 2019

Comments

Search Posts

Reset

Receive Latest Materials and Offers on Java Course

Interviews