+ 1

Why the class variable can’t be created?

public class Program { public static void main(String[] args) { public class VariableScopeTest { int someInt; public void someMethod () { int someInt; someInt = 5; // Method variable VariableScopeTest.someInt = 7; // class variable } } } }

8th Dec 2018, 8:07 AM
H T
H T - avatar
10 Answers
+ 2
1)within a method, you can't declare a class as public because the class scope is inside that method only 2)within a non-static method you can't access a non-static variable by class name i.e. VariableScopeTest.someInt = 7; is wrong 3)as the name of both non-static and local variable is same i.e. someInt , use this keyword to access non-static variable public class Program { public static void main(String args[]) { class VariableScopeTest { int someInt; public void someMethod () { int someInt; someInt = 5; // Method variable this.someInt = 7; // class variable System.out.println(someInt); System.out.println(this.someInt); } } new VariableScopeTest().someMethod(); } }
8th Dec 2018, 7:15 PM
Rishi Anand
Rishi Anand - avatar
+ 5
Try to define your class outside the Program class
8th Dec 2018, 8:15 AM
Uni
Uni - avatar
+ 3
H T, You can define same variable in multiple methods for example: method 1(){ int V1; } method (){ Int V1; } But if you define variable V1 with class scope you can't define V1 again inside method // you can only do this as a parameter method(int V1){}
8th Dec 2018, 8:29 AM
Michal
Michal - avatar
8th Dec 2018, 8:47 AM
Michal
Michal - avatar
+ 2
Create a method in the VariableScopeTest class and using this pointer assign the value to variable.
8th Dec 2018, 10:50 AM
Adarsh.n. Bidari
Adarsh.n. Bidari - avatar
+ 1
You can't create two variables with the same name and type in one class. //If variable Has class scope
8th Dec 2018, 8:23 AM
Michal
Michal - avatar
0
The error I get is: Illegal start of the expression. And the marker shows "public" in "public class VariableScopeTest"
8th Dec 2018, 8:22 AM
H T
H T - avatar
0
One variable is defined in the class and the other one is defined inside the method not the class. I'm testing the variable scope here.
8th Dec 2018, 8:24 AM
H T
H T - avatar
0
Michal hmmm So what is the meaning of this expression: VariableScooeTest.someInt = 7;
8th Dec 2018, 8:34 AM
H T
H T - avatar
0
Rishi Anand Tx a lot sir
10th Dec 2018, 7:27 AM
H T
H T - avatar