Setting variables in Constructor using this - java

So I am OK with java, but new to C++. I am basically trying to make a Constructor for C++ with a parameter passed, and assign that value to the field for that object using this. So here is what it would look like in java:
//Foo fields
private int num;
//Foo Constructor
public Foo(int num){
this.num = num;
}
How can I use this to set a variable like that in C++? Or is this not an option? Thanks!!

C++ has an even cleaner approach, called constructor initializers. Instead of having lots of assignments, you can use this syntax:
public MyClass::MyClass(int num): someVar(num), someOtherVar(0) {
// constructor here
}
If you really, really want to use this, remember that in C++ this is a pointer, so you have to use the pointer dereference operators, so either
this->num = num;
or
(*this).num = num;

Use this->num, as in c++ this is a pointer, to access struct/class members via pointer you have to use -> instead of . between variable and member name, here is from manual
expression can be read as
*x pointed by x
&x address of x
x.y member y of object x
x->y member y of object pointed by x

Related

Why does the new Integer act as value type int?

public static void main(String []args){
Integer a = new Integer(9);
d(a);
System.out.print(a) ;
}
public static void d(int z){
z=z+2;
}
or suppose I write
public static void main(String []args){
int a = 9;
d(a);
System.out.print(a) ;
}
public static void d(int z){
z=z+2;
}
but the output is the same for both: 9. Can anyone explain me in detail why?
Because JAVA is PASS BY VALUE not PASS BY REFERENCE.
Let us understand it this way,
Your main function has a local variable z whose scope is limited to main only
and your d function has another local variable z whose scope is limited to d only
So, in your d fucntion, you are basically creating a new integer literal 11 and putting it to local variable z whose scope is limited to d function only and not the variable z of main.
In your code with Integer a process called unboxing occurs. The Integer-instance is unboxed to a primitive int when calling your method d. See this to better understand how autoboxing and unboxing works.
As for your z=z+2 inside the method d. Java objects are passed-by-reference, but Java primitives or Immutable objects (like Strings) are passed-by-value. Since your method d has a primitive parameter int it's passed-by-value in this case. Your z=z+2 isn't returned however.
If you would add System.out.println(z); right after z=z+2 it will indeed print 11. So why isn't the a in your main-method changed to 11 and how can you accomplish this? As I mentioned, it's passed-by-value for primitives. You'll need to return the new value and set the a in the main method with it. If you change your code to this it will work:
public static void main(String []args){
int a = 9;
a = d(a);
System.out.print(a);
}
public static int d(int z){
return z+2;
}
Try it online.
As you can see, the void d is changed to int d, and we return the result of z+2. We then overwrite the value of a with this new result with a = d(a); in the main-method.
Java has a concept of AutoBoxing and Auto unboxing for primitive datatypes.
Since primitves like int, float double, long etc are technically not objects, they have their corresponding Classes which can be instantiated with the primitive value to treat them as objects.
So to reduce the pain, java automatically converts int to Integer and Integer to int where ever applicable.
If you are wondering why the addition value has not reflected, though it is an Integer object on performing addition, a new int object will be resulted. so it wont reflect directly. You can return the value from the method you call and assign to it.
Java passes variables by value, not by reference. If you think that passing an object and changing the value of its data member would work, it won't. In that case, too, a copy of that object will be passed, not the original object. The only solution is to declare the variable as static that can be changed from anywhere.
it's all because of Autoboxing and Unboxing feature of java which provide the functionality of converting primitive to object(Wrapper) type and vice-versa. for better understanding you can check here
. I hope it will clear all your doubts.

How to define ascending Intergers in function?

My question is rather simple but nonetheless I wasnt able to find an answer.
Id like to create a new Integer (or any other data type) every time a method is called like:
public void x(){
int i = 0;
int num;(plus value of i in its name eg: num1, num2, num3,...)
i++;
}
what you're thinking of is called varvars (variable variables) and Java does not support them (thank god - we have reflection)
PHP does though: http://php.net/manual/en/language.variables.variable.php
what you probably want is to put your Integers in a Collection: https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
You should store your int num into the class instead of the method, this wise your variable has object escope and will have its reference anytime you call your method.

Why do they call it pass by value in Java? [duplicate]

