Java String: From Basics To Advance

Java String: From Basics To Advance

Here, we are going to discuss –

  • What is String?
  • String declaration
  • String Initialization
  • String declaration and initialization in a single line
  • Multiple strings in a single line
  • String Class
  • Difference Between String s = new String("codemeright") and String s = "codemeright"
  • Most used String functions

 

What is String?

A String in Java is a sequence of characters enclosed in double quotes. These are also called string literals.

For Example:  "Winter is coming!" or "This is simply a boring example of another string literal"

 

String Declaration

We have primitive data types to hold numeric, boolean and character literals. But sometimes we need to hold a string literal into a variable during the execution of a program. For example, The name of the user who has logged into the system, say 'John Doe' to print it on the screen. To store string literals we need string variable and we can declare a string variable using String keyword as shown below. A String variable shares the same naming convention as any other variable in java. It can only start with a-z, A-Z, _ (Underscore) and $ (Doller) and can only contain a-z, A-Z, 0-9 and _ (Underscore) and $ (Doller). Let us take a look at some valid and invalid String declarations –

String codemeright; (Correct)

String Codemeright; (Correct)

String CodeMeRight; (Correct)

String CodeMeRight38; (Correct)

String _codemeright; (Correct)

String code_me_right; (Correct)

String cmr49; (Correct)

String 49cmr; (Incorrect)

String $cmr; (Correct)

String cmr$; (Correct)

String &cmr; (Incorrect)

String cmr&; (Incorrect)

Note: Variables in Java are case-sensitive. It means cmr, cMr and Cmr are three different variables in java.

 

String Initialization

Once we declared a string variable, we can assign it a string literal of any size. This is called string initialization.

String s;

s = "I love you Java, will you marry me?";

Well, that was a pretty stupid example but I am sure you get my point. Another thing to point out here that we can also initialize a string variable using the new keyword.

String s;

s = new String("No disguise is better than Clark Kent’s lame glasses");

This initialization has its own disadvantage. We will see an explanation for this below.

 

String declaration and initialization in a single line

A string variable can be declared and initialized in a single line as follows –

String s = "This is a sample text";

 

Multiple strings in a single line

Multiple strings can be declared in the same line as follows –

String x, y, z;

Multiple strings can be initialized in the same line as follows –

x = y = z = "Code Me Right";

Multiple strings can be declared and initialized in a single line as follows –

String x = "Code", y = "Me", z = "Right";

 

String Class

String is a java class present in java.lang package. This class can be used to create a string object using the new keyword.

For example:

String s = new String("This is a simple string");

String Class Constructors

public String();

String s1 = new String(); //Empty

 

public String(String original);

String s2 = new String("cmr"); //cmr

 

public String(StringBuilder builder)

String s3 = new String(new StringBuilder("cmr")); //cmr

 

public String(StringBuffer buffer);

String s4 = new String(new StringBuffer("cmr")); //cmr

 

public String(byte[] bytes);

String s5 = new String(new byte[]{99, 109, 114}); //cmr

 

public String(char value[]);

String s6 = new String(new char[]{'c', 'm', 'r'}); //cmr

 

public String(byte bytes[], String charsetName);

String s7 = new String(new byte[]{99, 109, 114}, "UTF-8"); //cmr

 

public String(byte[] bytes, Charset charset);

String s8 = new String(new byte[]{99, 109, 114}, Charset.forName("UTF-8")); //cmr

 

public String(byte bytes[], int offset, int length);

String s9 = new String(new byte[]{99, 109, 114},1, 2); //mr

 

public String(char value[], int offset, int count);

String s10 = new String(new char[]{'c', 'm', 'r'},1, 2); //mr

 

public String(int[] codePoints, int offset, int count);

String s11 = new String(new int[]{99, 109, 114},1, 2); //mr

 

public String(byte bytes[], int offset, int length, String charsetName);

String s12 = new String(new byte[]{99, 109, 114},1, 2, "UTF-8"); //mr

 

public String(byte bytes[], int offset, int length, Charset charset);

String s13 = new String(new byte[]{99, 109, 114},1, 2, Charset.forName("UTF-8")); //mr

 

Difference Between String s = new String("codemeright") and String s = "codemeright"

We have seen above that a string object can be created in two ways –

First is,

String s = "Code Me Right";

And second is,

String s = new String(“Code Me Right”);

But, Are these two initializations are same?

No, these two initializations are different. When a string is created with the first method then the JVM creates only one string object in SCP (String Constant Pool) Memory Area.

But, when a string is created using the second method then the JVM creates two objects. One in Heap Memory Area and one in SCP Memory Area.

The object present in Heap Memory Area is used for the current variable and the object created in SCP Memory Area is stored for future use.

Next time when JVM has to create a string object in SCP it first checks if an object with the same content already exists. If the same required object exists then JVM use that object otherwise it creates a new object. 

 

Most used String functions

1. trim

This function is used to remove leading and trailing extra spaces from a string.

package com.codemeright.string;

public class Trim {
    public static void main(String[] args) {
        String str = "     I am John Snow   ";
        
        System.out.println("A String with extra spaces : ");
        System.out.println(str + ".");
        
        System.out.println("That string after removing spaces : ");
        System.out.println(str.trim() + ".");
    }
}

OUTPUT

A String with extra spaces : 
     I am John Snow   .

That string after removing spaces : 
I am John Snow.

2. toUpperCase

This function is used to convert each and every character of a string to upper case.

package com.codemeright.string;

public class ToUpperCase {
    public static void main(String[] args) {
        String str = "I am John Snow";
        
        System.out.println("A String in default case : ");
        System.out.println(str);
        
        System.out.println("That string in upper case : ");
        System.out.println(str.toUpperCase());
    }
}

OUTPUT : 

A String in title case : 
I am John Snow

That string in upper case : 
I AM JOHN SNOW

3. toLowerCase

This function is used to convert each and every character of a string to lower case.

package com.codemeright.string;

public class ToLowerCase {
    public static void main(String[] args) {
        String str = "I am John Snow";
        
        System.out.println("A String in default case : ");
        System.out.println(str);
        
        System.out.println("That string in lower case : ");
        System.out.println(str.toLowerCase());
    }
}

OUTPUT : 

A String in default case : 
I am John Snow

That string in lower case : 
i am john snow

4. toCharArray

This function is used to create an array of characters present in a string.

package com.codemeright.string;

public class ToCharArray {
    public static void main(String[] args) {
        String bankName = "ICICI";
        String bankNameWithDots = "";
        
        System.out.println("Bank name without dots : ");
        System.out.println(bankName);
        
        System.out.println("Bank name with dots : ");
        for (char ch : bankName.toCharArray()) {
            bankNameWithDots = bankNameWithDots + ch + ".";
        }
        System.out.println(bankNameWithDots);
    }
}

OUTPUT : 

Bank name without dots : 
ICICI

Bank name with dots : 
I.C.I.C.I.

5. substring

This function is used to cut out a part of a string.

package com.codemeright.string;

public class Substring {
    public static void main(String[] args) {
        String str = "CodeMeRight";
        
        System.out.println("Substring of a given string from given begin-index to last");
        System.out.println(str.substring(6));
        
        System.out.println("Substring of a given string from given begin-index(inclusive) to given eng-index(exclusive)");
        System.out.println(str.substring(2, 5));
    }
}

OUTPUT : 

Substring of a given string from given begin-index to last
Right

Substring of a given string from given begin-index(inclusive) to given eng-index(exclusive)
deM

6. startsWith

This function is used to know whether a string starts with a particular sequence of characters or not.

package com.codemeright.string;

public class StartsWith {
    public static void main(String[] args) {
        String name = "Angelina Jolie";
        
        System.out.println("A fullname is : ");
        System.out.println(name);
        
        System.out.println("Is firstname start with 'Ang'?");
        System.out.println(name.startsWith("Ang"));
        
        System.out.println("Is firstname start with 'ang'?");
        System.out.println(name.startsWith("ang"));
        
        System.out.println("Is lastname start with 'Jol'?");
        System.out.println(name.startsWith("Jol", 9));
        
        System.out.println("Is lastname start with 'jol'?");
        System.out.println(name.startsWith("jol", 9));
    }
}

OUTPUT : 

A fullname is : 
Angelina Jolie

Is firstname start with 'Ang'?
true

Is firstname start with 'ang'?
false

Is lastname start with 'Jol'?
true

Is lastname start with 'jol'?
false

7. split

This function is used to split a string.

package com.codemeright.string;

