noob Java question - help appreciated :)

Associate
Joined
20 Oct 2002
Posts
610
Location
Glasgow
Hi there,

I am trying to learn Java from scratch as part of a course and am going though some assignments.

My current problem is:

I want to use a variable for assigning names to other variables. Is it possible to use a variable for assigning other variables? I don't think we come onto arrays etc until later in the course so I'm thinking they are looking for a simple way to do this.

Never used Java before so its all new to me :)

Thanks in advance for any help you can give.
 
Can you expand a little on what your aim is? Why do you want to be able to use a variable to name another?

As far as I know this is not possible in Java and I think you are trying to do something that can be done another way. Java is quite strict and a strongly-typed language that stops you from doing this where as something like PHP would let you do this easily but there is normally a good reason for doing so.
 
As RobH has said, we need to know a bit more about what you are after. As it is your first assignment I doubt they would be asking for anything very complicated.
 
As far as I know the only way to name a variable with a variable name is to use a map, and have the variable name as the key for a value in the map.
 
It sounds like a very early assignment, especially if they haven't even covered arrays, so I think using a map is going way beyond what is being asked of him.
 
Do you mean something like:


string name = "John";
string thesamename = name;
string anothername = "John";

Console.Write(name == thesamename);
Console.Write(name == anothername);
Console.Write(name.Equals(anothername));
 
Yeah it sound like one of the first tutorials I did at Uni when learning Java where we had to experiment with equality using '==' and '.equals()' . Where '==' is reference equality and '.equals()' is value equality. So:

Code:
String name1 = "john";
String name2 = "john";
System.out.println(name1 == name2);          // false
System.out.println(name1.equals(name2));     // true

then if...

name2 = name1
System.out.println(name1 == name2);          // true
 
Last edited:
Back
Top Bottom