This question already has answers here:
Is Java "pass-by-reference" or "pass-by-value"?
(93 answers)
Closed 8 years ago.
Ok, so I am a relatively new programmer. I have read over and over about passing variables. From what I have read here is what I've come to understand: In Java, when you pass a variable to a method (be it primitive or Object) you are ALWAYS passing by value. But what you are REALLY doing is passing a copy of the reference to an object or variable in memory.
So why do they call it pass by value? It seems to me you are passing by reference. Also, in C when you pass a pointer to a function, aren't you passing the address of a variable in memory? Yet it is called pass by value. What am I overlooking? Can someone please explain and clarify why I this? I know how to pass variables and such and I have read several SO posts on this but I am not fully satisfied yet. Consider an example:
static void setNameStatic(Dog d, String name) {
d.name = name;
}
public static void main (String args[]) {
Dog d = new Dog("dog1");
System.out.println( d.getName() );
setNameStatic( d, "dog2" );
System.out.println( d.getName() );
}
Won't this output: dog1 and dog2. So aren't you going to where the reference is referring to and changing data around? What exactly does the value have to do with here? Any helpful comments are appreciated. And yes, I know it is pass by value, but why isn't it called "pass by sending copy of reference" lol?
Update: Thanks to everyone that gave a helpful answer. I know this was marked duplicate, and sorry about that. I am satisfied with the answers now.
Your memory looks like this at the moment of:
Dog d = new Dog("dog1");
Stack (with local vars) Heap
+-----------+ points to
| Dog d | ---------------> real dog object
+-----------+
| ... |
+-----------+
| ... |
+-----------+
And then, when you pass in a reference to a method, it looks something like this (where the Dog dog2 is the method argument):
Stack (with local vars) Heap
+-----------+
| Dog d | ---------------> real dog object
+-----------+ ^
| ... | |
+-----------+ |
| Dog d2 |------------------------------
+-----------+
So, the reference is passed by value. It points to the same object but it is the new reference!
Meaning, if you would try something like this:
public static void main(String ... args) {
Dog d= new Dog("dog1");
setNameStatic(d, "dog2");
System.out.println(d); // Still prints dog1 !!!
}
static void setNameStatic(Dog d2, String name) {
d2= new Dog(name);
}
Because the new (copied) reference now points to the new object on heap and the original object has not changed.
Because the value of any variable of reference type is its address in memory.
Because the value of any variable of primitive type is its value itself.
So you always pass values of variables.
Every variable is passed by value. In the instance of primatives, we have the naive case - the values are passed into the function.
In the instance of Objects, we have a slightly more complicated although analogous paradigm - the references to the objects are passed by value.
Note the subtle differences:
//This is essentially a no-op. The values are only local to the function
void swap(int a, int b){
int temp = a;
a = b;
b = temp;
}
//This is different. The references to a and b are passed by value so the values of a.x and b.x are actually swapped on return.
void swap(Point a, Point b){
int temp = a.x;
a.x = b.x;
b.x = temp;
}
Passing by value means that the value is transferred to method, i.e. yet another copy of the same value is created:
int i = 5; // one copy of 5
foo(i);
private void foo(int n) {
// here n is 5, however it is "another" 5
}
The evidence of passing by value is that you cannot change your i from within the method foo():
int i = 5; // one copy of 5
foo(i);
// i is still 5 here
private void foo(int n) {
n = 6;
// n is 6, however it is actual inside the method only.
}
The same is with objects, however in that case reference is passed by value.
Also, in C when you pass a pointer to a function, aren't you passing the address of a variable in memory? Yet it is called pass by value.
No it is not. When you pass a pointer to a value to a function in C, it is known as 'pass by reference'. The function can directly access & modify the original value because it has it's address. Pass by value is when you pass the value of objects instead of their locations or addresses. Look at the following examples.
int addOne(int x)
{
return x + 1;
}
void destructiveAddOne(int *x)
{
*x += 1;
}
int main(void)
{
int x = 5;
int y = 5;
// We pass the _value_ of x, ie, 5 to addOne, and store the result in z.
// The value of x will remain unchanged, ie, 5.
int z = addOne(x);
// We pass a REFERENCE to y, ie, it's address to destructiveAddOne()
// destructiveAddOne then modifies the value of y to be y + 1. The value of y
// has now CHANGED to 6. This is call by reference.
destructiveAddOne(&y);
return 0;
}
A variable holds the bits that tell the JVM how to get to the referenced Object in memory (Heap).
When passing arguments to a method you ARE NOT passing the reference variable, but a copy of the bits in the reference variable. Something like this: 3bad086a. 3bad086a represents a way to get to the passed object.
So you're just passing 3bad086a that it's the value of the reference.
You're passing the value of the reference and not the reference itself (and not the object).
This value is actually COPIED and given to the method.
Had that before:
Is Java "pass-by-reference" or "pass-by-value"?
It is a tricky thing to get your head round. I think of it as real numbers, albeit abstracted. Say your first dog, dog1, is created at memory location "100,000" (I know but bear with me). You pass the reference's value of 100,000 around to methods. Your method changes the name of the object living at 100,000.
If you pass your dog1 object into a method that does d = new Dog("dogXXX"), then it will work with a brand new object at (say) 200,000 leaving your dog1 at memory address 100,000 unchanged.
Apologies for the memory address abuse which will have experts spitting their coffee...
In java you're passing parameters by value to the methods, but the parameters are themselves ref type if the parameter is an object.
As a contrast in a programming language like C that passing by reference is allowed, if you print a reference you get something different from what you get when print it's value.
To insure that objects are reference types and compare them with primitives, Try this:
public class TestClass {
public static void main(String[] args) {
String s = new String("a");
String t = new String("a");
System.out.println(s==t);
char a = 'a';
char b = 'a';
System.out.println(a==b);
}
}
The result is :falsetrue
References in Java are passed by value of the reference.
When you pass reference as a method parameter copy is created and you operate on this copy.
To illustrate it have a look at this sample code:
final Person person = new Person();
person.setName("A");
changeName(person, "B");
System.out.println(person.getName());
Now if we have changeName implemented as this:
private static void changeName(Person person, String name) {
person.setName(name);
}
Then the result is B. It's because copy of the reference still points to the same object and there is possibility to modify it.
On the other hand if you change the changeName method to this:
private static void changeName(Person person, String name) {
person = new Person();
person.setName(name);
}
Then the result is A. It's because copy of the reference points to the new object, but original reference still points to the original object and it's value is not modified.
If Java would pass object references by reference than the result would be B, because it would operate on the original object.
When you pass an object as a parameter in Java, you actually pass a reference, and the reference is the value used in the stack. However, any assignment you make to this reference inside the method will not be observed by the caller, because you only change a copy of the reference. Same goes with primitive values as parameters.
In other languages (like C++), you have the option to pass by reference, allowing you to change the reference itself from within a method. In Java, for example, you can't implement a swap method that takes two parameters and swaps them. In C++ it's possible.

