Java Final Keyword vs C++ const pointer vs C++ reference - java

as I see it C++ constant pointer, C++ reference and Java final keyword (final on a variable) are all the same thing or at least act the same way.
they prevent the variable to change his "pointed address" but the internal value can be changed.
am I right for thinking that?
If not what are the differences?
regarding the c++ part
what are the differences between a constant pointer and a reference?
they look like a different way to do the same thing, why adding the reference concept to c++ if the concept already existed in the form of constant pointer?
regarding the Java part
is there a way(in Java) to simulate the same behavior of a pointer to a constant value of c++? basically is there a way to make constant values?
something more similar to const Shape* s = new Shape;
edit: I found at least 1 reason to introduce the reference concept
when we define a copy constructor we need to get the object as an argument and without a reference, we will get an infinite loop
C++:
class Shape{
public:
int member = 3;
};
Shape s1;
Shape s2;
Shape* const cp_var_1 = &s1;
cp_var_1->member = 5; // valid
cp_var_1 = &s2; //not valid
Shape& ref_var_2 = s1;
ref_var_2.member = 6; // valid - s1 changed as well
// cant change ref_var_2 to reference other variable (like s2)
ref_var_2 = s2;
// assignment operator called - s1 and s2 content are the same
// but ref_var_2 still reference s1
Java:
class Shape{
public int member = 3;
}
Shape s1 = new Shape();
Shape s2 = new Shape();
final Shape final_var_3 = s1;
final_var_3.member = 7; // valid
final_var_3 = s2; // not valid

Yes, you're precisely correct: in final var_3 = s1;, the final prevents you from ever making var_3 reference anything else, but you can dereference the variable and do whatever you want to what you find there: var_3.member = 7; is therefore valid (the dot is the dereference operator).
Note that the final keyword in java is used for different purposes. You can mark classes as final, which means they cannot be extended. (class Foo extends SomeClassMarkedFinal {} will not compile). final can also be applied to methods: In that case, it means any subclass may not override this method. Whilst the english name final does seem like a good term for all of this behaviour, the final as used on variable declarations, and the final as used on methods and classes, are otherwise utterly unrelated.
Many java types (such as java.lang.String, java.lang.Integer, and many more) are so-called 'immutable': These objects have absolutely no way to change anything about them. java's strings are objects (not ersatz char arrays), you can't access the underlying char array, there is no clear() or setChar() method, etc: Therefore, a final variable of type string is completely constant.
Java does not (currently) offer any way of marking a type as 'constant' in this sense, and it probably wouldn't make much sense to add this as a notion. For example, in java, java.io.File, which represents a file path, is immutable: It has absolutely no methods to mutate any of its state.
And yet, is it immutable? Is it 'constant'? If I run file.delete(), I can most assuredly observe a change, even though the object itself (which has just one field, of type string, containing a file path) hasn't changed at all.

The final keyword in java does have (basically) the same effect as a reference or constant pointer in c++, but const in c++ ends up being a lot more general and more powerful.
If you have a pointer or a reference to a const object, then the object itself should be regarded as immutable. For example, if a function takes a const reference to an object, I can safely pass in objects with the assumption that they won’t be modified. And if I write a const member function, then I’m promising that that member function won’t modify the underlying object.
Adding const to function parameters (especially those passed by reference or pointer) can make it a lot easier for programmers to reason about code. They know that they can expect those inputs to remain unchanged. This is an enormous benefit when tracking down bugs, and it makes it easier to reason about the interface for external libraries that use const properly.
Finally, unlike in Java, a function that takes a value by reference in C++ is allowed (and encouraged) to assume that the reference you passed it isn’t null. This is good. If you write your code so that your references are never null, the code will be simpler, cleaner, and faster (since you won’t have to do null checks) .

Related

Copy constructor over assignment