public class Split {
    public static void main(String[] args) {
        String movie = "The-Amazing-Spiderman";
        
        System.out.println("A movie name is : ");
        System.out.println(movie);
        
        System.out.println("Split the movie name with '-'");
        String[] movieName = movie.split("-");
        
        System.out.print("Part 1 : ");
        System.out.println(movieName[0]);
        
        System.out.print("Part 2 : ");
        System.out.println(movieName[1]);
        
        System.out.print("Part 3 : ");
        System.out.println(movieName[2]);
        
        System.out.println("Again, Split the movie name with '-'. But limit the split in two parts only :");
        movieName = movie.split("-", 2);
        
        System.out.print("Part 1 : ");
        System.out.println(movieName[0]);
        
        System.out.print("Part 2 : ");
        System.out.println(movieName[1]);
    }
}

OUTPUT : 

A movie name is : 
The-Amazing-Spiderman

Split the movie name with '-'
Part 1 : The
Part 2 : Amazing
Part 3 : Spiderman

Again, Split the movie name with '-'. But limit the split in two parts only :
Part 1 : The
Part 2 : Amazing-Spiderman

8. replace

This function is used to replace a character or characters from a string.

package com.codemeright.string;

public class Replace {
    public static void main(String[] args) {
        String movie = "The-Amazing-Sipderman-3";
        
        System.out.println("A movie name is : ");
        System.out.println(movie);
        
        System.out.println("Replace each characer 'a' with 'A' : ");
        System.out.println(movie.replace('a', 'A'));
        
        System.out.println("Replace each '-' with space : ");
        System.out.println(movie.replace("-", " "));
        
        System.out.println("Replace every character that is not 'a' with 'A' : ");
        System.out.println(movie.replaceAll("[^a]", "A"));
        
        System.out.println("Replace first '-' with space : ");
        System.out.println(movie.replaceFirst("-", " "));
    }
}

OUTPUT : 

A movie name is : 
The-Amazing-Sipderman-3

Replace each characer 'a' with 'A' : 
The-AmAzing-SipdermAn-3

Replace each '-' with space : 
The Amazing Sipderman 3

Replace every character that is not 'a' with 'A' : 
AAAAAAaAAAAAAAAAAAAaAAA

Replace first '-' with space : 
The Amazing-Sipderman-3

9. matches

This function tells if a string matches a pattern or not.

package com.codemeright.string;

public class Matches {
    public static void main(String[] args) {
        String mobileNo1 = "7905041612";
        String mobileNo2 = "5905041612";
        
        if(mobileNo1.matches("[789][0-9]{9}")) {
            System.out.println(mobileNo1 + " is a valid 10 digit mobile number");
        } else {
            System.out.println(mobileNo1 + " is not a valid 10 digit mobile number");
        }
        
        if(mobileNo2.matches("[789][0-9]{9}")) {
            System.out.println(mobileNo2 + " is a valid 10 digit mobile number");
        } else {
            System.out.println(mobileNo2 + " is not a valid 10 digit mobile number");
        }
    }
}

OUTPUT : 

7905041612 is a valid 10 digit mobile number
5905041612 is not a valid 10 digit mobile number

10. equals

This function tells if one string is equal in value to another string.

package com.codemeright.string;

public class Equals {
    public static void main(String[] args) {
        String name1 = "John Doe";
        String name2 = "john doe";

        System.out.println("Is '" + name1 + "' equal to '" + name2 + "' ?");
        System.out.println(name1.equals(name2));
        
        System.out.println("Is '" + name1 + "' equal to '" + name2 + "' after ignoring the case ?");
        System.out.println(name1.equalsIgnoreCase(name2));
    }
}

OUTPUT : 

Is 'John Doe' equal to 'john doe' ?
false

Is 'John Doe' equal to 'john doe' after ignoring the case ?
true

11. endsWith

This function tells if a string ends with certain sequence of characters or not.

package com.codemeright.string;

public class EndsWith {
    public static void main(String[] args) {
        String name = "John Doe";
        
        System.out.println("Is '" + name + "' ends with 'Do' ?");
        System.out.println(name.endsWith("Oe"));
        
        System.out.println("Is '" + name + "' ends with 'oe' ?");
        System.out.println(name.endsWith("oe"));
    }
}

OUTPUT : 

Is 'John Doe' ends with 'Do' ?
false

Is 'John Doe' ends with 'oe' ?
true

ADVERTISEMENT

About  |  Privacy Policy  |  Disclaimer  |  © Copyright 2018. All Rights Reserved.