can any one send me the example program of immutable class?

Answers were Sorted based on User's Feedback



can any one send me the example program of immutable class?..

Answer / jagannath

public class ImmutableClass {
int i;
public ImmutableClass(int i)
{
this.i=i;
}
public int getI()
{
return i;
}
public ImmutableClass setI(int i)
{
if(i==this.i)
{
return this;
}
else
return new ImmutableClass(i);
}
public static void main(String args[])
{
ImmutableClass ic = new ImmutableClass(5);
ic.getI();
System.out.println(ic);
ic = ic.setI(10);
System.out.println(ic);
}
}
// If you pass 5 as the value in setter method, you will see
same address. It means whenever you are trying to change the
value of variable, a new object is created and returned. So
your object is immutable.

Is This Answer Correct ?    5 Yes 2 No

can any one send me the example program of immutable class?..

Answer / jinxuan

public class SingletonTest
{
public static void main(String[] args)
{
Singleton singleton = Singleton.getInstance();
Singleton singleton1 = Singleton.getInstance();

System.out.println(singleton == singleton1);
}
}

class Singleton
{
private static Singleton singleton = new Singleton();
private Singleton()
{

}

public static Singleton getInstance()
{
return singleton;
}

}
it means whenerver you new a Object,it returns the same
object address, i'ts Singleton Pattern. so your object is
immutable class

Is This Answer Correct ?    0 Yes 3 No

Post New Answer

More Core Java Interview Questions

Break statement can be used as labels in java?

0 Answers  


Why parsing is done?

0 Answers  


placement papaers of spring computing technology

0 Answers   Spring Computing Technologies,


how a programmer confirms that the data submitted has been succesfully inserted into the database(either oracle or my sql).. How a programmer confirm if there is any problem with the program he wrote for insertion... ANS:--- >executeupdate method is having boolean return type, if anything goes wrong in data insertion or data updation, it would return false. otherwise, if it successfully inserts data into the database, it would return true NOW HOW TO I CHECK IN MY DURING EXECUTION WHETHER IT RETURNS TRUE OR FALSE... WELL IT WILL DISPLAY ANY MESSAGE OR NOT

0 Answers   Google,


Can an unreachable object become reachable again?

3 Answers  






what is the form of storage space in java?

5 Answers  


explain about method overloading and method overriding with difficult examples

4 Answers  


What do you mean by Hash Map and Hash Table?

0 Answers   Atos Origin,


Program to find greatest prime number in n numbers?

3 Answers   Huawei,


why pointer is not used in java?

3 Answers  


Is there a jre for java 11?

0 Answers  


Can we print null in java?

0 Answers  


Categories