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

How to initialize an Applet ?

9 Answers   TCS,


How is it possible in java programming for two string objects with identical values not to be equal under the == operator?

0 Answers  


What is a stringbuffer?

0 Answers  


What is abstraction with strong example program? (not a general program)

3 Answers  


How to invoke external process in java.

0 Answers  


What is difference between “==” and equals()?

1 Answers   IBM,


When should you use arraylist and when should you use linkedlist?

0 Answers  


What is the class in java?

0 Answers  


Can Anybody tell the diff b/w jdk1.6 and latest version.

2 Answers  


What is ellipsis in java?

0 Answers  


Is JRE required to compile Java files ?

4 Answers   HCL,


Have you ever used hashtable and dictionary?

0 Answers  


Categories