String In Java

A String can be called as a sequence of characters but, a String In Java is an object that represents a sequence of characters. The java.lang.String class is used to create string object. It is the most extensively used class in Java. It can store the maximum of 2 billion characters (256 KB).

 

StringInJava

There are two ways to create a String object

  • By string literal
      • Java String literal is created by using double quotes
        For Example: String str =“Welcome”;
  • By new keyword
    • Java String is created by using a keyword “new”
      For Example: String str =new String(“Welcome”);
      It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap

Java String Constructors

  • String()
  • String(String)
  • String(char[], int stindex, int num)
  • String(byte[], int stindex, int num)

Now let’s understand them with the help of an example

  • String s1 = new String();                     // Declaration of a new String
  • String s2 = new String(“Welcome”)
  • char c[] = {‘W’,’e’,’l’,’c’,’o’,’m’,’e’};
  • String s3 = new String(c,3,4);          //output will be  (‘come’)
  • byte b[] = {65,66,67,68,69,70};
  • String s4 = new String(b,0,5);          //output will be   (‘ABCDE’)

Java String Methods

  • String length(): It tells the length of the string and returns the count of a total number of characters present in the String.

For Example

public class Example{
public static void main(String args[]) { 
String s1 = "hello"; 
String s2 = "Welcome"; 
System.out.println("String length is : "+s1.length()); 
System.out.println("String length is : "+s2.length());

Here, String length()  function will return the length 5 for s1 and 7 for s2 respectively

  • String compareTo(): It compares the given string with current string. It either returns the positive number, negative number or Zero.

For Example

public class CompareToExample{
public static void main(String args[]){
String s1 = "hello";
String s2 = "hello";
String s3 = "world";
String s4 = "Adios";
System.out.println(s1.compareTo(s2));     // 0 because both are equal
System.out.println(s1.compareTo(s3));     // -10 because "l" is 10 times lower than "w"
System.out.println(s1.compareTo(s4));     // 7 because "h" is 7 times greater then "A"
}
}
  • Java String concat(): It combines a specific string at the end of another string and ultimately returns a combined string.

For Example

public class ConcatExample{public static void main(String args[]){
String s1 = "Hello";
s1 = s1.concat(" "+"Welcome to P3lang");
System.out.println(S1);
}}

The above code returns “Hello Welcome to P3lang”
  • String IsEmpty(): This method checks whether the String contains anything or not. If the java String is Empty, it returns true else false.

For Example

public class IsEmptyExample{
public static void main(String args[]){
String s1 = "";
String s2 = "hello";
System.out.println(s1.isEmpty());           //true
System.out.println(s2.isEmpty());           //false
} }
  •  Java String Trim(): It removes the leading and trailing spaces and also checks the Unicode value of space character (‘\u0020’) before and after the string. If it exists, then removes the spaces and return the omitted string.

For Example

public class StringTrimExample{
public static void main(String args[]){
String s1 = "  hello  ";
System.out.println(s1+ "Welcome to p3Lang");                  //without trim()
System.out.println(s1.trim()+ "Welcome to p3Lang");          //without trim()

In the above code, the first print statement will print “hello Welcome to p3Lang” while the second statement will print “helloWelcome to p3Lang” using the trim() function.

  • Java String toLowerCase(): It converts all the characters of the String to lower case.

For Example

public class StringLowerExample{
public static void main(String args[]){
String s1= "HELLO WelCoMe To p3LanG";
String s1lower= s1.toLowerCase();
System.out.println(s1lower);}
}

The above code will return “hello welcome to p3lang

  • Java String toUpper(): It converts all the characters of the String to upper case.

For Example

public class StringUpperExample{
public static void main(String args[])
{
String s1= "HEllo WelCoMe To p3LanG";
String s1upper= s1.toUpperCase();
System.out.println(s1upper);}
}

The above code will return “HELLO WELCOME TO P3LANG”.

  • Java String ValueOf(): It converts different types of values into a string. Here you can convert int to string, long to string, Boolean to string, character to string, float to a string, double to a string, object to string and char array to string. The signature or syntax of string valueOf() method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

Let’s understand this with a programmatic example:

public class StringValueOfExample{
public static void main(String args[]){
int value = 2025;
String s1 = String.valueOf(value);
System.out.println(s1+2520);               //concatenating string with 10

In the above code, it concatenates the Java String and gives the output – 2017 

  • Java String replace(): It returns a string, replacing all the old characters or CharSequence to new characters.

For Example

public class ReplaceExample{
public static void main(String args[]){
String s1 = "Hello Welcome to P3Lang";
String replaceString= s1.replace( 'H' , 'T' );
System.out.println(replaceString);}}

In the above code, it will replace all the occurrences of ‘H’ to ‘T’. Output to the above code will be “Tello Welcome to p3Lang”.

  • Java String contains(): It searches the sequence of characters in the string. If the sequences of characters are found, then it returns true otherwise returns false.

For Example

class ContainsExample{
public static void main(String args[]){
String name = "Welcome to P3Lang";
System.out.println(name.contains("P3Lang"));                // returns true
System.out.println(name.contains("Welcome"));            // returns true
System.out.println(name.contains("page"));                    // returns false

In the above code, the first two statements will return true as it matches the String,
whereas the second print statement will return false because the characters are not present in the string.

  • Java String equals(): The Java String equals() method compares the two given strings on the basis of the content of the string i.e Java String representation. If all the characters are matched, it returns true else it will return false.

For Example

public class EqualsExample{
public static void main(String args[]){
String s1 = "Welcome";
String s2 = "Welcome";
String s3= "Hello";
System.out.println(s1.equalsIgnoreCase(s2));        //returns true
System.out.println(s1.equalsIgnoreCase(s3));       //returns false
}
}
  • String equalsIgnoreCase(): It compares two string on the basis of content but it does not check the case like equals() method. In this method, if the characters match, it returns true else false.

For Example

public class EqualsIgnoreCaseExample{
public static void main(String args[]){
String s1 = "Welcome";
String s2 = "Hello";
String s3 = "hello";
System.out.println(s1.equalsIgnoreCase(s2));        //returns false
System.out.println(s2.equalsIgnoreCase(s3));        //returns true

In the above code, the first statement will return true because the content is same irrespective of the case.
Then, in the second print statement will return false as the content doesn’t match in the respective strings.

  • String toCharArray(): This method converts the string into a character array i.e first it will calculate the length of the given Java String including spaces and then create an array of char type with the same content.

For Example

StringToCharArrayExample{
public static void main(String args[]){
String s1 = "Welcome to P3Lang";
char [ ] ch = s1.toCharArray();
for( int i=0;i
System.out.println(ch[i]);
}}}

The above code will return “Welcome to p3Lang”.

  • String IsEmpty(): It checks whether the String is empty or not. If the length of the String is 0, it returns true else false.

For example

public class IsEmptyExample{
public static void main(String args[]) {
String s1="";
String s2="welcome";
System.out.println(s1.isEmpty());          //returns true
System.out.println(s2.isEmpty());          //returns false

In the above code, the first print statement will return true as it does not contain anything while the second print statement will return false

  • Java String endsWith(): The Java String endsWith() method checks if this string ends with the given suffix. If it returns with the given suffix, it will return true else returns false.

For example

public class EndsWithExample{
public static void main(String args[]){
String s1 = "Welcome to p3Lang";
System.out.println(s1.endsWith("g"));                  //returns true
System.out.println(s1.endsWith("p3Lang"));      //returns true
System.out.println(s1.endsWith("to"));                //returns true

 

 

 

 

 

Check out Some java programs on String from P3Lang Git

 

Frequently asked questions on Strings In Java

Immutable objects are like constants. You can’t modify them once they are created. They are final in nature. Whereas mutable objects are concerned, you can perform modifications to them.
The equals() method matches the content of the strings whereas == operator matches object or reference of the strings.
String object created by new() operator is by default not added in String pool as opposed to String literal. The intern() method allows putting a String object into a pool.
A string is immutable and final in Java, so whenever we do String manipulation, it creates a new String. StringBuffer and StringBuilder are mutable classes. StringBuffer operations are thread-safe and synchronized where StringBuilder operations are not thread-safe.