Java, Java, Java!!!!!!!!!!!!!!

Java, Java, Java!!!!!!!!!!!!!!
 
public class Test{
public int aMethod(){
static int i=0;
i++;
return i;
}
public static void main(String args[]){
Test test = new Test();
test.aMethod();
int j=test.aMethod();
System.out.println(j);
}
}
 
This code looks perfectly okie for any person who is well through in C++ and who starts learning Java. But it is not a complilable code. This gives complilation error at line number 3. The reason is very simple, you can’t have a static variable inside any function. They can only be declared as Class variables. If you wanna have the same expected functionality as in C++, the above code can be modified as,
public class Test{
static int i=0;
public int aMethod(){
i++;
return i;
}
public static void main(String args[]){
Test test = new Test();
test.aMethod();
int j=test.aMethod();
System.out.println(j);
}
}
 
Cheers,
rOCk

1 thought on “Java, Java, Java!!!!!!!!!!!!!!

Leave a comment