×

String Handling Method in Java

What is a String?

Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language.

“String” is a Java platform class that allows you to construct and handle strings.

Creating String:

The normal way of a creating String in Java is to simply write:

String s = “Hello World”;

The compiler constructs a String object with the value "Hello world!" whenever it detects a string phrase in your code.

String objects cannot be made by using the new keyword and a function Object, just like any other object. The String class provides 11 constructors that allow you to set the string's initial value from a variety of sources, including an array of characters.

Another way of a creating String is:

String s = new String (“Hello World”);

Where is String Object stored?

When a string object is generated, it is placed in a pool of Strings known as the String pool, which is then stocked in Java's heap memory.

To be accurate, the Java String class implements three different interfaces: CharSequence, Comparable, and Serializable.

String class is a subclass of the Object class

Because strings are immutable, anytime we change one string a new string is formed. Java provides us with many service classes called StringBuilder and StringBuffer that allow us to generate mutable strings.

As we've seen, String in Java is a class, so it's no surprise that it has a large range of methods connected with it.

String Handling Method

charAt (int index):

This method helps in returning the character value at the particular index.

Example:

public class CharAtSample{
           public static void main(String args[]){
                       String sample = “Hello World”;
                       char ch1 = sample.charAt(1);
                       System.out.println(ch1);
           }
}

Output:

E

equals (Object obj):

This method returns a Boolean value, indicating if the comparing string matches or not.

Example:

public class EqualsSample{ 
           public static void main(String args[]){ 
 
                   String s1="java"; 
                   String s2="java"; 
                   String s3="string"; 
 
                   System.out.println(s1.equals(s2));
                   System.out.println(s1.equals(s3)); 
            }
}

Output:

True
False

compareTo(String certainString):

This is a Comparable interface method that the String class implements. It is used to compare a string to the one currently in use string. As a consequence of the comparison, the method returns a value of 0 or a positive or negative number.

  • When both the strings are equal it returns 0.
  • If string 1st is less than string 2nd it returns negative.
  • If string 1st is greater than string 2nd it returns positive.

Example:

public class CompareToSample{ 
           public static void main(String args[]){ 
           String s1="string "; 
           String s2="string"; 
           String s3="ring"; 
           String s4="swing"; 
 
           System.out.println(s1.compareTo(s2));
           //0 because both are equal 
 
           System.out.println(s1.compareTo(s3));
           //1 because "s" is 1 time greater than "r"
 
           System.out.println(s1.compareTo(s4)); 
           // -3 because "t" is 3 times lower than "w"
           }
 }

Output:

0
1
-3

Length():

This method returns an integer value that shows the full length of the String.

Example:

public class EqualsSample{ 
         public static void main(String args[]){ 
 
                 String s1="helloworld "; 
                 String s2="hello";  
 
                 System.out.println(s1.length()); 
                 // 10 is the length of helloworld string
 
                 System.out.println(s2.length()); 
                 //5 is the length of hello string
          }
}

Output:

10
5

replace(char oldLetter, char newLetter) :

This method returns a new string in which the old character is replaced by the new character in all of the string's occurrences.

Example:

public class EqualsSample{ 
          public static void main(String args[]){ 
 
                   String s1="swap";
                   String s2 = replace(“w”,”n”); 
 
                   System.out.println(s2);
          }
}

Output:

Snap

toLowerCase():

This method changes all the characters in the strings into lowercase.

Example:

public class ToLowerCaseSample{ 
            public static void main(String args[]){ 
 
                  String s1="HELLO WORLD"; 
                  String s2 = s1.toLowerCase(s1);
 
                  System.out.println(s2);
            }
}

Output:

hello world

toUpperCase():

This method changes all the characters in the strings into upper case.

Example :

public class ToUpperCaseSample{ 
           public static void main(String args[]){ 
 
                  String s1="helloworld "; 
                  String s2 = s1.toUpperCase(s1);
 
                  System.out.println(s2);
           }
 }

Output:

HELLOWORLD

concat(String newString):

This produces a new concatenated string with a new string appended to the end of the previous one. The mark on a string is the new string.

Example:

public class ConcatSample{ 
          public static void main(String args[]){ 
 
                   String s1="Welcome to"; 
                   String s2 =”my world”;
                   String s3 = s1.concat(s2);
                    
                   System.out.println(s3);
           }
}

