Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 16 of 16

Thread: primitive vs reference data-type

  1. #1
    Junior Member
    Join Date
    Aug 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default primitive vs reference data-type

    Hello everyone!

    This is probably a really simple question but i got a little it confused.
    I wanted to write a little example which explains the difference between a non reference and a reference data type.
    So i choose 2 ints and 2 strings:
             int eins,zwei;
             string a,b; 
    ...
             eins = 3;
        	 zwei = eins;
        	 a = "before";
        	 b = a;
    //i generated an outout then i set
     
             eins = 5;
             a = "after";
    //again i generated an output

    what i expected was: eins =5 zwei= 3 a= "after" b= "after"

    BUT b is still "before"

    i thought with b= a; i set the reference to a so that b would change when i change a; where am i thinking wrong?


  2. #2
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: primitive vs reference data-type

    Strings are immutable, so:
    a = "before";
    b = a; (now they both point to the same string)

    a = "after" (now a points to a different string and b still points to the same old string because b was not changed)

    See the accepted answer here

  3. #3
    Crazy Cat Lady KevinWorkman's Avatar
    Join Date
    Oct 2010
    Location
    Washington, DC
    Posts
    5,424
    My Mood
    Hungover
    Thanks
    144
    Thanked 636 Times in 540 Posts

    Default Re: primitive vs reference data-type

    Java doesn't use the word "reference" the way you might be thinking of. It's not like a C pointer reference. Java is pass-by-value only.

    To understand what's going on, I highly recommend reading this: JavaRanch Campfire - Cup Size: a Story About Variables

    And then its follow up: JavaRanch Campfire - Pass By Value, Please
    Useful links: How to Ask Questions the Smart Way | Use Code Tags | Java Tutorials
    Static Void Games - Play indie games, learn from game tutorials and source code, upload your own games!

  4. The Following User Says Thank You to KevinWorkman For This Useful Post:

    Wolfone (August 30th, 2013)

  5. #4
    Junior Member
    Join Date
    Aug 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: primitive vs reference data-type

    I c...ok...ill try explain my understanding of this:

    i create strings a,b;
    i set a = "before"; b = a; now b is pointing to the actually same place somewhere in my memory if i got jps right? following the tuts kevin linked i copied the reference of a and gave it to b (where a and b are just some fixed adress while runtime and in this adresses is the adress of the data a and b are supposed to represent, thos stored adresses are the said remote controls in the tutorial).
    now when i set a = "after"; new memory is asigned and a new string is created for a with a new adress in my memory and the adress in a is now leading to the place in memory where the new ccreated string "after" stands. i DIDNT change the "before". therefore (cause i didn't change the reference/remote control in b) b is still pointing to the memory where "before" is stored.

    this principle applies to all classes.

    did i get that right?

    if yes: is there a possibility to simulate a structure like i thought it was? namely:
    a=c;
    b=c;
    change in c directly affects a and b.
    when i got it right changing c wouldn't do anything to a and b in this.

    thank you two for your time!

  6. #5
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: primitive vs reference data-type

    Some code to play with
    public class EditableObject {
     
    	private String message;
     
    	public EditableObject(String message) {
    		this.setMessage(message);
    	}
     
    	public String getMessage() {
    		return message;
    	}
     
    	public void setMessage(String message) {
    		this.message = message;
    	}
     
    }
    public class EditableObjectTest {
     
    	public static void main(String[] args) {
     
    		EditableObject eo = new EditableObject("before");
    		EditableObject copy = eo;
    		System.out.println(eo.getMessage());
    		copy.setMessage("after");
    		System.out.println(eo.getMessage());
    	}
     
    }

  7. #6
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: primitive vs reference data-type

    Hello.
    It is okay to use "reference" in java termilonogy.
    Suppose I have a ArrayList object arrayList that holds 'n' strings.
    I invoke shrink(arrayList). In the shrink() method I remove the last two elements. After control returns from shrink() method to the calling method the object referred to by arrayList has been changed. It has 'n-2' strings.
    Coming to String, String objects are immutable. It means once an String object is created it will never ever be modified. The operations invoked on it return another String which is again immutable.
    But if I say,
    String s1="abc", s2="abc" both s1 and s2 refer to same object.
    So using "reference" term is perfectly fine in java.

    Bottom line is it is the implementation that will decide if an object can be modified or not. But "reference" is always there.

    Syed.

  8. #7
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: primitive vs reference data-type

    Quote Originally Posted by syedbhai View Post
    String s1="abc", s2="abc" both s1 and s2 refer to same object.
    s1 and s2 would refer to two different objects which happen to hold the same value, but s1==s2 is false, they are two different objects

  9. #8
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: primitive vs reference data-type

    <code>
    public static void main(String str[]) {
    String s1="abc", s2="abc";

    System.out.println(s1.hashCode());
    System.out.println(s2.hashCode());
    System.out.println(s1 == s2);
    }
    </code>
    This is the output:
    96354
    96354
    true

  10. #9
    Junior Member
    Join Date
    Aug 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: primitive vs reference data-type

    ok..i runned your code jps.
    am i right when i say that this works, because the object you created is mutable via the method you implemented which allows to change the value of the object while the object remains at its place in memory?
    no references are changed but the data in the referenced object?
    is changing an objects values using a method of this object the only way i can achieve this?

    (concerning the s1 s2 example: == compares the reference (of non primitive types) so syeds code would create 2 different places in memory for 2 strings of same value but the comparing would give me a false. but lets say we have 2 strings with same value and i don't know in which way they were set. it could possibly be that they refer to the same object even if they probably don't?)

  11. #10
    Super Moderator
    Join Date
    Jun 2013
    Location
    So. Maryland, USA
    Posts
    5,520
    My Mood
    Mellow
    Thanks
    215
    Thanked 698 Times in 680 Posts

    Default Re: primitive vs reference data-type

    Syed, code tags are enclosed by square braces, '[tagHere]'.

  12. #11
    Junior Member
    Join Date
    Aug 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: primitive vs reference data-type

    Quote Originally Posted by syedbhai View Post
    public static void main(String str[])  {
          String s1="abc", s2="abc";
     
          System.out.println(s1.hashCode());
          System.out.println(s2.hashCode());
          System.out.println(s1 == s2);
        }
    This is the output:
    96354
    96354
    true

    that confuses me...i really thought that would give a false...

  13. #12
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: primitive vs reference data-type

    Quote Originally Posted by syedbhai View Post
    <code>
    public static void main(String str[]) {
    String s1="abc", s2="abc";

    System.out.println(s1.hashCode());
    System.out.println(s2.hashCode());
    System.out.println(s1 == s2);
    }
    </code>
    This is the output:
    96354
    96354
    true
    The compiler has optimized because s1 and s2 were declared with static strings of equal value, and since strings are immutable there was no reason to make two different String objects with the same value.
    public static void main(String str[]) {
    	String s1, s2;
    	Scanner scanner = new Scanner(System.in);
    	System.out.println("Enter s1");
    	s1 = scanner.nextLine();
    	System.out.println("Enter s2");
    	s2 = scanner.nextLine();
    	System.out.println(s1 == s2);
    	scanner.close();
    	}
    Input: a a
    Output: false

    --- Update ---

    Quote Originally Posted by Wolfone View Post
    ok..i runned your code jps.
    am i right when i say that this works, because the object you created is mutable via the method you implemented which allows to change the value of the object while the object remains at its place in memory?
    no references are changed but the data in the referenced object?
    is changing an objects values using a method of this object the only way i can achieve this?

    (concerning the s1 s2 example: == compares the reference (of non primitive types) so syeds code would create 2 different places in memory for 2 strings of same value but the comparing would give me a false. but lets say we have 2 strings with same value and i don't know in which way they were set. it could possibly be that they refer to the same object even if they probably don't?)
    Yes you are understanding correctly. The important thing to note is that both variables are linked to the same object. Note that the printlns were both done on the variable named eo and the string was updated through the variable named copy, (actually a very poor variable name for this example, my bad)
    Using a method is not the only way, any field can be changed, or any method can be called, provided it is visible and accessable (public/protected/etc).

  14. The Following User Says Thank You to jps For This Useful Post:

    Wolfone (August 30th, 2013)

  15. #13
    Junior Member
    Join Date
    Aug 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: primitive vs reference data-type

    so strings which hold the same value at compile-time get the same address but strings subsequently added at runtime would get different addresses even if they hold the same value?


    EDIT: reply to #12 update: i thought so and already tested it in your example by removing the private modification and so on.
    well copy holds a copy of the address it refers to...so its not that bad...^^

    thanks for enlightening me (again )!

  16. #14
    Super Moderator jps's Avatar
    Join Date
    Jul 2012
    Posts
    2,642
    My Mood
    Daring
    Thanks
    90
    Thanked 263 Times in 232 Posts

    Default Re: primitive vs reference data-type

    Quote Originally Posted by Wolfone View Post
    so strings which hold the same value at compile-time get the same address but strings subsequently added at runtime would get different addresses even if they hold the same value?
    This is an optimization any decent compiler should make, yes, but there is no guarantee it will happen that I know of.

  17. The Following User Says Thank You to jps For This Useful Post:

    Wolfone (August 30th, 2013)

  18. #15
    Member
    Join Date
    Jul 2013
    Posts
    219
    Thanks
    0
    Thanked 18 Times in 17 Posts

    Default Re: primitive vs reference data-type

    Wolfone,
    This link may be of help to you.
    String constant/literal pool » the Open Tutorials

    Syed.

  19. The Following User Says Thank You to syedbhai For This Useful Post:

    Wolfone (August 30th, 2013)

  20. #16
    Junior Member
    Join Date
    Aug 2013
    Posts
    17
    Thanks
    6
    Thanked 0 Times in 0 Posts

    Default Re: primitive vs reference data-type

    very interesting link! thanks!

    you three helped a lot!

    i think that solves this thread

Similar Threads

  1. Tutorial: Primitive Data Types
    By newbie in forum Java Programming Tutorials
    Replies: 3
    Last Post: July 5th, 2012, 11:56 PM
  2. [SOLVED] Converting primitive data types causing NumberFormatException
    By Melawe in forum What's Wrong With My Code?
    Replies: 11
    Last Post: December 10th, 2011, 12:30 AM
  3. [SOLVED] Instance data member vs Local variables (primitive/object reference)
    By chronoz13 in forum Java Theory & Questions
    Replies: 1
    Last Post: September 23rd, 2011, 12:42 AM
  4. Primitive data type
    By stuart harper in forum What's Wrong With My Code?
    Replies: 4
    Last Post: September 17th, 2011, 12:14 PM
  5. Fitting a large primitive into a small reference variable
    By Phobia in forum Java Theory & Questions
    Replies: 15
    Last Post: October 23rd, 2009, 03:10 PM