Loose blocks of code - java

When I try running this piece of code, it prints "x y c g ". I know that x has priority over y because it is static and the constructor (c) prints before the method (g), but what exactly is the purpose of putting two lines in their own blocks, and what does this help achieve?
public class Sequence {
Sequence() { System.out.print("c "); }
{ System.out.print("y ");}
public static void main(String[] args) {
new Sequence().go();
}
void go() { System.out.print("g "); }
static { System.out.print("x "); }
}

Your question is closely related to this one, but not exactly a duplicate: Why java Instance initializers?
When you first reference a class, it gets loaded and the static components get initialized in the static initializer. These blocks can be very useful, for setting up collections or loading native code.
An instance initializer is a bit of code that works similar to the static initializer except it operates on every instance before the constructor is invoked. It appears that there is no absolute need for this in Java since it can just be placed in the beginning of your constructor.

Related

Why Instance Initialization blocks are executed first than constructors?

I'm not able to get exactly why this code gives an output 0?
public class Poly
{
public static void main(String[] args)
{
Square sq=new Square(10);
}
}
class Square
{
int side;
Square(int a)
{
side=a;
}
{
System.out.print("The side of square is : "+side);
System.out.println();
}
}
What I want to ask-
Why it is showing output 0,and not 10?
Why Instance Initialization Block is initializing first and then
constructors?
It's not an instance initializer's job to completely initialize the whole object, you can have multiple initializers that each handle different things. When you have multiple initialization blocks they run in the order in which they appear in the file, top-to-bottom, and they cannot contain forward references. This article by Bill Venners has a lot of useful detail.
On the other hand, a constructor is responsible for initializing the entire object. Once the constructor has run the object is initialized, it should be in a valid state and be ready to be used.
So if an instance initializer ran after the constructor it wouldn't be initializing, it would be changing something that was already set. So the initializers have to run before the constructor.
Order is something like this, the static blocks go first and then the non static blocks. Then the Constructor.

eclipse acting weird when creating methods