Output:

Welcome to my world

trim():

This function produces a string that is devoid of the leading and following whitespaces found in the original string.

Example:

public class TrimSample{ 
            public static void main(String args[]){ 
 
                  String s1="      My name is          ";  
 
                  System.out.println(s1 +”:Thomson”);
                  System.out.println(s1.trim() +”:Thomson”);
             }
}

Output:

My name is          :Thomson
My name is Thomson

split():

After breaking the input string against the specified regular expression, this method provides a character array.

Example:

public class SplitSample{ 
         public static void main(String args[]){ 
 
                String s1="Hey I Am John"; 
                String [] s2 = s1.split(“\\s”); 
                //splits based on whitespace
 
                 for(String word: s2){
                          System.out.println(s2);
                 }
          }
}

Output:

Hey
I
Am
John

valueOf():

This method converts several types to String, such as integer to string, long to string, Boolean to string, float to string, and so on.

Example:

public class ValueOfSample{ 
         public static void main(String args[]){


                float value = 89;
                String s1 = String.valueOf(value);
 
                System.out.println(s1+”%”); 
                //concatenating the obtained string
          }
}


Output:

89%

These are the various types of String handling program methods in Java. The String class isn't limited to the methods listed above; it contains a slew of other handy methods that can make programming a breeze.


Related Topics

The final Keyword in Java

The final keyword is employed in several instances. Firstly, the non-access modifier final only applies to variables, methods, and classes. The final can be used in the following situations. Final Variables When...

6 minutes read.

Difference between String, StringBuffer and StringBuilder in java

What is a string in Java? Strings are a collection of characters that are commonly used in Java programming. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Process and Thread in Java

Process It is a program that is running on your computer. The process is a heavy-weight, which takes memory separately to other processes. The process may be a small background task like spell-checker; it...

11 minutes read.

Quick Sort in Java

Quick Sort in Java Like merge sort, quick sort also uses the divide and conquer approach to sort the given array or list. In quick sort, the sorting of an array...

6 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.

Java Program to generate binary numbers

A binary tree can create binary numbers ranging from 1 to n. Every node in a tree, the right, and left nodes, has two children, as is common knowledge. The...

3 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Tilt operator in Java | Tilde operator in Java Example

The symbol designates it as a unary operator (pronounced as the tilde). It gives back the bit's complement or inverse. Every 0 turns into a 1, and every 1 back...

3 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Addition Program in Java

Addition Program in Java We can perform the addition (sum) of two or more numbers by using the arithmetic operator (+). To write an addition program in Java, one must understand...

3 minutes read.

Java Binary Operators

In this article, we are going to discuss about the binary operators in Java and their operations. Also, an example program will be discussed along with the operations. These are...

6 minutes read.

Singleton Design Pattern in Java

In the singleton pattern, a class that only has one instance and offers a universal point of access is taken into consideration. It can also be defined in another way, a...

4 minutes read.

Time Class Operation in Java

The Java SQL package includes the time class. This class is merely a lightweight wrapper for java. util. THANKS TO THE recognize BC API can recognize this as a SQL...

3 minutes read.

Java Logo

Java is a prominent and extensively used object-oriented programming language. In 1995, Sun Microsystems created it. Later in 2009, Oracle Corp takeover Java. History of Java Logo The name of the island...

3 minutes read.

JIT in Java

What is JIT ? JIT stands for " Just in Time Compiler ". It is called "Just in time" because it is called at the very last moment when the interpretation...

5 minutes read.

How to convert String to String array in Java

A String in Java is a thing that indicates a collection of letters. We must include the String class from java.lang package if we want to be using strings. An...

5 minutes read.

Java Interface Lock

A synchronisation method called the Lock interface is available as of JDK 1.5. It is comparable to a synchronised block but more complex and versatile. The package java.util.concurrent contains the...

4 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Difference between JDK, JRE and JVM In Java

In the Java ecosystem, three primary components are often mentioned: JDK, JRE, and JVM. Here’s a breakdown of each: Java Development Kit (JDK) The Java Development Kit (JDK) is a comprehensive software...

2 minutes read.

Byte to Hex in Java

Java exclusively uses byte data types to store in a byte array, which is an array. Each component of a byte array has a default value of 0. Hex String -...

3 minutes read.