After searching a lot, at least this question helped me to understand the difference of using copy constructor and assignment operatorMy question is about this line instance has to be destroyed and re-initialized if it has internal dynamic memory If I initialize an instance like
Object copyObj = null; and then then assign copyObj = realObj then still this overhead (destruction and re-initialization) remains?If not, then Now in this scenario, why should I use Copy Constructor instead of direct assigning the object
The concept of using a copy constructor by overriding the = simply does not exist in Java. You can't override operators. The concept of a copy constructor in Java works like this:
public class MyType {
private String myField;
public MyType(MyType source) {
this.myField = source.myField;
}
}
A copy constructor is a constructor that takes a parameter of the same type and copies all it's values. It is used to get a new object with the same state.
MyType original = new MyType();
MyType copy = new MyType(original);
// After here orginal == copy will be false and original.equals(copy) should be true
MyType referenceCopy = original
// After here orginal == referenceCopy will be true and original.equals(referenceCopy) will also be true
The = operator does the same: Assigning an object to a variable. It produces no overhead. The thing that can differ in runtime is the constructor call.
A Copy constructor allows you to keep two references; one to the "old" object, one to the "new". These objects are independent ( or should be depending upon how deep you allow the copy to be )
If you do a reassignment, you only have a reference to the "new" object. The "old" object will no longer be accessible ( assuming there are no other references to it ) and will be eligible for garbage collection.
It comes down to what it is your trying to achieve. If you want an exact copy of the object, and you want this object to have an independent life of its own, use a copy constructor. If you just want a new object and don't care about the old one, reassign the variable.
PS - I have to admit, I didn't read the question you linked to ..
First some basics about copy construction and copy assignment in C++ and Java
C++ and Java are two very different beasts due to object semantics in C++ and Reference semantics in Java. What I mean by this is:
SomeClass obj = expr;
In C++ this line denotes a new object that gets initialized with expr. In Java, this line creates not a new object but a new reference to an object, and that reference refers to what ever the expression gives. Java references can be null, meaning "no object". C++ objects are, so there is no "no object"-object ;-) Java references are very much like C++ pointers. The only thing that can make the distinction difficult is that while C++ has pointers and objects and dereferences pointers with ->, in Java everything is a reference (except int and a few other basic types), and accessing objects through references uses ., wich easily can be confused with access to "direct" objects in C++. "Everything is a reference" means, that any object (except int & Co.) is conceptually created on the heap.
Having said that, let's have a look at assignments and copies in both languages.
Copy construction means the same in both languages, you essentially create a new object that is a copy of another. Copy constructor definition is similar:
SomeClass(SomeClass obj) { /* ... */ } //Java
SomeClass(SomeClass const& obj) { /* ... */ } //C++
The difference is only that C++ explicitly has to declare the parameter as a reference, while in Java everything is a reference anyways. Writing the first line in C++ would define a constructor that takes it's argument by copy, i.e. the compiler would have to create a copy already, using the copy constructor, for which it has to create a copy,... - not a good idea.
Using copy construction in the two languages will look like this:
SomeClass newObj = new SomeClass(oldObj); //Java
SomeClass newObj = oldObj; //C++ object
SomeClass* ptrNewObj = new SomeClass(oldObj); //C++ pointer
When you look at the first and third line, they look essentially the same. This is because they are essentially the same, since Java references are essentially like pointers in C++. Both expressions create a new object that can outlive the function scope it is created in. The second line creates a plain C++ object on the stack, wich does not exist in Java. In C++, copies are also created implicitly by the compiler eg. when an object is passed to a function that accepts its parameter by value instead of by reference.
Defining copy assignment: In C++, you can define operator= wich (normally) assigns the values of an object to an already existing object, discarding the old values of the object you assign to. If you don't define it yourself, the compiler will do it's best to generate one for you, doing a plain elementwise copy of the objects' elements. In Java, you cannot overload operators, so you will have to define a method, called e.g. assign:
void assign(SomeObject other) {/* ... */} //Java
SomeObject& operator=(SomeObject const& other) {/* ... */} //C++
Note thet here again we explicitly declare the parameter as reference in C++ but not in Java.
Using copy assignment:
objA = objB; //C++ copy assignment
objA = objB; //Java ref assignment
ptrObjA = ptrObjB; //C++ pointer assignment
objA.assign(objB); //Java
objB.change();
Here the first two lines look exactly the same but could not be more different. Remember that in C++, objA and objB deonte the objects themselves, while in Java they are only references. So in C++ this is copy assignment on objects, meaning you finish with two objects that have the same content. After changing objB you will have objA with the value that objB had before the assignment, while objB has changed.
In Java (line 2) that assignment is an assignment of references, meaning after that the two references objA and objB refer to the very same object, while the object previously referred ba objA is not referred to any more and so it will be garbage collected. Calling objB.change() will change the single object both references point to and accessing it through the reference objA will reveal these changes.
Again it's (nearly) the same with C++ pointers. You see you cannot distinguish the syntax of object and pointer assignment, it's all determined by the types that get assigned. The difference with C++ is that it has no garbace collector and you end up with a memory leak because the object ptrObjA pointed to can not be deleted any more.
About your question:
Consider a C++ class:
class X {
int* pi;
unsigned count;
public:
X(X const&);
X& operator= (X const&);
~X();
};
Suppose each X object allocates it's own dynamic array of ints, the pointer to it gets stored in pi. Since C++ has no garbage collection, the X objects have to care themselves for their allocated memory, i.e. they have to destroy it manually:
X::~X() { delete[] pi; }
A copy constructor will copy the dynamic array of the original, so the two do not conflict while using the same array. This is called deep copy and is used equally in Java and C++:
X::X(X const& other) : pi(NULL), count(0) {
pi = new int[other.count]; //allocates own memory
count = other.count;
std::copy(other.pi, other.pi+count, pi); //copies the contents of the array
}
Now to the qoute in your question:
Consider two objects x1 and x2 and the assignment x1 = x2. If you leave everythign to the compiler, it will generate an assignment operator like this:
X& X::operator=(X const& other) {
pi = other.pi;
count = other.count;
}
In the first line x1.pi gets the pointer value of x2.pi. Like I explained in the section about copy assignment, this will lead to both pointers pointing to the same array, and the array previously owned by x1 will be lost in space, meaning you have a leak and odd behavior when both objects work on their shared array.
The correct implementation would be:
X& X::operator=(X const& other) {
delete[] pi; //1
pi = new int[other.count]; //allocates own memory
count = other.count;
std::copy(other.pi, other.pi+count, pi); //copies the contents of the array
}
Here you see what the quote says: First, the object is "cleaed up", i.e. the memory is freed, essentially doing what the destructor does ("instance has to be destroyed").
Then, the deep copy is performed, doing what the copy constructor does ("...and re-initialized").
This is called the "Rule of Three": If you have to write your own copy constructor (because the generated one does not what you want it to do), you will mostly have to write your own destructor and assignment operator as well. Since C++11 it has become the "Rule of Five", because you have move assignment and move construction that have to be considered as well.

in java, why do closured variables need to be declared final?

final Object o;
List l = new ArrayList(){{
// closure over o, in lexical scope
this.add(o);
}};
why must o be declared final? why don't other JVM languages with mutable vars have this requirement?
This is not JVM-deep, it all happens at syntactic-sugar level. The reason is that exporting a non-final var via a closure makes it vulnerable to datarace issues and, since Java was designed to be a "blue-collar" language, such a surprising change in the behavior of an otherwise tame and safe local var was deemed way too "advanced".
It's not hard to deduce logically why it has to be final.
In Java, when a local variable is captured into an anonymous class, it is copied by value. The reason for this is that the object may live longer than the current function call (e.g. it may be returned, etc.), but local variables only live as long as the current function call. So it is not possible to simply "reference" the variable because it may not exist by then. Some languages like Python, Ruby, JavaScript, do allow you to reference variables after the scope is gone, by keeping a reference to the environment in the heap or something. But this is hard to do with the JVM because local variables are allocated on the function's stack frame, which is destroyed when the function call is done.
Now, since it is copied, there are two copies of the variable (and more, if there are more closures capturing this variable). If they were assignable, then you can change one of them without changing the other. For example, hypothetically:
Object o;
Object x = new Object(){
public String toString() {
return o.toString();
}
};
o = somethingElse;
System.out.println(x.toString()); // prints the original object, not the re-assigned one
// even though "o" now refers to the re-assigned one
Since there is only one o variable in the scope, you would expect them to to refer to the same thing. In the example above, after you assign to o, you would expect a later access of o from the object to refer to the new value; but it doesn't. This would be surprising and unexpected to the programmer, and violates the principle that uses of the same variable refer to the same thing.
So to avoid this surprise, they mandate that you cannot assign to it anywhere; i.e. it has to be final.
Now, of course, you can still initialize the final variable from a non-final variable. And inside the closure, you can still assign the final variable to something else non-final.
Object a; // non-final
final Object o = a;
Object x = new Object(){
Object m = o; // non-final
public String toString() {
return ,.toString();
}
};
But then this is all good since you are explicitly using different variables, so there is no surprise about what it does.

Confusion over Java's pass-by-value and immutability

In preparation for the SCJP (or OCPJP as it's now known) exam, I'm being caught out by some mock questions regarding pass-by-(reference)value and immutability.
My understanding, is that when you pass a variable into a method, you pass a copy of the bits that represent how to get to that variable, not the actual object itself.
The copy that you send in, points to the same object, so you can modify that object if its mutable, such as appending to a StringBuilder. However, if you do something to an immutable object, such as incrementing an Integer, the local reference variable now points to a new object, and the original reference variable remains oblivious to this.
Consider my example here :
public class PassByValueExperiment
{
public static void main(String[] args)
{
StringBuilder sb = new StringBuilder();
sb.append("hello");
doSomething(sb);
System.out.println(sb);
Integer i = 0;
System.out.println("i before method call : " + i);
doSomethingAgain(i);
System.out.println("i after method call: " + i);
}
private static void doSomethingAgain(Integer localI)
{
// Integer is immutable, so by incrementing it, localI refers to newly created object, not the existing one
localI++;
}
private static void doSomething(StringBuilder localSb)
{
// localSb is a different reference variable, but points to the same object on heap
localSb.append(" world");
}
}
Question : Is it only immutable objects that behave in such a manner, and mutable objects can be modified by pass-by-value references? Is my understanding correct or are there other perks in this behaviour?
There is no difference between mutable and immautable objects on the language level - immutability is purely a property of a class's API.
This fact is only muddled by autoboxing which allows ++ to be used on wrapper types, making it look like an operation on the object - but it's not really, as you've noticed yourself. Instead, it's syntactic sugar for converting the value to a primitive, incrementing that, converting the result back to the wrapper type and assigning a reference to that to the variable.
So the distinction is really between what the ++ operator does when it's used on a primitive vs. a wrapper, which doesn't have anything to do with parameter passing.
Java itself has no idea of whether an object is immutable or not. In every case, you pass the value of the argument, which is either a reference or a primitive value. Changing the value of the parameter never has any effect.
Now, to clarify, this code does not change the value of the parameter:
localSb.append(" world");
That changes the data within the object that the value of the parameter refers to, which is very different. Note that you're not assigning a new value to localSb.
Fundamentally, you need to understand that:
The value of an expression (variable, argument, parameter etc) is always either a reference or a primitive value. It's never an object.
Java always uses pass-by-value semantics. The value of the argument becomes the initial value of the parameter.
Once you think about those things carefully, and separate in your mind the concepts of "variable", "value" and "object", things should become clearer.

Constant Object vs Immutable Object

Can I use the term "Constant Object" in the place of the term "Immutable Object"? Though I get the feeling that Immutable for an Object is what Constant is for a variable, I am not sure if this terminology is accepted. Please help me understand.
In fact, in Java the term constant has no defined meaning. It occurs in the JLS only in the larger term compile time constant expression, which is an expression which can (and must) be calculated by the compiler instead of at runtime. (And the keyword const is reserved to allow compilers to give better error messages.)
In Java, we instead use the term final to refer to variables (whether class, object or local ones) who can't be changed, and immutable when we refer to objects who can't change. Both can be used when speaking about a variable x - the first then means the variable itself (meaning it can't be switched to another object), the second means the object behind the variable. Thus here the two meanings are orthogonal, and are often combined to create a "true constant".
I would read constant as being the same object (the same reference), whereas immutable clearly means to me the fact that the object doesn't change.
Since these are two different things, I would perhaps refer to this:
private final Immutable i = new Immutable();
as being a constant immutable object.
Constant often has a very specific meaning in different programming languages. In java, a constant already refers to a constant variable, a variable that cannot be changed after assignment, e.g.:
final int FOO = 1;
FOO = 4; // constant variable cannot be changed.
An immutable object is a constant object in the sense that its properties can never be changed, but of course an object pointed to by a constant variable can still be changed. So to avoid confusion, the term immutable (which literally means "unchanging over time") is used.
They are very close in meaning, with the understanding that an Object contains methods while a Constant is generally considered to only contain data.
Within Java, there's the additional consideration of the keyword final, which basically means non-reassignable. Some people will casually call a final variable a constant (as it's reference to a particular object is a constant. This often comes about due to confusion as to the particular roles of the member and the object it refers to, as 95% of the time a person does this to refer to an immutable Object.
Not every method is to return back data that depends wholly upon the internal members. For example System.currentTimeMillis() returns back a Unix like timestamp, yet there would be no need for the actual "System" object to change.
Immutability of the object means it can't transform it's state... i.e. can't mutate... For examle
final class Person {
private int age = 0;
public Person(int age) { this.age = age; }
}
The object to this type are immutable objects since you can't change it's state.... (forget Reflection for a moment)
Constant at the other hand in Programming means inline... Even the compiler does that they inline the values of the constant variables for primative types... for object types it means the ref variable can't be reassigned.

How can Java assignment be made to point to an object instead of making a copy?

In a class, I have:
private Foo bar;
public Constructor(Foo bar)
{
this.bar = bar;
}
Instead of creating a copy of bar from the object provided in the parameter, is it possible to include a pointer to bar in the constructor such that changing the original bar changes the field in this object?
Another way of putting it:
int x = 7;
int y = x;
x = 9;
System.out.print(y); //Prints 7.
It is possible to set it up so that printing y prints 9 instead of 7?
When a variable is used as argument to a method, it's content is always copied. (Java has only call-by-value.) What's important to understand here, is that you can only refer to objects through references. So what actually happens when you pass a variable referring to an object, is that you pass the reference to the object (by value!).
Someone may tell you "primitives are passed by value" and "non primitives are passed by reference", but that is merely because a variable can never contain an object to begin with, only a reference to an object. When this someone understands this, he will agree that even variables referring to objects are passed by value.
From Is Java "pass-by-reference" or "pass-by-value"?
Java is always pass-by-value. The difficult thing can be to understand that Java passes objects as references passed by value.
From http://www.javaworld.com/javaworld/javaqa/2000-05/03-qa-0526-pass.html
Java does manipulate objects by reference, and all object variables are references. However, Java doesn't pass method arguments by reference; it passes them by value.
In Java, there is no counter part to the C++ "reference type" for primitives.
Your last example works that way because int is a primitive, it is copied by value. In the first example, "this.bar" would hold a copy of the reference (sort of pointer) to bar. So if you change the original bar (internally), the change will be reflected in your class. Try it.
To get that behavior you could modify a member of an object:
public class Number{
int value;
Number(int value){
this.value = value;
}
public String toString() {
return "" + value;
}
}
You could then do:
Number x = new Number(7);
Number y = x;
x.value = 9;
System.out.println(y);//prints 9
Java never copies objects. It's easiest to think of in terms of for each "new" you will have one object instance--never more.
People get REALLY CONFUSING when they discuss this in terms of pass by reference/pass by value, if you aren't amazingly familiar with what these terms mean, I suggest you ignore them and just remember that Java never copies objects.
So java works exactly the way you wanted your first example to work, and this is a core part of OO Design--the fact that once you've instantiated an object, it's the same object for everyone using it.
Dealing with primitives and references is a little different--since they aren't objects they are always copied--but the net effect is that java is just about always doing what you want it to do without extra syntax or confusing options.
In order to keep the original value of member bar, you will need to implement Cloneable interface. Then before assigning a new value to the object, you will need to make a clone of it and pass the cloned value and assign new values to the cloned object. Here is a tutorial on how to do it http://www.java-tips.org/java-se-tips/java.lang/how-to-implement-cloneable-interface.html .

Categories