Reputation: 165
I'm currently reading the book called Java the complete reference. In chapter 18 , there is a introduction for Primitive Type Wrappers.
As mentioned in Part I of this book, Java uses primitive types, such as int and char, for performance reasons. These data types are not part of the object hierarchy. They are passed by value to methods and cannot be directly passed by reference. Also, there is no way for two methods to refer to the same instance of an int At times, you will need to create an object representation for one of these primitive types. For example, there are collection classes discussed in Chapter 19 that deal only with objects; to store a primitive type in one of these classes, you need to wrap the primitive type in a class.
What does the author actually mean in the the lines given in the bold? there is no way for two methods to refer to the same instance of an int. It would be great if someone explain this line using an example:) Thank You in advance.
Upvotes: 2
Views: 76
Reputation: 1917
I might be wrong in my consideration of the bold line, as mentioned in comments by community users as well. But, AFAIK, it is trying to say that if a primitive type variable or a wrapper of primitive type is passed to two methods, then both the methods have different copies of that. I have implemented an example to help you on this.
You can try running it and see the output in all the cases. In the cases, where int or Integer is passed, the change in value is not reflected in another method.
Pardon my camel-casing.
public class TestPrimitive
{
public static void main(String[] args)
{
int i = 15;
Integer j = 20;
StringBuffer str = new StringBuffer("Hello");
XYZ obj = new XYZ(10);
printIWithAddition(i);
printIWithoutAddition(i);
IntegerWrapperWithChange(j);
IntegerWrapperWithoutChange(j);
StringBufferWithChange(str);
StringBufferWithoutChange(str);
XYZWithChange(obj);
XYZWithoutChange(obj);
}
private static void printIWithAddition(int i) {
i++;
System.out.println(i);
}
private static void printIWithoutAddition(int i) {
System.out.println(i);
}
private static void IntegerWrapperWithChange(Integer j) {
j++;
System.out.println(j);
}
private static void IntegerWrapperWithoutChange(Integer j) {
System.out.println(j);
}
private static void StringBufferWithChange(StringBuffer str) {
System.out.println(str.append(" World"));
}
private static void StringBufferWithoutChange(StringBuffer str) {
System.out.println(str);
}
private static void XYZWithChange(XYZ obj) {
obj.a = 20;
System.out.println(obj);
}
private static void XYZWithoutChange(XYZ obj) {
System.out.println(obj);
}
}
class XYZ {
int a;
public int getA()
{
return a;
}
public void setA(int a)
{
this.a = a;
}
public XYZ(int a)
{
this.a = a;
}
@Override public String toString()
{
return "XYZ{" + "a=" + a + '}';
}
}
Upvotes: 1