Thursday, November 2, 2017

String in Java + Static



STRING
2. What is immutable object? Can you write immutable object?
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String("Test");
 

does not put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. It’s only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.


StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

5.  Write code to find the First non repeated character in the String  ?
Another good Java interview question, This question is mainly asked by Amazon and equivalent companies. See first non repeated character in the string : Amazon interview question

16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java
Today we are going to understand the difference between String , StringBuilder and StringBuffer . As you will find that there are minor differences between the above mentioned classes.

String

String is immutable  ( once created cannot be changed )object. The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String cannot be used by two threads simultaneously.
String  once assigned cannot be changed.

String  demo = " hello " ;
// The above object is stored in constant string pool and its value cannot be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable           
 // "hello" string still exists in string constant pool and its value is not override but we lost reference to the  "hello"string 

StringBuffer

StringBufferis mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
StringBuffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe . 


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder


----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------                
Storage Area | Constant String Pool           Heap                       Heap
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------




Immutable Class Interview Questions

Q1) What is an immutable class?
Ans) Immutable class is a class which once created, it’s contents can not be changed. Immutable objects are the objects whose state can not be changed once constructed. e.g. String class
Q2) How to create an immutable class?
Ans) To create an immutable class following steps should be followed:
  1. Create a final class.
  2. Set the values of properties using constructor only.
  3. Make the properties of the class final and private
  4. Do not provide any setters for these properties.
  5. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    1. Don't provide methods that modify the mutable objects.
    2. Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.
public final class FinalPersonClass { 
    private final String name; 
    private final int age; 
 
    public FinalPersonClass(final String name, final int age) {       
     this.name = name; 
     this.age = age; 
    } 
    public int getAge() { 
      return age; 
    } 
    public String getName() { 
     return name; 
    } 
  }
Q3) Immutable objects are automatically thread-safe –true/false?
Ans) True. Since the state of the immutable objects can not be changed once they are created they are automatically synchronized/thread-safe.
Q4) Which classes in java are immutable?
Ans) All wrapper classes in java.lang are immutable –
String, Integer, Boolean, Character, Byte, Short, Long, Float, Double, BigDecimal, BigInteger
Q5) What are the advantages of immutability?
Ans)
  • Immutable objects are automatically thread-safe, the overhead caused due to use of synchronisation is avoided.
  • Once created the state of the immutable object can not be changed so there is no possibility of them getting into an inconsistent state.
  • The references to the immutable objects can be easily shared or cached without having to copy or clone them as there state can not be changed ever after construction.
  • The best use of the immutable objects is as the keys of a map.
To create immutable class in java, you have to do following steps.
1.      Declare the class as final so it can’t be extended.
2.      Make all fields private so that direct access is not allowed.
3.      Don’t provide setter methods for variables
4.      Make all mutable fields final so that it’s value can be assigned only once.
5.      Initialize all the fields via a constructor performing deep copy.
6.      Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.


package com.Immutable.Again;

public class NonImmutableClass {

private String state;
private String country;


public NonImmutableClass(String state, String country) {
super();
this.state = state;
this.country = country;
}

public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}

@Override
public String toString() {
return "NonImmutableClass [state=" + state + ", country=" + country
+ "]";
}

}
--------------------
package com.Immutable.Again;

