String in Java Example

String in Java Example

String is a combination of character combined together. Java implement string as an object which make handling of string convenient. Java provides various methods, which makes handling of String as object easy, we’ll see them all going futher.

A String created is immutable, which is no hurdle in performing operation provided by Java on it. Every time an operation is performed on string object, a new string object is created with modifications and assigned to it.

This can be overcome by use of mutable string type StringBuilder or StringBuffer.

String Constructor:

String str= new String();

This is used to create an empty instance of string.

String str= new String(char charsval[]);

This used to create an string with string characters defined in charsval. The resultant output will be concatenated characters. Let’s see an example

char chars[]={'a','b','c'};

String str=new String(chars);


This will initialize str with string “abc”.

String str= String(char chars[ ], int startIndex, int numChars):

This will initialize string object str with characters defined in chars with starting and number of characters followed by it.


char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };

String str = new String(chars, 2, 3);


This will initialize the string object str with “cde”.

String str=new String(Sting StrObj);

This will initialize the str with string object stored in StrObj.

String length:

This will return the number of characters in string object on which the function has been called.

String str=new String("abcde");
System.out.println("String lenght is" str.length());

str.length will return 5.

String literals:

String literals are a way by which string object can be initialized.

String str="abc"; // String literal

String methods can also be called directly on string literals as: “abc”.length(), this will return to be 3, which exactly the same as in case of string object.

String Concatenation:

Java doesn’t allow any operator to be applied on String object. However it has exception for ‘+’ operator which is used for concatenation of two string.

String str= "Welcome to "+" code2succeed.";

Above example demonstrate the concatenation of string literals; this method can also be applied on concatenation of other data types with string.

int number= 90;
String str="You've scored " +number+ " out of 100";


You’ve scored 90 out of 100

Here in this internal mechanism convert the data type of number to string while concatenation with string literals.

String Conversion and toString( )

We saw in above example, a data of type int is converted to String type when concatenating with data of type string. This is done by overloaded method defined by String.valueof(). For simple data type, this method converts them to type String and returns human readable string. But for type object, it calls toString method.

Every class implements toString methods and it can be overridden to provide our own implementation.

Signature of toString method:

String toString()

Let’s see an example to demonstrate how this can achieved.

Main Class file:

public class ToStringExample {

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		toStringDetails detail=new toStringDetails("Code2Succeed",".com");	
		System.out.println("String returned from toString method is "+ detail);

Class file:

public class toStringDetails {

		String fname=new String();
		String lname=new String();

		toStringDetails(String fname,String lname){
			this.fname= fname;
		public String toString(){
			return "Welcome to "+ fname+ lname;


Welcome to

String returned from toString method is Welcome to


We kicked off understanding of string that it is easy to handle string as object as it provides various methods which makes it easy to handle. Below are the listed methods which can be used on String-

  • charAt( )

    This can be used to extract a single character from given string at specified index location.

    Its signature is defined as-

    char charAt(int where);


    char ch="abc".charAt(1);
    System.out.println("Character at index location 1 is: "+ch);


    Character at index location 1 is: b

  • getChars( )

    This is used to extract more than one character at a time. It signature is defined as-

    void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)


    sourceStart, sourceEnd- This used to specify the start and end index from where characters are required to be extracted. The characters are extracted from sourceStart and sourceEnd-1 index location.

    target[]: This is the array defined in which characters will be stored. One must ensure that it’s size matches the length of characters.

    targetStart: This specifies the index location in target array, starting where the characters will be copied.


    public class getCharsExample {
    	public static void main(String[] args) {
    		String str="Welcome to Help you grow";
    		int startIndex=10;
    		int endIndex=27;
    		char[] targetArray=new char[endIndex-startIndex];
    		int targetArrayStartindex=0;


  • toCharArray( )

    This method is used to convert all characters in a string object to character array. It always return an array of character for the string on which this method has been called.


    char[ ] toCharArray( )


    String str="Welcome to";
    Char[] ch= str.toCharArray();

    This will convert the str of type string into character array.

  • equals( )

    This will compare two given string return true or false depending upon if content is same or not. This method also considers letter case i.e. will return false if two string only differentiate capital case or letter case.


    boolean equals(Object str)

    String s1="hello";
    String s2="Welcome";
    String s3="HELLO";
    String s4="hello";
    //This will return false.
    //This will return false, as both differ by letter type case i.e. small case and capital case.
    //This will return true, as both the string are equal.


  • equalsIgnoreCase( )

    This is same perform same as equals() method except for letter case differentiation. This will ignore the difference of small or capital case.


    boolean equalsIgnoreCase(String str)


    String s1="hello";
    String s2="HELLO";
    System.out.println("s1.equalsIgnoreCase( s2)");


  • regionMatches( )

    This method is used to compare specific region inside the given string with specified start index and number of characters to be compared.


    boolean regionMatches(int startIndex, String str2,int str2StartIndex, int numChars)

    boolean regionMatches(boolean ignoreCase,int startIndex, String str2,int str2StartIndex, int numChars)

  • startsWith( ) and endsWith( )

    This method returns true if the string on which this function has been called starts or ends with specified string.


    "Welcome to code2succeed".startsWith("Welcome");

    This will return true, if given string starts with Welcome and if not then return false. Similar is the case with endWith().

Leave a Reply

Your email address will not be published. Required fields are marked *