Click here to Skip to main content
15,881,715 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
class Temp
{
int x;
{
this.x=100;
System.out.println("Init Block");
}
Temp()
{
this(20);
System.out.println(x);
System.out.println("default");
}
Temp(int x)
{
System.out.println(x);
System.out.println(x);
}
public static void main(String...a)
{
Temp t = new Temp();
}
}
// output
Init block
20
20
100
default

why not output comes

init block
100
100
100
default

What I have tried:

class Temp
{
int x;
{
this.x=100;
System.out.println("Init Block");
}
Temp()
{
this(20);
System.out.println(x);
System.out.println("default");
}
Temp(int z)
{
System.out.println("init block value" +z);
System.out.println("Constructor value" +x);
}
public static void main(String...a)
{
Temp t = new Temp();
}
}
// No data shadowing, problem arises when data shadowing is used
Posted
Updated 15-Oct-16 6:29am
Comments
Suvendu Shekhar Giri 15-Oct-16 11:31am    
so what is question here?
Member 12785791 15-Oct-16 11:40am    
when init block comes in constructor. Is variable x is a local part of constructor or not if its local part then why it prints 100 instead of printing 20.
Member 12785791 15-Oct-16 11:42am    
because local priority is always high and this thing is confusing me
Member 12785791 15-Oct-16 13:01pm    
yup this my typing mistake i am sorry

1 solution

Your constructor will print that value of parameter x Not instance value x. If you want the latter then you need to use the this Prefix to disambiguate it, thus:
Java
System.out.println(this.x);
 
Share this answer
 
Comments
Member 12785791 15-Oct-16 12:44pm    
Thank You Sir for clearing my doubt
Richard MacCutchan 15-Oct-16 12:53pm    
What you have is not a static block, it is an initialiser.
Member 12785791 15-Oct-16 13:00pm    
yup, that is mine typing mistake i am sorry.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900