public final class ImmutableClass {
private int id;
private String name;
//private NonImmutableClass nonImmutableClass = new NonImmutableClass("Maharastra","India");
private NonImmutableClass nonImmutableClass;
public ImmutableClass(int id, String name,
NonImmutableClass nonImmutableClass) {
this.id = id;
this.name = name;
this.nonImmutableClass = nonImmutableClass;
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public NonImmutableClass getNonImmutableClass() {
return new NonImmutableClass("ABC","DEF");
}

@Override
public String toString() {
return "ImmutableClass [id=" + id + ", name=" + name
+ ", nonImmutableClass=" + nonImmutableClass + "]";
}
}
------------------------
package com.Immutable.Again;

public class ImmutableTest {

public static void main(String[] args) {

ImmutableClass immutableClass = new ImmutableClass(1, "Ali", new NonImmutableClass("Maharasstra","India"));
immutableClass.getNonImmutableClass().setCountry("USA");
System.out.println(immutableClass);
}

}

------------------------

OUTPUT:-

ImmutableClass [id=1, name=Ali, nonImmutableClass=NonImmutableClass [state=Maharasstra, country=India]]


----------------------------------------------
package com.Immutable;

public final class Immutable_for_Test_1 {

private int id = 100;
private String name = "Ali";
private String city;
private String country;
private For_Test_A forA = new For_Test_A(city,country);


public Immutable_for_Test_1(int id, String name, For_Test_A forA) {
super();
this.id = id;
this.name = name;
this.forA = forA;
forA.setCity("Mumbai");
forA.setCountry("India");
}

public int getId() {
return id;
}

public String getName() {
return name;
}

public For_Test_A getForA() {
return new For_Test_A(forA.getCity(),forA.getCountry());
}

@Override
public String toString() {
return "Immutable_for_Test_1 [id=" + id + ", name=" + name + ", forA="
+ forA + "]";
}



}
--------------
package com.Immutable;

public class Immutable_Test_2 {

public static void main(String[] args) {
Immutable_for_Test_1 abc = new Immutable_for_Test_1(100, "Ali", new For_Test_A("abc", "abc"));
abc.getForA().setCity("Delhi");// After change its wont do any effect on city
abc.getForA().setCountry("USA");// After change its wont do any effect on country
System.out.println("OK");
System.out.println();
System.out.println(abc);
System.out.println("id :" + abc.getId());
System.out.println("Name :"+ abc.getName());
System.out.println("City :" + abc.getForA().getCity());
System.out.println("Country :"+ abc.getForA().getCountry());
}

}
--------
OUTPUT:-


OK

Immutable_for_Test_1 [id=100, name=Ali, forA=com.Immutable.For_Test_A@15db9742]
id :100
Name :Ali
City :Mumbai
Country :India


----------------------------------------------------------------------------------------------------
STRING
2. What is immutable object? Can you write immutable object?
Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new() and literal?
When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String("Test");
 

does not put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. It’s only when you create String object as String literal e.g. String s = "Test" Java automatically put that into String pool.


StringBuilder in Java is introduced in Java 5 and only difference between both of them is that Stringbuffer methods are synchronized while StringBuilder is non synchronized. See StringBuilder vs StringBuffer for more differences.

5.  Write code to find the First non repeated character in the String  ?
Another good Java interview question, This question is mainly asked by Amazon and equivalent companies. See first non repeated character in the string : Amazon interview question

16. What is the difference when String is gets created using literal or new() operator ?
When we create string with new() its created in heap and not added into string pool while String created using literal are created in String pool itself which exists in Perm area of heap.

Difference Between String , StringBuilder and StringBuffer Classes with Example : Java
Today we are going to understand the difference between String , StringBuilder and StringBuffer . As you will find that there are minor differences between the above mentioned classes.

String

String is immutable  ( once created cannot be changed )object. The object created as a String is stored in the  Constant String Pool  .
Every immutable object in Java is thread safe ,that implies String is also thread safe . String cannot be used by two threads simultaneously.
String  once assigned cannot be changed.

String  demo = " hello " ;
// The above object is stored in constant string pool and its value cannot be modified.


demo="Bye" ;     //new "Bye" string is created in constant pool and referenced by the demo variable        
 // "hello" string still exists in string constant pool and its value is not override but we lost reference to the  "hello"string

StringBuffer

StringBufferis mutable means one can change the value of the object . The object created through StringBuffer is stored in the heap . StringBuffer  has the same methods as the StringBuilder , but each method in StringBuffer is synchronized that is StringBuffer is thread safe .

Due to this it does not allow  two threads to simultaneously access the same method . Each method can be accessed by one thread at a time .

But being thread safe has disadvantages too as the performance of the StringBuffer hits due to thread safe property . Thus  StringBuilder is faster than the StringBuffer when calling the same methods of each class.

StringBuffer value can be changed , it means it can be assigned to the new value . Nowadays its a most common interview question ,the differences between the above classes .
StringBuffer can be converted to the string by using
toString() method.

StringBuffer demo1 = new StringBuffer("Hello") ;
// The above object stored in heap and its value can be changed .
demo1=new StringBuffer("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuffer

StringBuilder

StringBuilder  is same as the StringBuffer , that is it stores the object in heap and it can also be modified . The main difference between the StringBuffer and StringBuilder is that StringBuilder is also not thread safe. 
StringBuilder is fast as it is not thread safe .


StringBuilder demo2= new StringBuilder("Hello");
// The above object too is stored in the heap and its value can be modified
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the StringBuilder


----------------------------------------------------------------------------------
                                    String                    StringBuffer         StringBuilder
----------------------------------------------------------------------------------              
Storage Area | Constant String Pool           Heap                       Heap
Modifiable     |  No (immutable)            Yes( mutable )          Yes( mutable )
Thread Safe   |           Yes                                  Yes                              No
 Performance |         Fast                                Very slow                    Fast
-----------------------------------------------------------------------------------

A Strategy for Defining Immutable Objects


The following rules define a simple strategy for creating immutable objects. Not all classes documented as "immutable" follow these rules. This does not necessarily mean the creators of these classes were sloppy — they may have good reason for believing that instances of their classes never change after construction. However, such strategies require sophisticated analysis and are not for beginners.
  1. Don't provide "setter" methods — methods that modify fields or objects referred to by fields.
  2. Make all fields final and private.
  3. Don't allow subclasses to override methods. The simplest way to do this is to declare the class as final. A more sophisticated approach is to make the constructor private and construct instances in factory methods.
  4. If the instance fields include references to mutable objects, don't allow those objects to be changed:
    • Don't provide methods that modify the mutable objects.
    • Don't share references to the mutable objects. Never store references to external, mutable objects passed to the constructor; if necessary, create copies, and store references to the copies. Similarly, create copies of your internal mutable objects when necessary to avoid returning the originals in your methods.

String literal and New Object in String

What is String literal pool? How to create a String

There are two ways to create a String object in Java:
·         Using the new operator. For example, 
String str = new String("Hello");.
·         Using a string literal or constant expression). For example,String str="Hello"; (string literal) orString str="Hel" + "lo"; (string constant expression).
What is difference between these String's creations? In Java, the equals method can be considered to perform a deep comparison of the value of an object, whereas the == operator performs a shallow comparison. The equals method compares the content of two objects rather than two objects' references. The == operator with reference types (i.e., Objects) evaluates as true if the references are identical - point to the same object. With value types (i.e., primitives) it evaluates as true if the value is identical. The equals method is to return true if two objects have identical content - however, the equals method in the java.lang.Object class - the default equals method if a class does not override it - returns true only if both references point to the same object.
Let's use the following example to see what difference between these creations of string:
public class DemoStringCreation {



  public static void main (String args[]) {

    String str1 = "Hello";  

    String str2 = "Hello"; 

    System.out.println("str1 and str2 are created by using string literal.");    

    System.out.println("    str1 == str2 is " + (str1 == str2));  

    System.out.println("    str1.equals(str2) is " + str1.equals(str2));  





    String str3 = new String("Hello");  

    String str4 = new String("Hello"); 

    System.out.println("str3 and str4 are created by using new operator.");    

    System.out.println("    str3 == str4 is " + (str3 == str4));  

    System.out.println("    str3.equals(str4) is " + str3.equals(str4));  



    String str5 = "Hel"+ "lo";  

    String str6 = "He" + "llo"; 

    System.out.println("str5 and str6 are created by using string 
   constant expression.");    

    System.out.println("    str5 == str6 is " + (str5 == str6));  

    System.out.println("    str5.equals(str6) is " + str5.equals(str6));



    String s = "lo";

    String str7 = "Hel"+ s;  

    String str8 = "He" + "llo"; 

    System.out.println("str7 is computed at runtime.");                     

    System.out.println("str8 is created by using string constant 
expression.");    

    System.out.println("    str7 == str8 is " + (str7 == str8));  

    System.out.println("    str7.equals(str8) is " + str7.equals(str8));



  }

}
The output result is:
str1 and str2 are created by using string literal.

    str1 == str2 is true

    str1.equals(str2) is true

str3 and str4 are created by using new operator.

    str3 == str4 is false

    str3.equals(str4) is true

str5 and str6 are created by using string constant expression.

    str5 == str6 is true

    str5.equals(str6) is true

str7 is computed at runtime.

str8 is created by using string constant expression.

    str7 == str8 is false

    str7.equals(str8) is true
The creation of two strings with the same sequence of letters without the use of the newkeyword will create pointers to the same String in the Java String literal pool. The String literal pool is a way Java conserves resources.

String Literal Pool

String allocation, like all object allocation, proves costly in both time and memory. The JVM performs some trickery while instantiating string literals to increase performance and decrease memory overhead. To cut down the number of String objects created in the JVM, the String class keeps a pool of strings. Each time your code create a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance returns. If the string does not exist in the pool, a new String object instantiates, then is placed in the pool. Java can make this optimization since strings are immutable and can be shared without fear of data corruption. For example
public class Program

{

    public static void main(String[] args)

    {

       String str1 = "Hello";  

       String str2 = "Hello"; 

       System.out.print(str1 == str2);

    }

}
The result is
true
 Unfortunately, when you use
String a=new String("Hello");
a String object is created out of the String literal pool, even if an equal string already exists in the pool. Considering all that, avoid new String unless you specifically know that you need it! For example
public class Program

{

    public static void main(String[] args)

    {

       String str1 = "Hello";  

       String str2 = new String("Hello");

       System.out.print(str1 == str2 + " ");

       System.out.print(str1.equals(str2));

    }

}
 
The result is
false true

A JVM has a string pool where it keeps at most one object of any String. String literals always refer to an object in the string pool. String objects created with the new operator do not refer to objects in the string pool but can be made to using String's intern() method. The java.lang.String.intern() returns an interned String, that is, one that has an entry in the global String pool. If the String is not already in the global String pool, then it will be added. For example
public class Program

{

    public static void main(String[] args)

    {

        // Create three strings in three different ways.

        String s1 = "Hello";

        String s2 = new StringBuffer("He").append("llo").toString();

        String s3 = s2.intern();



        // Determine which strings are equivalent using the ==

        // operator

        System.out.println("s1 == s2? " + (s1 == s2));

        System.out.println("s1 == s3? " + (s1 == s3));

    }

}
The output is
s1 == s2? false

s1 == s3? true
There is a table always maintaining a single reference to each unique String object in the global string literal pool ever created by an instance of the runtime in order to optimize space. That means that they always have a reference to String objects in string literal pool, therefore, the string objects in the string literal pool not eligible for garbage collection.

String Literals in the Java Language Specification Third Edition


Each string literal is a reference to an instance of class String. String objects have a constant value. String literals-or, more generally, strings that are the values of constant expressions-are "interned" so as to share unique instances, using the method String.intern.
Thus, the test program consisting of the compilation unit:
package testPackage;

class Test {

        public static void main(String[] args) {

                String hello = "Hello", lo = "lo";

                System.out.print((hello == "Hello") + " ");

                System.out.print((Other.hello == hello) + " ");

                System.out.print((other.Other.hello == hello) + " ");

                System.out.print((hello == ("Hel"+"lo")) + " ");

                System.out.print((hello == ("Hel"+lo)) + " ");

                System.out.println(hello == ("Hel"+lo).intern());

        }

}

class Other { static String hello = "Hello"; }
and the compilation unit:
package other;

public class Other { static String hello = "Hello"; }
produces the output:
true true true true false true
This example illustrates six points:
·         Literal strings within the same class in the same package represent references to the same String object.
·         Literal strings within different classes in the same package represent references to the same String object.
·         Literal strings within different classes in different packages likewise represent references to the same String object.
·         Strings computed by constant expressions are computed at compile time and then treated as if they were literals.
·         Strings computed by concatenation at run time are newly created and therefore distinct.
The result of explicitly interning a computed string is the same string as any pre-existing literal string with the same contents.

String strObject =newString("Java");  and

String strLiteral ="Java";
Both expression gives you String object, but there is subtle difference between them. When you create String object using new() operator, it always create a new object in heap memory. On the other hand, if you create object using String literal syntax e.g. "Java", it may return an existing object from String pool (a cache of String object in Perm gen space, which is now moved to heap space in recent Java release), if it's already exists. Otherwise it will create a new string object and put in string pool for future re-use. In rest of this article, why it is one of the most important thing you should remember about String in Java.

What is String literal and String Pool

Since String is one of the most used type in any application, Java designer took a step further to optimize uses of this class. They know that Strings will not going to be cheap, and that's why they come up with an idea to cache all String instances created inside double quotes e.g. "Java". These double quoted literal is known as String literal and the cache which stored these String instances are known as as String pool. In earlier version of Java, I think up-to Java 1.6 String pool is located in permgen area of heap, but in Java 1.7 updates its moved to main heap area. Earlier since it was in PermGen space, it was always a risk to create too many String object, because its a very limited space, default size 64 MB and used to store class metadata e.g. .class files. Creating too many String literals can cause java.lang.OutOfMemory: permgen space. Now because String pool is moved to a much larger memory space, it's much more safe. By the way, don't misuse memory here, always try to minimize temporary String object e.g. "a", "b" and then "ab". Always use StringBuilder to deal with temporary String object.

1.1.1        Difference between String literal and String object

At high level both are String object, but main difference comes from the point that new() operator always creates a new String object. Also when you create String using literal they are interned. This will be much more clear when you compare two String objects created using String literal and new operator, as shown in below example :
String a ="Java";
String b ="Java";
System.out.println(a == b);  // True

Here two different objects are created and they have different references:
String c =newString("Java");
String d =newString("Java");
System.out.println(c == d);  // False

Similarly when you compare a
 String literal with an String object created using new() operator using == operator, it will return false, as shown below :
String e ="JDK";
String f =newString("JDK");
System.out.println(e == f);  // False

In general you should use the
 string literal notation when possible. It is easier to read and it gives the compiler a chance to optimize your code. By the way any answer to this question is incomplete until you explain what is String interning, so let's see that in next section.

String interning using inter() method
Java by default doesn't put all String object into String pool, instead they gives you flexibility to explicitly store any arbitrary object in String pool. You can put any object to String pool by calling intern() method of java.lang.String class. Though, when you create using String literal notation of Java, it automatically call intern() method to put that object into String pool, provided it was not present in the pool already. This is another difference between string literal and new string, because in case of new, interning doesn't happen automatically, until you call intern()method on that object. Also don't forget to use StringBuffer and StringBuilder for string concatenation, they will reduce number

That's all about this question,
 what is difference between String literal and String object in Java. Always remember that literal Strings are returned from string pool and Java put them in pool if not stored already. This difference is most obvious, when you compare two String objects using equality operator (==). That's why it's suggested as always compare two String object using equals() method and never compare them using == operator, because you never know which one is coming from pool and which one is created using new() operator. If you know the difference between string object and string literal, you can also solve questions from Java written test, which also test this concept. It's something, every Java programmer should know. of temporary String object in heap space.

Why String is Immutable in Java ?

1. Requirement of String Pool
String pool (String intern pool) is a special storage area in Java heap. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
2. Security
String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause security problem in Reflection too, as the parameters are strings.

Why String is immutable in Java ?


String is an immutable class in Java. An immutable class is simply a class whose instances cannot be modified. All information in an instance is initialized when the instance is created and the information can not be modified. There are many advantages of immutable classes. This article summarizes why String is designed to be immutable. A good answer depends on the deep understanding of memory, synchronization, data structures, etc.
1. Requirement of String Pool
String pool (String intern pool) is a special storage area in Method Area. When a string is created and if the string already exists in the pool, the reference of the existing string will be returned, instead of creating a new object and returning its reference.
The following code will create only one string object in the heap.
String string1 = "abcd";
String string2 = "abcd";
Here is how it looks:
If a string is not immutable, changing the string with one reference will lead to the wrong value for the other references.
2. Caching Hashcode
The hashcode of the string is frequently used in Java. For example, in a HashMap. Being immutable guarantees that hashcode will always the same so that it can be cashed without worrying the changes.That means, there is no need to calculate hashcode every time it is used. This is more efficient.
In String class, it has the following code:
privateint hash;//this is used to cache hash code.
3. Facilitating the Use of Other Objects
To make this concrete, consider the following program:
HashSet<String> set = new HashSet<String>();
set.add(new String("a"));
set.add(new String("b"));
set.add(new String("c"));
 
for(String a: set)
               a.value = "a";
In this example, if String is mutable, it's value can be changed which would violate the design of set (set contains unduplicated elements). This example is designed for simplicity sake, in the real String class there is no value field.
4. Security
String is widely used as a parameter for many java classes, e.g. network connection, opening files, etc. Were String not immutable, a connection or file would be changed and lead to a serious security threat. The method thought it was connecting to one machine, but was not. Mutable strings could cause a security problem in Reflection too, as the parameters are strings.
Here is a code example:
boolean connect(string s){
if (!isSecure(s)) { 
thrownew SecurityException(); 
}
//here will cause problem, if s is changed before this by using other references.    
    causeProblem(s);
}
5. Immutable objects are naturally thread-safe
Because immutable objects can not be changed, they can be shared among multiple threads freely. This eliminates the requirements of doing synchronization.
In summary, String is designed to be immutable for the sake of efficiency and security. This is also the reason why immutable classes are preferred in general.
-------------------------------------------------------------------------------------------------------------------------------

Static blocks

 

Static blocks in Java

Unlike C++, Java supports a special block, called static block (also called static clause) which can be used for static initializations of a class. This code inside static block is executed only once: the first time you make an object of that class or the first time you access a static member of that class (even if you never make an object of that class). For example, check output of following Java program.


// filename: Main.java
classTest {
    staticinti;
    intj;
     
    // start of static block
    static{
        i = 10;
        System.out.println("static block called ");
    }
    // end of static block
}

classMain {
    publicstaticvoidmain(String args[]) {

        // Although we don't have an object of Test, static block is
        // called because i is being accessed in following statement.
        System.out.println(Test.i);
    }
}
Run on IDE
Output:
static   block    called
10


Also, static blocks are executed before constructors. For example, check output of following Java program.


// filename: Main.java
classTest {
staticinti;
intj;
static{
i = 10;
System.out.println("static block called ");
}
Test(){
System.out.println("Constructor called");
}
}

classMain {
publicstaticvoidmain(String args[]) {

// Although we have two objects, static block is executed only once.
Test t1 = newTest();
Test t2 = newTest();
}
}


Run on IDE
Output:
static   block    called
Constructor     called
Constructor called
What if we want to execute some code for every object?
We use
 Initializer Block in Java


Java static keyword

  1. Static variable
  2. Program of counter without static variable
  3. Program of counter with static variable
  4. Static method
  5. Restrictions for static method
  6. Why main method is static ?
  7. Static block
  8. Can we execute a program without main method ?

The static keyword in java is used for memory management mainly. We can apply java static keyword with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of the class.
The static can be:
  1. variable (also known as class variable)
  2. method (also known as class method)
  3. block
  4. nested class



1) Java static variable

If you declare any variable as static, it is known static variable.
  • The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees,college name of students etc.
  • The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable
It makes your program memory efficient (i.e. it saves memory).

Understanding problem without static variable

1.      class Student{  
2.           int rollno;  
3.           String name;  
4.           String college="ITS";  
5.      }  
Suppose there are 500 students in my college, now all instance data members will get memory each time when object is created. All student have its unique rollno and name so instance data member is good. Here, college refers to the common property of all objects. If we make it static, this field will get memory only once.

1.1.1.1       Java static property is shared to all objects.

Example of static variable

1.      //Program of static variable  
2.        
3.      class Student8{  
4.         int rollno;  
5.         String name;  
6.         static String college ="ITS";  
7.           
8.         Student8(int r,String n){  
9.         rollno = r;  
10.     name = n;  
11.     }  
12.   void display (){
13.  System.out.println(rollno+" "+name+" "+college);
14.  }    
15.   public static void main(String args[]){  
16.   Student8 s1 = new Student8(111,"Karan");  
17.   Student8 s2 = new Student8(222,"Aryan");  
18.     
19.   s1.display();  
20.   s2.display();  
21.   }  
22.  }  
Output:111 Karan ITS
       222 Aryan ITS
Program of counter without static variable
In this example, we have created an instance variable named count which is incremented in the constructor. Since instance variable gets the memory at the time of object creation, each object will have the copy of the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the value 1 in the count variable.
1.      class Counter{  
2.      int count=0;//will get memory when instance is created  
3.        
4.      Counter(){  
5.      count++;  
6.      System.out.println(count);  
7.      }  
8.        
9.      public static void main(String args[]){  
10.    
11.  Counter c1=new Counter();  
12.  Counter c2=new Counter();  
13.  Counter c3=new Counter();  
14.    
15.   }  
16.  }  
Output:1
       1
       1



Program of counter by static variable
As we have mentioned above, static variable will get the memory only once, if any object changes the value of the static variable, it will retain its value.
1.      class Counter2{  
2.      static int count=0;//will get memory only once and retain its value    
3.      Counter2(){  
4.      count++;  
5.      System.out.println(count);  
6.      }  
7.        
8.      public static void main(String args[]){  
9.        
10.  Counter2 c1=new Counter2();  
11.  Counter2 c2=new Counter2();  
12.  Counter2 c3=new Counter2();  
13.    
14.   }  
15.  }  
Output:1
       2
       3



2) Java static method

If you apply static keyword with any method, it is known as static method.
  • A static method belongs to the class rather than object of a class.
  • A static method can be invoked without the need for creating an instance of a class.
  • static method can access static data member and can change the value of it.

Example of static method

1.      //Program +of changing the common property of all objects(static field).  
2.        
3.      class Student9{  
4.           int rollno;  
5.           String name;  
6.           static String college = "ITS";  
7.             
8.           static void change(){  
9.           college = "BBDIT";  
10.       }  
11.    
12.       Student9(int r, String n){  
13.       rollno = r;  
14.       name = n;  
15.       }  
16.    
17.       void display (){
18.  System.out.println(rollno+" "+name+" "+college);
19.  }  
20.       public static void main(String args[]){  
21.      Student9.change();  
22.    
23.      Student9 s1 = new Student9 (111,"Karan");  
24.      Student9 s2 = new Student9 (222,"Aryan");  
25.      Student9 s3 = new Student9 (333,"Sonoo");  
26.    
27.      s1.display();  
28.      s2.display();  
29.      s3.display();  
30.      }  
31.  }  
Output:111 Karan BBDIT
       222 Aryan BBDIT
       333 Sonoo BBDIT



1.1.2        Another example of static method that performs normal calculation

1.      //Program to get cube of a given number by static method  
2.        
3.      class Calculate{  
4.        static int cube(int x){  
5.        return x*x*x;  
6.        }  
7.        
8.        public static void main(String args[]){  
9.        int result=Calculate.cube(5);  
10.    System.out.println(result);  
11.    }  
12.  }  
Output:125
 
Restrictions for static method
There are two main restrictions for the static method. They are:

1.      The static method cannot use non static data member or call non-static method directly.
2.      this and super cannot be used in static context.





1.      class A{  
2.       int a=40;//non static  
3.         
4.       public static void main(String args[]){  
5.        System.out.println(a);  
6.       }  
7.      }        
Output:Compile Time Error



1.1.1        Q) why java main method is static?

Ans) because object is not required to call static method if it were non-static method, jvm create object first then call main() method that will lead the problem of extra memory allocation.



1.2         3) Java static block

  • Is used to initialize the static data member.
  • It is executed before main method at the time of class loading.
Example of static block
1.      class A2{  
2.        static{
3.      System.out.println("static block is invoked");
4.      }  
5.        public static void main(String args[]){  
6.        System.out.println("Hello main");  
7.        }  
8.      }  
Output:static block is invoked
       Hello main



1.2.1        Q) Can we execute a program without main() method?

Ans) Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
1.      class A3{  
2.        static{  
3.        System.out.println("static block is invoked");  
4.        System.exit(0);  
5.        }  
6.      }  
Output:static block is invoked (if not JDK7)
In JDK7 and above, output will be:
Output:Error: Main method not found in class A3, please define the main method as:
public static void main(String[] args)

Class Variables – Static Fields
Class variables also known as static fields share characteristics across all Objects within a Class. When you declare a field to be static, only a single instance of the associated variable is created, which is common to all the Objects of that Class. Hence when one Object changes the value of a Class variable, it affects all the Objects of the Class. We can access a Class variable by using the name of the Class, and not necessarily using a reference to an individual Object within the Class. Static variables can be accessed even when no Objects of that Class exists. Class variables are  declared using the static keyword.