I don't see what could be wrong here, I was working on a different method but had some problems so I tried to simplify it to check where could the mistake be but I ended going up into this very simple method and still I have the same error.
When I put the mouse over the redX at line 6 I get a message saying:
multiple markers at this line
-Syntax error on token "(",;expected
-Syntax error on token ")",;expected`
mouse at line 7 says:
void method cannot return a value
2 quick fixes available
change method return type to 'int'
change to 'return;'
I changed public static void to public static int and also changed the method's modifier but the error at line 6 appears everytime.
I don't see anything wrong here but I think I'm making a mistake that just needs a simple fix, am I going crazy? never had this particular problem before
The problem is that you are declaring a method called y within the main method. In Java, you cannot nest method declerations.
You will have to move it outside the main method scope or else, declare a private inner class which will hold your y method.
In short:
public class gat {
public static void main(String args[]) {
...
}
int y(int a) {
return a + 5;
}
}
Or:
public class gat {
public static void main(String args[]) {
class inner {
int y (int a) {
return a + 5;
}
}
}
}
The first approach is the most common, however you sometimes do end up using the second approach, especially when dealing with Swing Events and other threading aspects.

Java static method vs main static method

I'm having trouble understanding the following code's execution. I want to follow the Java program so that I can understand how everything works together. I step up breakpoints in Eclipse but it doesn't explain why. Here's the code:
public class Sequence {
public Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}
The output to the code is x y c g. Can someone explain why this is? I thought the program entry point was public static void main but it appears static executes first?
The static block is executed before the main starts, so x get printed.
Then we enter the main, and we call
new Sequence().go();
Which calls the Sequence constructor. As per the static block, before The Sequence constructor gets called (so before a new Sequence object gets initialized), the instance block (the one written within the braces) gets executed, so y gets printed.
Then the constructor call prints c.
In the end, the go() method gets called on the newly created object, so g gets printed.
So the full output will be
x y c g
The JLS is of help here, chapter 12 to be precise.
First the static block will run. This will happen when the class is loaded by the ClassLoader.
Then main will run, this is executed by the JVM to start the application.
Then your constructor is executed when you call new Sequence(). The compiler will yank your instance initialiser (the bit in curly brackets) into the top of the constructor (after the implicit call to to the superclass constructor). So the bit in curly brackets runs first then the code in the constructor.
Finally the method go() is called.
So the output of the code is x y c g
Java execute static block after class loading and before any method. Main method is entry point for any program but it is however a method then static class initialization.
In your class you have used
//constructor
public Sequence() {
System.out.print("c ");
}
//instance init block
{
System.out.print("y ");
}
//method
void go() {
System.out.print("g ");
}
//static init block
static {
System.out.print("x ");
}
-> Init blocks execute in the order they appear.
->Static init blocks run once, when the class is first loaded.
-> Instance init blocks run every time a class instance is created.
-> Instance init blocks run after the constructor's call to super().
->Constructor run after when you create an instance.
According all of that rules you got,as expected x y c g output
First jvm loads static blocks when application starts. So static block executed first.
Then main method execution starts.
{
System.out.print("y ");
}
is the constructor block it will be copied to each constructor so when u instantiate class it will be called every time.
Click here
Steps:
i. When class is loaded then static block is executed first.
ii. Every time object of that class is instantiated then initialization block
i.e.
{
System.out.print("y ");
}
is executed(every time) and after that the time of constructor comes to be executed.
iii. When object creation is finished then go() method is executed.
And hence the output.

Calling a Java method with no name

I'm looking at the code below and found something a bit strange:
public class Sequence {
Sequence() {
System.out.print("c ");
}
{
System.out.print("y ");
}
public static void main(String[] args) {
new Sequence().go();
}
void go() {
System.out.print("g ");
}
static {
System.out.print("x ");
}
}
I would've expected this to give a compilation error as the System.out with "y " doesn't belong to a method declaration just a { }. Why is this valid? I don't see how this code would or should be called.
When running this it produces x y c g also, why does the static { } get called before the sequence constructor?
This:
static {
System.out.print("x ");
}
is a static initialization block, and is called when the class is loaded. You can have as many of them in your class as you want, and they will be executed in order of their appearance (from top to bottom).
This:
{
System.out.print("y ");
}
is an initialization block, and the code is copied into the beginning of each constructor of the class. So if you have many constructors of your class, and they all need to do something common at their beginning, you only need to write the code once and put it in an initialization block like this.
Hence your output makes perfect sense.
As Stanley commented below, see the section in the Oracle tutorial describing initializaiton blocks for more information.
Its not a method but a initialization block.
{
System.out.print("y ");
}
It will be executed before the constructor call.
While
static {
System.out.print("x ");
}
is static initialization block which is executed when class is loaded by class loader.
So when you run your code
Class is loaded by class loader so static initialization block is executed
Output: x is printed
Object is created so initialization block is executed and then constuctor is called
Output: y is printed followed by c
Main method is invoked which in turn invokes go method
Output: g is printed
Final output: x y c g
This might help http://blog.sanaulla.info/2008/06/30/initialization-blocks-in-java/
That's an instance initialization block followed by a static initialization block.
{
System.out.print("y ");
}
gets called when you create an instance of the class.
static {
System.out.print("x ");
}
gets called when the class is loaded by the class loader. So when you do
new Sequence().go();
the class gets loaded, so it executes static {}, then it executes the instance initialization block {}, afterwards the body of the constructor is called, and then the method on the newly created instance. Ergo the output x y c g.
static {
System.out.print("x ");
}
Is a static block and is called during Class Loading
{
System.out.print("y ");
}
Is an initialization block
You can have multiple initialization blocks in a class in which case they execute in the sequence in which they appear in the class.
Note that any initialization block present in the class is executed before the constructor.
static {
System.out.print("x ");
}
is an initialization block shared by the class(as indicated by static), which is executed first.
{
System.out.print("y ");
}
is an initialization block shared by all objects(constructors) of the class, which comes next.
Sequence() {
System.out.print("c ");
}
is a particular constructor for the class, which is executed third. The instance initialization block is invoked first every time the constructor is executed. That's why "y" comes just before "c".
void go() {
System.out.print("g ");
}
is just an instance method associated with objects constructed using the constructor above, which comes last.
{
System.out.print("y ");
}
These kinds of blocks are called initializer block. It is executed every time you create an instance of a class.
At compile time, this code is moved into every constructor of your class.
Where as in case of static initializer block: -
static {
System.out.println("x ");
}
it is executed once when the class is loaded.
We generally use static initializer block when the initialization of a static field, require multiple steps.
It is used as an initialisation block and runs after any static declaration. It could be used to ensure that no one else can create an instance of the class (In the same way you would use a private constructor) as with the Singleton design pattern.
static {
System.out.print("x ");
}
Static blocks are only executed once when the class is loaded and initialized by the JRE.
And non-static block will be call every time your are creating a new instance and it will be call just before the Constructor.
As here you've created only 1 instance of Sequence so constructed has been called after non-static blocks and then the method which actually your goal.

Why is this Java code in curly braces ({}) outside of a method?

I am getting ready for a java certification exam and I have seen code LIKE this in one of the practice tests:
class Foo {
int x = 1;
public static void main(String [] args) {
int x = 2;
Foo f = new Foo();
f.whatever();
}
{ x += x; } // <-- what's up with this?
void whatever() {
++x;
System.out.println(x);
}
}
My question is ... Is it valid to write code in curly braces outside a method? What are the effects of these (if any)?
Borrowed from here -
Normally, you would put code to initialize an instance variable in a
constructor. There are two alternatives to using a constructor to
initialize instance variables: initializer blocks and final methods.
Initializer blocks for instance variables look just like static
initializer blocks, but without the static keyword:
{
// whatever code is needed for initialization goes here
}
The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code between multiple constructors.
You may also wanna look at the discussions here.
This is an initializer block that is executed while the instance of the class is being loaded/created and that is used to initialize member properties of a class (See Java http://download.oracle.com/javase/tutorial/java/javaOO/initial.html). You can have as many blocks as you want and they will be instantiated from top to bottom.
In addition to the instance block, you can have as many static blocks as you want as well to initialize static members. They would be declared as follows:
public class Initialization {
static int b = 10;
int a = 5;
static {
b = -9;
}
{
a += 2;
}
public static void main(String[] args) throws Exception {
System.out.println(ClientVoting.b);
System.out.println(new ClientVoting().a);
System.out.println(ClientVoting.b);
System.out.println(new ClientVoting().a);
}
static {
b = 1;
}
{
a++;
}
}
While the class is being initialized, the static member "b" is initialized as 10, then the first static scope changes its value to -9, and later to 1. This is only executed once while the class is loaded. This executes before the initialization of the first line of the main method.
On the other hand, the similar example to your class is the instance reference "a". A is initialized as 5, then the instance block updates it to 7, and the last block to 8. As expected, the static members are only initialized once in this code, while the instance blocks are executed EVERY time you create a new instance.
The output to this example is 1 8 1 8
It's an initializer block. It's used to set instance variables. The motivation to use initializer blocks over constructors is to prevent writing redundant code. The Java compiler copies the contents of the block into each constructor.

Categories