Results 1 to 10 of 10
  1. #1
    Join Date
    Dec 2013
    Posts
    8
    Rep Power
    0

    Default Passing variables by Value or Reference

    I am an old C Programmer who is trying to help (not do his work) my son with Java.
    Java being object orientated doesn't seem to work by passing variables to methods by Value or by Reference.
    My confusion - looking at the programing manual, methods seem to be limited to returning one variable only using the 'return' statement, e.g.
    Java Code:
    public static int[] reverse(int[] list) {
      int[] result = new int[list.length];
    
      for (int i = 0, j = result.length - 1; i < list.length; i++, j--) {
        result[j] = list[i];
      }
      return result;
    }
    Whilst I can see a method can be called with several variables, am I correct in saying a method can only return one variable through the return statement?
    An example of what I am trying to do in pseudo code:
    run main()
    declare length, breadth and depth as integers = 0
    call get_dimensions(length, breadth, depth)
    call display_volume(length, breadth, depth)
    end main


    get_dimensions(length, breadth, depth) /*passed by Reference as I need the values set and returned to main()*/
    get user to enter length;
    get user to enter breadth;
    get user to enter depth;
    return with length, breadth and depth
    end get_dimensions


    display_volume(length, breadth, depth) /*passed by value as the values will not be changed*/
    display volume = length * breadth * depth
    end display_volume


    Happy to provide code if necessary (not written as yet), noting I am simply trying to understand how to pass variables to a method, change their values and return the three variables (with new values) to the calling method.

    Maybe I shouldn't have stopped programming over the past 15 years????

  2. #2
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,023
    Rep Power
    6

    Default Re: Passing variables by Value or Reference

    Both C and Java pass by value, not by reference. If you want to return more than one value in the return statement, then you can return an instance of an object which contains those values as instance variables.

    You can also pass one or more object references as arguments and change their fields within the method itself. But you are still passing by value since you can't change the actual value (i.e. the reference) to anything else.

    Regards,
    Jim
    Last edited by jim829; 12-25-2013 at 04:20 AM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  3. #3
    Join Date
    Dec 2013
    Posts
    8
    Rep Power
    0

    Default Re: Passing variables by Value or Reference

    Jim,
    Thank you for your comments. I stand corrected about C and passing by Reference, it was by pointers.
    I have gone ahead and coded my example as follows:
    Please note I kept and commented out my first attempt with variables

    CalcVolume.java
    Java Code:
    // CalcVolume.java
    // calculates the volume of a rectangular prism
    // example of using an instance of an object
    
    public class CalcVolume
    {
    	public static void main( String[] args )
    	{
    		// create RectangularPrism object - I assume this is so we can call 'access' the methods "get_dimensions and display_volume in RectangularPrism.java
    		RectangularPrism myRectangularPrism = new RectangularPrism();
    		
    		//  int length = 0;  // variables declared (an initialised to 0) here so they visible in get_dimension and display_volume
    		//  int breadth = 0;
    		//  int depth = 0;
    		
    		myRectangularPrism.get_dimensions(/*length, breadth, depth*/);  // call get_dimensions - I initially sent in variables to be set
    		myRectangularPrism.display_volume(/*length, breadth, depth*/); // call display_volume - I initially sent in variables which were set in get_dimensions
    	}
    }
    AND RectangularPrism.java
    Java Code:
    // RectanularPrism.java
    // Class declaration with two methods
    // Called by: Application Class-CalcVolume.java
    
    import java.util.Scanner;  // to allow for input from keyboard
    
    public class RectangularPrism
    {
    	private int length;
    	private int breadth;
    	private int depth;
    		
    
    	public void get_dimensions(/*int length, int breadth, int depth*/) // I was initially sending in variables from main()
    	{	
    		Scanner input = new Scanner( System.in );
    		
    		System.out.printf("%s\n", "Enter length");
    		length = input.nextInt();
    		
    		System.out.printf("%s\n", "Enter breadth");
    		breadth = input.nextInt();
    		
    		System.out.printf("%s\n", "Enter depth");
    		depth = input.nextInt();
    
    	//	return length,breadth,depth;   // no need to return a value if using variables that are 'global'
    	}
    	
    	public void display_volume (/*int length, int breadth, int depth*/)
    	{
    		int volume = length * breadth * depth;
    		
    		System.out.printf("%s%d\n", "length is: ", length);
    		System.out.printf("%s%d\n", "breadth is: ", breadth);
    		System.out.printf("%s%d\n", "depth is: ", depth);
    		System.out.printf("%s%d", "Volume is: ", volume);
    		
    	}
    }
    OUTPUT is as follows - keyboard entry is bold (not concerned with formatting)

    Enter length
    2
    Enter breadth
    3
    Enter depth
    4
    length is: 2
    breadth is: 3
    depth is: 4
    volume is: 24

    QUESTION: The program works, however, I have declared length, breadth and depth variables as 'global' to the class - is this standard programming practice these days? I'd prefer guidance than simply being told what to do, as I learn better by reading and practicing.

    I am trying to understand so I can "guide" my son - I will not be answering his assignment question.
    Thanks for assisting
    Peter

  4. #4
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,772
    Blog Entries
    7
    Rep Power
    21

    Default Re: Passing variables by Value or Reference

    C and Java are very alike: under the hood Java passes only pointers to objects (primitives such as ints, doubles, longs etc. are an exception to the rule). Variables of object type (not primitives) contain only a pointer to the real thing. Everything is passed by value, so a copy of the object pointers are passed, and the copy points to the same object. Effectively there's only a 'refererence' to an object passed ...

    kind regards,

    Jos

    ps. avoid globals as much as possible.
    cenosillicaphobia: the fear for an empty beer glass

  5. #5
    Join Date
    Dec 2013
    Posts
    8
    Rep Power
    0

    Default Re: Passing variables by Value or Reference

    Jos,
    Thank you - is there something I could improve on with the code above?
    Regards
    Peter

  6. #6
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,772
    Blog Entries
    7
    Rep Power
    21

    Default Re: Passing variables by Value or Reference

    Quote Originally Posted by Peter Peterson View Post
    Jos,
    Thank you - is there something I could improve on with the code above?
    Regards
    Peter
    Erm, yes; I would add an appropriate constructor and the normal hoopla in that class:

    Java Code:
    public class RectangularPrism {
       private double length, width, height;
    
       // constructor:
       public RectangularPrism(double length, double width, double height) {
          this.length= length;
          this.width= width;
          this.height= height;
       }
    
       // hoopla stuff:
       public double getLength() { return length; }
       public double getWidth() { return width; }
       public double getHeight() { return height; }
    
       // sensible methods: 
       public double getVolume() { /* you do it ... */ }
    }
    The constuctor allows to create a new RectangularPrism is one go, i.e. new RectangularPrism(10, 20, 30); the 'business intelligence' method such as getVolume() know how to do their job; the hoopla stuff is just there in case of ...

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  7. #7
    Join Date
    Dec 2013
    Posts
    8
    Rep Power
    0

    Default Re: Passing variables by Value or Reference

    Jos,
    Thanks very much - I'll keep practicing and learning.
    Not sure how to close this post.
    Regards
    Peter

  8. #8
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,772
    Blog Entries
    7
    Rep Power
    21

    Default Re: Passing variables by Value or Reference

    Quote Originally Posted by Peter Peterson View Post
    Not sure how to close this post.
    There's no need to do that; if nobody responds anymore, the thread sinks down the list and is lost for the posterity ;-) Unless a spammer resurrects it (but then I'll close it instantly, after having shredded the spammer ;-)

    kind regards,

    Jos

    ps. you can set the thread title to 'solved' with the 'advanced' editor, but that isn't needed either.
    cenosillicaphobia: the fear for an empty beer glass

  9. #9
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    4,023
    Rep Power
    6

    Default Re: Passing variables by Value or Reference

    Quote Originally Posted by JosAH View Post
    ps. avoid globals as much as possible.
    Actually, Jos, I believe that his use of global in this case means instance fields (i.e. "global to the class").

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  10. #10
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,772
    Blog Entries
    7
    Rep Power
    21

    Default Re: Passing variables by Value or Reference

    Quote Originally Posted by jim829 View Post
    Actually, Jos, I believe that his use of global in this case means instance fields (i.e. "global to the class").
    Ah, yes, I see now (after rereading the code); I was assuming 'public static' stuff (I know, assumptions are a nono); private instance fields are fine of course.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Reference Type Variables
    By Nazneen Ali in forum New To Java
    Replies: 2
    Last Post: 10-15-2013, 10:56 AM
  2. Replies: 1
    Last Post: 02-28-2012, 11:34 AM
  3. Question on Passing by Reference..
    By fatabass in forum New To Java
    Replies: 1
    Last Post: 02-07-2012, 01:02 AM
  4. Replies: 9
    Last Post: 10-21-2011, 10:07 PM
  5. Passing Class Reference to method
    By nekt in forum Advanced Java
    Replies: 5
    Last Post: 03-26-2009, 06:08 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •