Reputation: 13
I am trying to print static int value in main method of java, when I am printing it is giving me value as [Ljava.lang.String;@7852e922
as object notation instead of actual value. Could you please explain what is happening under internally.
Also, when I am trying using ClassName.varibaleName its working and printing correct value. Also, when I am printing using object. it is showing the correct result.
I am seeing the issue only when I am directly accessing the value of static variable in main method.
I also, tried creating other method and it is giving the result.
class Demo1 {
static int a;
public static void main(String a[]) {
Demo1 demo1 = new Demo1();
demo1.inc();
Demo1 demo2 = new Demo1();
demo2.inc();
Demo1 demo3 = new Demo1();
demo3.inc();
System.out.print("Count value is=" + a);
System.out.print(a);
System.out.print("\n" + demo1.a);
System.out.print(demo2.a);
System.out.print(demo3.a);
}
public static void inc() {
a = a + 1;
System.out.println("Value a" + a);
}
}
I am getting below Result:
Value a1
Value a2
Value a3
Count value is=[Ljava.lang.String;@7852e922[Ljava.lang.String;@7852e922
333
But expecting Count value is= 3
instead of [Ljava.lang.String;@7852e922
Upvotes: 0
Views: 70
Reputation: 262494
Your int a
is not visible in a method that also has a local variable called String[] a
(which will be used instead).
This is called "shadowing". The "closest" variable definition wins.
Use better variable names to avoid this.
Upvotes: 3