Results 1 to 2 of 2
  1. #1
    yma16 is offline Member
    Join Date
    Apr 2011
    Posts
    52
    Rep Power
    0

    Default Why does change one variable also change another?

    The code has 3 class as following

    Java Code:
    import java.util.*;
    import java.awt.*;
    
    public class AList {
    	public static void main(String[] args)
    	{
            String s1,s2,s3;
    		s1="a";s3="b";
    		s2=s1;
    		System.out.println(s2);
    		s2=s3;
    		System.out.println(s1);
            GList g = new GList();
    		g.add("Luke");
        }
    }


    Java Code:
    public class GList<E>
    {
    	private static class Node<E>
    	{
    		public E data;
    		public Node<E> next;
    
    		public Node(E data, Node<E> next)
    		{
    		this.data = data;
    		this.next = next;
    		}
    		public E get()
    		{
    		    return this.data;
    		}
    	}
    private Node<E> head;
    
    public GList()
    {
    	head = new Node<E>(null, null);
    }
    public void add(E e)
    {
    	Node<E> c=head;
    	while ( c.next!=null)
    		c=c.next;
    	Node<E> newNode=new Node<E>(e, null);
    	c.next=newNode;
    }
    }


    After s2=s3, s2 contains "b". s1 still has "a". But after
    c.next=newNode, head.next is not null and contains newNode.
    Why? Thank you.
    Last edited by Fubarable; 04-17-2011 at 05:29 PM. Reason: Moderator Edit: Code tags added

  2. #2
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,233
    Rep Power
    7

Similar Threads

  1. Why wont my boolean variable change?
    By equal in forum New To Java
    Replies: 8
    Last Post: 02-22-2011, 10:43 PM
  2. can i listen to variable change in diffrent class
    By gloomy1991 in forum New To Java
    Replies: 2
    Last Post: 01-08-2011, 01:50 AM
  3. How to change JDK?
    By mew in forum Eclipse
    Replies: 5
    Last Post: 05-21-2010, 05:21 AM
  4. Change in O/p
    By shiv_122 in forum Advanced Java
    Replies: 4
    Last Post: 12-22-2008, 02:37 AM
  5. Is it possible to change the '\n' into ' ' ...
    By johnny7white in forum New To Java
    Replies: 1
    Last Post: 11-15-2007, 02:32 PM

Posting Permissions

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