Primitive Wrapper Classes are Immutable in Java
All primitive wrapper classes (Integer, Byte, Long, Float, Double, Character, Boolean and Short) are immutable in Java, so operations like addition and subtraction create a new object and not modify the old.
// Java program to demonstrate that prmitive
// wrapper classes are immutable
class Demo
{
public static void main(String[] args)
{
Integer i = new Integer(12);
System.out.println(i);
modify(i);
System.out.println(i);
}
private static void modify(Integer i)
{
i = i + 1;
}
}
Output :
12
12
// Java program to demonstrate that prmitive
// wrapper classes are immutable
class Demo
{
public static void main(String[] args)
{
Integer i = new Integer(12);
System.out.println(i);
modify(i);
System.out.println(i);
}
private static void modify(Integer i)
{
i = i + 1;
}
}
Output :
12
12
Comments
Post a Comment