Saturday, 16 May 2015

String Handling in Java_1

What is String in Java?
  •      It is an object of type String.
  •           String is a sequence of characters.
  •      String is immutable.

Following are the different constructors provided by Java to create String.
  •      Create an empty String.

                 String str = new String ();
  •  Create a String by passing String object as constructor argument.

String str = new String (String strObj);
  •              Create a String initialized by an array of character.

String str = new String (char ch[]);
  •       Creating String by String Literal way.

String str = “JAVA”;

Example Program:

package com.string.handling;
// Package is container of similar classes and interfaces etc.

public class MyFirstString
   public static void main(String[] args)
       String str1=new String(); // empty string object is created.
       // another way of string creation.
       char ch[] = {'J','A','V','A'};
       String str2=new String(ch); //String initialized by character array.
       //initializing with String object.
       String str3=new String(str2);
       //assigning one string to other.
       // creating string literal.
       String str4="JAVA";
       System.out.println("Empty String output: "+str1);
       System.out.println("String initialized by charater: "+str2);
       System.out.println("String initialized by String object: "+str3);
       System.out.println("String Literal: "+str4);

Note: String is immutable. Once string is created you cannot change it.

There are two ways by which String can be created:

  •            By New Keyword.
  •            By String Literal.

// Stay tuned to explore difference between new keyword usage and String Literal.