Strings in Java

Strings in Java

  • Strings in Java are Objects that are backed internally by a char array. 

  • Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created

  • Syntax:

  • <String_Type> <string_variable> = “<sequence_of_string>”;

Example:-


    String str = "hii"; 

Memory allotment of String:-

  • Whenever a String Object is created, two objects will be created- one in the Heap Area and one in the String constant pool and the String object reference always points to heap area object.





Example:-

String str = "hii";

Example:-


// Java code to illustrate String

  

import java.io.*;

import java.lang.*;

  

class Test {

    public static void main(String[] args)

    {

        // Declare String without using new operator

        String s = "welcome";

  

        // Prints the String.

        System.out.println("String s = " + s);

  

        // Declare String using new operator

        String s1 = new String("welcome");

  

        // Prints the String.

        System.out.println("String s1 = " + s1);

    }

}

 

Output:

String s = welcome

String s1 = welcome

Interfaces and Classes in Strings in Java

Char Buffer:This class implements the Char Sequence interface. This class is used to allow character buffers to be used in place of Char Sequences. An example of such usage is the regular-expression package java.util.regex. 

String:String is a sequence of characters. In java, objects of String are immutable which means a constant and cannot be changed once create

Creating a String (There are two ways to create string in Java)

 

String literal:-                            String s = “welcome ”;

Using new keyword:-                String s = new String (“welcome”);

String obj=new String(“”); 

String s=”Hii”;

 String str =new String(“Welcome”); 

 Method in String class

  1. Length -str.length()-  length & String 

  2. INDEXof - indexof(str)  -indexvalue & first char in string

  3. CHARAT - str.charAt(index)-char at given index

  4. Replace-str.replace(old string,new string)

  5. To lower case- str.toLowerCase()

  6. Upper case -str.toUpperCase()

  7. Compareto  str.comparezto(str)     “  hiii   “

  8.  str. trim()

  9. str.concat(str)

     

 

 

 


 

 

 

 

 

 



Comments

Popular posts from this blog

Java Package

Life cycle of a Thread and creating thread class

Inheritance in Java