Monday, January 14, 2019

String in Java

String in Java

String is immutable i.e It cannot be changed but a new instance is created.
In Java,String is an object that represent a sequence of characters.
String is a final class in java.lang package which is used to represent the set of characters in java.
String is a derived type.

Two ways to create String object.

1.By String literal
2.By new Keyword

1.By String Literal


String s1="Welcome"
String s2="Welcome" // will not create new instance



Each time you create a string literal,the JVM check the string constant pool first.If the string already
exits in the pool,A reference to the pooled instance is returned.

If the string doesn't exist in the pool,a new string instance is created and placed in the pool.


- To make Java memory efficient (no new objects are created if it exists in the string constant pool.



2.By new Keyword

String s=new String("Welcome");//creates two objects and one reference variables.
In such case, JVM will create a new string object in normal(non-pool) heap memory and
the literal "Welcome" will be placed int the String constant pool.

-The variable (s) will refer to the object in the heap(non-pool)

Immutable String in java

-In Java,string object are immutable
-Immutable means unmodified or unchangeable
-Once string object is created its data or state can't changed but new string object is created.


String s="Sachin"
s.concat("Tendulkar");
S.O.P(s)//Sachin




- Here Sachin is not changed but a new object is created with Sachin Tendulkar
- Reference variable(s) still refer to Sachin ( not to Sachin Tendulkar)


Why Strings object is immutable in java ? 

Java used the concept of String Literal,there are 5 reference variables ,all refers to one object Sachin.

-If the reference variables changes the values of object,it will be affected to all reference variables.That is why String objects are immutable in java.

String comparison in java

3 ways to compare String object

1.By equals() method
2.By == operator ( Reference matching )
3.By compareTo() method

1. By equals() method

It compares values of string for equality


package com.test;

public class Test {

       public static void main(String[] args) {
             String s1="Ram";
             String s2="Ram";
             String s3=new String("Ram");
             String s4="Dev";
            
             System.out.println(s1.equals(s2));//True
             System.out.println(s1.equals(s3));//True
             System.out.println(s1.equals(s4));//False
            
       }

}



2. By == operator ( Reference matching )

== operator compares references not values.


package com.test;

public class Test {

       public static void main(String[] args) {
             String s1="Ram";
             String s2="Ram";
             String s3=new String("Ram");
                          
             System.out.println(s1==s2);//True
             System.out.println(s1==s3);//False because s3 refers to instance created in the non-pool
            
            
       }

}


intern()

It can be used to return string from memory, if it is created by new keyword. It creates exact copy of heap string object in string constant pool.


package com.test;

public class Test {

       public static void main(String[] args) {
             String s1 = "Ram";
             String s2 = new String("Ram");

             System.out.println(s1 == s2);// False

             String s3 = s2.intern();

             System.out.println(s1 == s3);// True

       }

}



3.By compareTo() method 


compareTo() method compares values and return an int which tells if the values compare less than,equal or greater than

S1==S2:0
S1>S2: Positive(1)
S1<S2: Positive(-1)


package com.test;

public class Test {

       public static void main(String[] args) {
             String s1 = "Ram";
             String s2 = "Ram";
             String s3 = "Sita";

             System.out.println(s1.compareTo(s2));// 0
             System.out.println(s1.compareTo(s3));// 1
             System.out.println(s3.compareTo(s1));// -1

       }

}



How will you create an immutable class in java?

You can create immutable class in java by implementing below points:

1. Make the class final so it can not be extended(inherited)
2. Make all fields private so one can not access them from outside the class.
3. Do not provide setter methods for the variables.
4. Declare all mutable fields as final so that it's value can be assigned only once.

   public final class Student{ 
    final String cardNumber; 
     
    public Student(String cardNumber){ 
    this.cardNumber=cardNumber; 
    } 
     
    public String getcardNumber(){ 
    return cardNumber; 
    } 
     
    }  


Why char Array is preferred over String in storing passwords?

One of the main reason to prefer char Array over String is security risk of stealing passwords. Since String are reusable in the constant pool , there are high chances that they remain in the memory for the long duration. Anyone who has access to the memory dump can find the password in clear text.
That's why password should be encrypted.

0 comments:

Post a Comment