Hi,

I am trying to print a String value like this but still not able to get it,.

my method is like this:-

Class1 {
public String mystring;
public void mymethod(){
  mystring = "";
}

//Then I am setting the value of mystring in other method like this:-
public void Method2(){
Class1 wow = new Class1();
wow.mymethod();
wow.mystring = somevalueInThisMethod;
 }
}

Now I am trying to print the value of mystring in Class1 method like this;-

Class3{
public void method3(){
Class1 wow = new Class1();
wow.mymethod();
System.out.println(wow.mystring);
}
}

Its showing null and not printing any value...
Can somebody tell me how can I make it work ?

Thanks in advance
Web_Sailor

//Then I am setting the value of mystring in other method like this:-
public void Method2(){
Class1 wow = new Class1();
wow.mymethod();
wow.mystring = somevalueInThisMethod;
}
}

Well, you've created three methods.

The first method, "mymethod", is relatively useless. You could declare and initialize mystring straight from the class instead of using a method to do it.

Method2 creates an instance of Class1 named "wow" and assigns a value to wow's mystring.

Method3 creates an instance of Class1 also named "wow" but doesn't assign a value to wow's mystring and then prints the value, which is null.

Thus, I would assume the reason is because you're never using Method2.

Here's an alternate way to do it.

Class 1:

class Class1 {

//Declaring mystring
public String mystring = "";

//Creating the class method to print the value of mystring
	public void printString() {
		//printing the value of mystring
		System.out.println(mystring);
	}
}

Class 3:

class Class3{

	//Creating the method that sets up the instance "wow"
	public static void Method2(){

		//Creating the instance "wow"
		Class1 wow = new Class1();

		//Assigning mystring a value
		wow.mystring = "somevalueInThisMethod";

		//Printing the string using the predetermined method in Class1
		wow.printString();
		
	}
}

To run:

public class Run {

	public static void main(String[] args) {
               //Runs the method defined in Class 3
		Class3.Method2();
	}

}

And now you have an output that isn't null.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.