• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Jeanne Boyarsky
  • Paul Clapham
Sheriffs:
  • Devaka Cooray
  • Ron McLeod
  • paul wheaton
Saloon Keepers:
  • Tim Moores
  • Piet Souris
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Al Hobbs
  • Frits Walraven
  • Scott Selikoff

explanation of Code

 
Ranch Hand
Posts: 168
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
public class Test1
{
static int k=1;
{
k=k*2;
}

public static void main(string args[])
{
System.out.println(k);
}
}

The output is 1 but i think it must be 2. How is it so? Please help me.
 
Ranch Hand
Posts: 558
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

instance blocks will run just before constructor.
There is no constructor call. and so is instance block call.
 
Ranch Hand
Posts: 447
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi

Gaurav Pavan Kumar Jain

{
k=k*2;
}
This is an instance block means when ever you create an instance of that class this code will be executed ,but before completion of execution of constructor
here in your case your not creating the object of that class.
If you have doubt create the object of that class,then you will come to know
 
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Gaurav,

Your output is correct. It should be 1. Because the code block k=k*2; is not put inside a static block. Its just a normal block. Your static declaration of k is ended with ;

If you want your output to be 2, then your code must be,
 
Chris Jebaraj
Ranch Hand
Posts: 34
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
As srinivasan said, you havent called the constructor. If you want the k=k*2 as a instance block and not a static one, then your code should be

 
I wish to win the lottery. I wish for a lovely piece of pie. And I wish for a tiny ad:
the value of filler advertising in 2021
https://coderanch.com/t/730886/filler-advertising
reply
    Bookmark Topic Watch Topic
  • New Topic