This week's book giveaway is in the Agile and other Processes forum. We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line! See this thread for details.
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
Joined: Jan 08, 2002
Posts: 411
posted
0
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
Joined: Dec 03, 2001
Posts: 40
posted
0
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 } }
--------------------<p>Karen Leoh<br />Sun Certified Programmer for Java™ 2 Platform
Kaspar Dahlqvist
Ranch Hand
Joined: Jun 18, 2001
Posts: 128
posted
0
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;