public class NewTest {
@Test
public static void main(String [] args) throws IOException {
new NewTest();
NewTest.test();
System.out.println(myname);
}
public static void test(){
String myname = "Sivarajan";
}
}
How to print myname
? Initialization error appeared while running this program.
Java variables have different scopes . If you define a variable inside a method it is non usable inside another method.
ways to fix it in your code:
public class NewTest {
public static String myname = "Sivarajan";
@Test
public static void main(String [] args) throws IOException
{
/*Note that since you are working with static methods
and variables you don't have to instantiate any class*/
System.out.println(myname);
}
test
return a String public class NewTest {
@Test
public static void main(String [] args) throws IOException
{
NewTest newt = new NewTest();
System.out.println(newt.test());
}
//Note that we did remove the static modifier
public String test(){
String myname = "Sivarajan";
return myName;
//or simply return "Sivarajan";
}
}
Further reading:
http://docs.oracle.com/javase/tutorial/java/javaOO/variables.html
Because your variable myname
is declared and initialized inside of the test()
method, it is unusable anywhere else in your program. You could have the test()
method return a String like this:
public class NewTest {
@Test
public static void main(String [] args) throws IOException {
new NewTest();
NewTest.test();
System.out.println(test());
}
public static String test() { //Changed to return a String
return "Sivarajan";
}
}
or declare it as a class variable and then use it in all methods of the class thereafter
public class NewTest {
String myname = "Sivarajan"; //added myname as a class variable
@Test
public static void main(String [] args) throws IOException {
new NewTest();
NewTest.test();
System.out.println(myname);
}
}
What I think you are trying to achieve involves using 'fields' of an object. What you have done is declared a variable inside a method, meaning it can only be referenced inside that method. By declaring a field you can then create objects of your class, and each one will have that field to access, like the below:
public class NewTest {
public static void main(String [] args) {
//Create NewTest object
NewTest tester = new NewTest();
//Run the method on our new Object
tester.test();
//Print the field which we just set
System.out.println(tester.myName);
}
//Set the field
public void test(){
myName = "Sivarajan";
}
//A public field which is accessible in any NewTest object that you create
public String myName = "";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.