pass by reference/value - simple example

I know this issue has been addressed many times - but my Java/C++ knowledge is so weak I can barely understand the answers :-( ... what I'd really like is just a super simple example.
In C++ I could write the following:
void func()
{
int x = 3;
add_one(x);
// now x is 4.
}
void add_one(int &var)
{
var++;
}
What I'd like to see now is the simplest way to achieve the same effect with java.
You can't directly. The closest you can get is to put the value in an object, and pass the reference (by value, so the reference gets copied) into the method.
void func()
{
int x = 3;
int[] holder = [x];
add_one(holder);
// now holder[0] is 4. x is still 3.
}
// container here is a copy of the reference holder in the calling scope.
// both container and holder point to the same underlying array object
void add_one(int[] container)
{
container[0]++;
}
Here I use an array, but the wrapper can be any object.
In java method arguments are pass-by-value, and can't be changed in the function. You must wrap the int - or any other primitive type - in an Object or an array. Passing an Object or an array as a method argument passes a reference which can be used to modify the object.
Java already has Object based wrappers for primitive types, e.g. Integer, but these are immutable by design. Some libraries provide mutable versions of these wrappers; you can also create your own:
public class MutableInt
{
private int val;
public MutableInt(int val)
{
this.val = val;
}
public void setValue(int newVal)
{
this.val = newVal;
}
public int getValue()
{
return this.val;
}
}
void func()
{
int x = 3;
MutableInt wrapper = new MutableInt(x);
add_one(wrapper);
}
void add_one(MutableInt arg)
{
arg.setValue(arg.getValue() + 1);
}
You cannot do this. Java is only pass by value. Primitives are obvious, but the thing that's passed for objects is a reference, not the object itself.
As you can see from the other answers, Java is purely pass by value. Objects are passed by what some call "value-reference". Since an object in java is simply a pointer reference, you can think of the "value" as the address where the object lives on the heap. So when you make a method call, you're copying the "value", aka address, to the method parameter:
Object x = new Object();
foo(x);
During object creation
Heap --> allocate Object (5000)
Variable Declaration
Stack --> allocate local variable (1000)
Variable Assignment
Stack address 1000 set to 5000 (to point to object instance)
So you can see that there are two separate memory allocations here. The "value" of the variable is considered to be it's address on the heap.
Method Call
Stack --> allocate method parameter 8000
Stack address 8000 set to same value as passed parameter 5000
This is why if you reassign an object instance in a method, it does not propagate back to the caller. You would have changed the heap location at stack location 8000. And the calling method's stack location 1000 still has the value 5000 (the original object instance).
Think of it like this in C:
void method(myobject * obj);
You can certainly change fields of "obj", and you can do this locally:
obj = new myobject();
But the caller will still see the original value it passed.
Java has no analog to the & reference operator.
And there are built in classes which can be used for the your purposes. AtomicInteger, AtomicLong, etc... are mutable, though you may suffer a performance hit due to synchronization involved.
I would recommend a generic ValueHolder class to account for all situations where you want to simulate pass by reference:
public class ValueHolder<T> {
private T value;
// getter/setter/constructor
}
Java allows copy by reference for objects and copy by vlaue for primitive types (int,float,etc..). This is so by default and is not subject to change. If you need to change the value of an int inside a function, then you can use the class Integer for example
public int getOneMore(int val) {
return val + 1;
}

Can someone explain to me in detail the use of 'this'?

I don't really understand the use of 'this' in Java. If someone could help me clarify I would really appreciate it.
On this website it says: http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
"Within an instance method or a constructor, this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this."
and it gives the following example:
For example, the Point class was written like this
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Yet, I still don't fully understand why x = a could have been written as this.x = x? Why isn't it this.x = a? Why is the x on the left side?
I'm sorry but I am very new to Java. I apologize for boring the experts.
If some variable/argument with same name as object's property is defined, it "overlaps" the name of that property and one should use this.var_name.
So yes, it could be written as this.x = a, but is somewhat redundant.
In the second example one of the arguments is named x. By referencing this.x, you mean the x field/property of the class the method is part of. It could read as:
Point.x = argument x
this is being used to differentiate the two, making the meaning of the code clear.
It isn't this.x = a because there isn't an 'a' in the second example. The point is that you can reuse the same variable name, which is less confusing :-|
The idea is to make it very clear that you are providing values for x and yin your constructor.
Problem is now that due to the scoping rules that within the constructor x refers to the passed value and not the field x. Hence x = x results in the parameter being assigned its own value and the shadowed field untouched. This is usually not what is wanted.
Hence, a mechanism is needed to say "I need another x than the one immediately visible here". Here this refers to the current object - so this.x refers to a field in the current object, and super refers to the object this object extends so you can get to a field "up higher".
this is a reference to the current object, so you access it like any other object - this.x is the x property of this. So x is the argument passed in, which you assign to this.x.
This is namespacing - the idea that a name for a variable only applies within a given block of code. In java, where you are working within a function belonging to the class, you are inside the namespace for that class, however, if you have another variable with the same name as an argument, it will take precedence, and you instead access the attribute via this.
this can also be used in other ways. For example, say I want to draw the current object to the screen in a fictional library, from within the class, I could do:
window.draw(this)
You can also call functions
this allows us to reference the object we are currently 'inside', so we can pass the current object as an argument. This is very useful. (No pun intended).
"this" is a reference to the current object you are using. You use it when you have a name clash between a field and a parameter. Parameter takes precedence over fields.
No clash, no need for this:
public Point(int a, int b) {
x = a;
y = b;
}
But this will work, too:
public Point(int a, int b) {
this.x = a;
this.y = b;
}
Name clash, need to use "this":
public Point(int x, int y) {
this.x = x;
this.y = y;
}
If you did only
public Point(int x, int y) {
x = x;
y = y;
}
then you would just assign parameters with its own value, which effectively does nothing.
There are more usages of keyword "this".
"This" is a hidden "argument" that gets passed for you so that the methods that operate on the object know which object exactly they are to operate on.
Now imagine you pass the argument of name "x" but the class does have that var name defined already. What happens ? Well, the name x that "belongs" to the object and the argument x are not the same data-object yet they share the name.
In order to disambiguate, you need to say explicitly "this.x", which tells the compiler that you're talking about the x that already belongs to "this" object. (That is, the current object you're trying to operate on.)
In the second example, the arguments to the constructor are not a and b; they were changed to x and y, and this.x = x; means "assign this Point class instance's member variable x the value passed to the constructor as x".
This really has to do with how the java compiler identifies variables by their name. Function (formaal) parameters names precede class member variables. In the first example the formal parameter names are a and b and they do not collide with the member variables x and y so writing
x = a;
is logical as x can only mean the member variable class Point.
In the second example x refers both to the formal parameter name and to the member variable. Writing x within the function body refers to the parameter so if you need some other way in order to refer to the member variable x. This is done by explicitly accessing a member via the 'this' keyword.

Categories

Resources