Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

variable initialisation

 
weiliu lili
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Test026
{
static Test026 t = new Test026();
String str;
public static void main(String args[]) {
Test026 t = new Test026();
t.method("0");
}
void method(String str) {
str = str;
System.out.println(str);
System.out.println(t.str);
System.out.println(this.str);
}
}
-----------------------------------------------------------------------
The output is:
0
null
null

the explanation:
The str for object t and this remains uninitialised and keep null value
I thought str has already been initialised as "str=str", where m i wrong?
thanks
 
Jamal Hasanov
Ranch Hand
Posts: 411
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Weilliu
change
str = str;
to
this.str = str;
str is an object given as a parameter. For accessing class's str you must refer to this
Thanx,
Jamal Hasanov
www.j-think.com
 
Karen Leoh
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi there..
I hope this helps. When you initialise "str=str", it is done locally. The instance variable is str is still null.
Correct me if I'm wrong.
public class Test026
{
static Test026 t = new Test026();
String str; //this is initialised to null
public static void main(String args[]) {
Test026 t = new Test026();
t.method("0");
}
void method(String str) {
str = str;
System.out.println(str);
System.out.println(t.str); //this called the instance variable str which is null
System.out.println(this.str); //this also call the instance variable str
}
}
 
Kaspar Dahlqvist
Ranch Hand
Posts: 128
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Howdy!
Method void method(String s) is currently too ambiguous for the compiler... Right now your method receives a reference to a String called str, and what you do with
str = str;
is to tell Java that you want str to reference the String that str points to. But, hey, it already does...
In your code you create two objects from the class Test026, and each has a instance variable called str. To initialize these to values other than null, you need to use the references to those objects. In other words, in an appropriate place, do the following:
t.str = str;
this.str = str;

Getting the hang of riding, yet?
/Kaspar
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic