r/javahelp • • May 15 '20

how reference variables are passed as method arguments in Java

Hello, I am struggling to understand what this question is asking for, I know in C++ for pass by reference the address of the variable is passed and altered before returning unlike pass-by value(correct me if Im wrong) but in java I thought all values were automatically pass by reference? struggling to make sense of the question so any help at all will be greatly appreciated:)

Explain the difference between how pass-by-reference operates in C++ and how reference variables are passed as method arguments in Java. A good answer will include a simple example of each

16 Upvotes

30 comments sorted by

View all comments

7

u/firsthour Profressional developer since 2006 May 15 '20

Why don't you tell us what you know so far.

2

u/djpfg May 15 '20

Well I know when creating an object of a class you create a reference to that object

Student djpfg = new Student(22,maths,..);

would that be along the lines of what the question is asking? My notes on java are unfortunately unclear

2

u/firsthour Profressional developer since 2006 May 15 '20

A bit, the real question is asking when you call another method and pass that Java object as a parameter, what capabilities does that other method have?

Can it change a Student's number from 22 to 23 and will that change be reflected in the original object?

Can it reassign the Student you passed in to a completely new Student and will that change be reflected in the original object?

If you passed in an int, can you change the value of the int and will that change be reflected in the original int?

These are some of the questions the concepts of pass-by-reference and pass-by-value try to simplify.

These are also things that are easy to test yourself with a simple Java program.