main method in java
Hello Sir
I m new to java .
I am trying to declare variables in main() method as static.
But i am getting errors
"
Illegal modifier for parameter b; only final is permitted
"
I m not getting its reason and its rectification.
Plz help me.
Thanx in advance.
Khushwinder
> ok sir. but this is leading to 2 more questions in my
> mind . plz clarify them.
>
> 1) i have read that we can only reference static variables in a static method.
> Then how can i main > method take the non static variables as well.
> 2)But this thing is not applicable to main method() . why?
You don't declare in static variable inside a static method, but you could reference to a static variable.
here is an example
public class Test {
private static int num = 10;
private String str = "abc";
public static int getNum() { // static method referencing static variable
return this.num;
}
public String getStr() { // non-static method referencing non-static variable
return this.str;
}
public static void main(String[] args) {
int myNum;
String myStr;
myNum = getNum(); // calling static method
Test myTest = new Test();
myStr = myTest.getStr(); // calling non-static method
System.out.println(myNum);
System.out.println(myStr);
}
}
Static variables belong to a Class. Declaring them inside a method (static or non-static) makes them local variables to that method and cannot be seen outside of that method. Thus defeating the purpose of them being static.
> i have read that we can only declare static variables in a static method.
Whoever told you that, is misinformed.