Class Methods – Static Methods
Class Methods, similar to Class variables can be invoked without having an instance of the Class. Class methods are often used to provide global functions for Java programs. For example, Methods in the java.lang.Math package are Class methods. You cannot call non-static Methods from inside a static Method.
Static Keyword Rules
·         Variable or Methods marked static belong to the Class rather than to any particular Instance. 
·         Static Method or variable can be used without creating or referencing any instance of the Class. 
·         If there are instances, a static variable of a Class will be shared by all instances of that class, This will result in only one copy.
·         A static Method can’t access a non static variable nor can directly invoke non static Method (It can invoke or access Method or variable via instances).
 Cheat-sheet
·         Static is a Non Access Modifier.
·         The Static modifier can be applied to a variable or Method or block or inner Class.
·         Static members belong to Class only not an instance.
·         A Static Method can not access an instance variable.
·         Static Methods can not be overriden as they are Class specific and don’t belong to an Instance.
·         Static Methods can be redefined.
·         If a Class contains any static blocks then that block will be executed only when the Class is loaded in JVM. Creating multiple instances does not execute the static block multiple time. Only the constructor will be executed multiple time.
·         If Class.forName(“class_name“) is called then the static block of the Class will get executed.

Class/Static Variables

·        Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
·        There would only be one copy of each class variable per class, regardless of how many objects are created from it.
·        Static variables are rarely used other than being declared as constants. Constants are variables that are declared as public/private, final, and static. Constant variables never change from their initial value.
·        Static variables are stored in the static memory. It is rare to use static variables other than declared final and used as either public or private constants.
·        Static variables are created when the program starts and destroyed when the program stops.
·        Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
·        Default values are same as instance variables. For numbers, the default value is 0; for Booleans, it is false; and for object references, it is null. Values can be assigned during the declaration or within the constructor. Additionally, values can be assigned in special static initializer blocks.
·        Static variables can be accessed by calling with the class name ClassName.VariableName.
·        When declaring class variables as public static final, then variable names (constants) are all in upper case. If the static variables are not public and final, the naming syntax is the same as instance and local variables.
---------------------------------------------------------------------------------------------------------------------------

No comments:

Post a Comment