scope of variable inside main in Java? [duplicate] - java

This question already has answers here:
Why does Java not have block-scoped variable declarations?
(6 answers)
Closed 9 years ago.
Am I correct that a block inside main() doesn't have separate scope?
For example, if I do the following, I will get compile error:
static int i = 1;
public static void main(String[] args) {
int i = 2;
{
int i = 3;
}
}
Why is this?

When I try to compile this, I get this message:
error: variable i is already defined in method main(String[])
This means that the static int i = 1; does not cause the error. The scope of the first i in main is for the whole main, so when you try to make another one, in the code block, you get an error.
Note that if you declared the i in a block:
public static void main(String[] args){
{
int i = 2;
}
{
int i = 3;
}
}
You don't get a compile error (see here).
The static int can be accessed in one of two ways: this.i (not recommended) or ClassName.i (recommended for accessing of a static variable)

Java does not allow obfuscation of stack (ie. local variables). You can obfuscate an instance or class variable because there are other ways to access them (ie. this.i for instance, or MainClass.i for static).

Related

Java variable scope in and outside loop [duplicate]

This question already has answers here:
Java variable may not have been initialized
(7 answers)
Why does the Java compiler not understand this variable is always initialized?
(3 answers)
Closed 2 years ago.
I wrote this code in an online java test recently. It was inside a method that was set to return an integer. I got an error message something like "variable a has no value assigned to it". I find this odd because the forloop must have access to the methods variable and the assignments inside of the loop must be registered right?
int a;
for(int i=1;i<5;i++){
a = i;}
return a;
I did assume that the method would return the integer 5.
This is only a question regarding scope of the variable a. I know that the code makes no sense.
You can try below code , that will help you. Initialisation is mandatory for any variable to return or hold any value.
class a{
public static void main(String[] args) {
System.out.println(test());
}
public static int test(){
int a = 0;
for(int i=1;i<5;i++){
a = i;}
return a;
}
}

Static Variables in Java [duplicate]

This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
What is the difference between referencing a field by class and calling a field by object?
(5 answers)
Closed 5 years ago.
I know that static variables are part of class and not part of the Object . How can the following lines of code work without any problem
class M
{
static int i=0;
void Inc()
{
System.out.println("Global "+M.i);
System.out.println("Local "+this.i);
}
}
public class StaticTest
{
public static void main(String args[])
{
M m1=new M();
m1.i=99; //How can the m1 object access i variable of the class
m1.Inc();
}
}
The output i get is
Global 99
Local 99
How can the m1 object access i variable of the class?
It is the very same i variable in both cases.
unfortunately, java allows you to access static fields using non-static syntax.
That is all there is to this, nothing else behind this.
Yes, it is allowed for non-static members to access and update static members.
See this for more information here

Instance variable value not being printed [duplicate]

This question already has answers here:
non static variable name cannot be referenced from a static context [duplicate]
(5 answers)
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 6 years ago.
I am trying to learn java. currently learning about types of variables.
i have written a small program defining instance,local,static variables and trying to print the same from with in the main method. but i am getting error saying "non static variable i cannot be referenced from static context. Below is my program
public class variable{
int i=5;
static int j=10;
public static void main(String[] args){
int k=15;
System.out.println(i);
System.out.println(j);
System.out.println(k);
}
}
Please let me know whats wrong with the program
You need to create a instance of variable and access i
variable v = new variable();
// then access v.i
BTW use Camelcase for you class name.
int i should be static becasue static context cant refer to the non-static variable
Options:
Make a new instance of your class so you can reach i. In fact it is maybe not the best option, because you should make it private, and add a getter method... :)
OR
You could change int i to static int i, because of the static main method.
+1 : it is better to have classnames camescased... :)

When are initializer blocks used in java? [duplicate]

This question already has answers here:
What is an initialization block?
(10 answers)
Closed 7 years ago.
I read that an initializer block is "an unnamed code block that contains th code that initializes the class?
For example :
class A {
final int x;
final int y;
final String n;
{
x = 10;
y = 20;
}
public A(String name ) {
/* etc... etc */
I have never seen this type of code used, so I was wondering where it may be helpful. Why don't we just initialize variables in constructor ?
thanks
I think it can sometimes be helpful to initialize a variable immediately when it is defined.
public class Stooges {
private ArrayList<String> stooges = new ArrayList<>();
{ stooges.add("Lary"); stooges.add("Curly"); stooges.add("Moe"); }
// ... etc. other methods.
}
That initializer is now common to all constructors, so it avoids code duplication. You could use a private method and call similar code from within all constructors, but this way avoid even remembering to insert a method call. Less maintenance!
There could be other examples. If the initializer code calls a method that throws an exception, then you can't just assign it. You have to catch the exception.
A common use for this is the static initializer block:
class A {
static boolean verbose;
final int x;
final int y;
final String n;
static {
verbose = doSomethingToGetThisValue();
}
public A(String name ) {
/* etc... etc */
This is useful because your static variables might be used by a static method before an instance of the class is ever created (and therefore before your constructor is ever called).
See also this SO answer.

Java custom method not working [duplicate]

This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 7 years ago.
I'm a beginner and I'm starting to learn programming by doing some
exercises...
Why this simple java code gives me an error?
class HelloWorldEdited {
public int a = 5;
public int b = 2;
public static int sum() {
return a + b;
}
public static void main(String[] args) {
HelloWorldEdited obj = new HelloWorldEdited();
System.out.println(obj.sum());
}
}
I think it's because you are accessing "non static" properties (a, b) from a static method (sum), this operation is forbidden.
Try to change
public static int sum()
to
public int sum()
To understand the "static" modifier I suggest you to read:
official tutorial
The method sum() is static. In this method you can't access variables "non static".

Categories