I want to "execute" main() method before the static block is called. As per Java rules Static block will be executed when the class is loading and then main() method is called. Is there any way to first "execute" main method and then static block?
public class StaticDemo {
static {
System.out.println("in static block");
}
public static void main(String args[]){
System.out.println("in main method");
}
}
The output will be....
in static block
in main method
calling main method from static block just generate expected output. but it first executed static block and from that it called main method.
import com.sun.javaws.Main;
public class StaticDemo {
static {
main(null);
System.out.println("in static block");
}
public static void main(String args[]){
System.out.println("in main method");
}
}
The output will be...
in main method
in static block
in main method
My expected output is....
in main method
in static block
Is there any way to first "execute" main method and then static blk
No. There isn't. Not that static block.
Assuming that you want to execute some code after the main method has finished, you could:
put the code into a method that you call at the end of the main method,
put the code into an uncaught exception handler for the main thread and deliberately throw an exception in main(), or
put the code into a shutdown hook.
You could also put the code into the static block for a different class, and either dynamically load / initialize it, or trigger it in various ways. But calling a method is simpler.
It's not possible with a static block, but you could use an instance initializer block:
public class Loader {
{
System.out.println("in instance initializer");
}
public static void main(final String[] args) {
System.out.println("in main method");
new Loader();
}
}
Related
I'm toying around with instance control flow and static control flow, notice the code below
class A {
{
m1();
}
A(){
System.out.println("A constructor");
}
void m1(){
System.out.println("A m1");
}
}
public class Main extends A {
public static void main(String[] args) throws Exception {
Main m = new Main();
}
void m1(){
System.out.println("Main m1");
}
}
The output for the code is:
Main m1
A constructor
I know this is because:
First, static blocks and variables were identified top-to-bottom parent-to-child, in this case there was just a main() that was static. Second, the static blocks and variable assignments are executed, so main()'s execution starts, and there is an attempt to create a new Main object.
So third, the instance blocks and variables of parent class will be identified. Then they will be executed top-bottom. (After that the constructor of the parent class will run, then the instance blocks and variables of child class will be identified, following which they will be executed top-bottom and finally the child class' constructor will execute).
So the instance block inside A, calls `m1()`. Then, A's constructor executes. Finally, control flow is returned to `main()` and program terminates.
Now, the call to `m1()` from A invoked `m1()` of `Main`. However, had I made both the `m1()` methods static, everything else remaining same, the call to `m1()` from the instance block of A would then have invoked `m1()` of A.
I have two questions(Why? Purely for academic reasons, I'm still learning Java):
When both the m1() methods are non-static, is it possible to invoke A's m1() from the instance block of A? I tried doing a this.m1() but that still invoked Main's m1().(Why?)
When both the m1() methods are static, is it possible to invoke Main's m1() from the instance block of A? (I'm guessing no but I'm not certain).
I know in the first case, it's overriding taking place, and in the second case it's method hiding. But I'm still not sure how to answer my questions based on that knowledge.
After compilation is done java 8 compiler your code looks like this:
class A {
A() {
this.m1(); // at runtime this refers to Main class instance
System.out.println("A constructor");
}
void m1() {
System.out.println("A m1");
}
}
public class Main extends A {
public Main() { }
public static void main(String[] args) throws Exception {
Main m = new Main();
m.m1();
}
void m1() {
System.out.println("Main m1");
}
}
Now to answer your first question: No. You cannot unless you are creating an instance of A(actual object of A).
To your second question:
after making both m1's static compilation looks like this:
class A {
A() {
m1(); // resolves to A's m1
System.out.println("A constructor");
}
static void m1() {
System.out.println("A m1");
}
}
public class Main extends A {
public Main() {
}
public static void main(String[] args) throws Exception {
new Main();
}
static void m1() {
System.out.println("Main m1");
}
}
Now no matter which instance(A or Main) you create you will see A's m1 excuted.
1.(When two methods are instance method) If you are inside the A (parent) class, if you call m1(); or this.m1(); you will call the A version of the m1() method but if you are inside the main class (child), if you call m1(); you will call the main version of m1 although if you call super.m1(); you will be calling the A version of m1 method.
2.(If the methods are static) you can call each version wherever you want, without and object of a class, for example, you can invoke mainĀ“s m1 method inside the A block with the following line Main.m1(); // ClassName.StaticMethodName();
When I try to call the lyrics function in this code, "invalid method declaration; return type required" occurs.
I'm learning java and very very new to it. I'm confused how to define the function and call the function so that code may run.
public class Main {
public static void main(String[] args) {
}
public void lyrics() {
System.out.println("some lyrics here");
}
lyrics();
}
Normally, one can't just invoke a method randomly in the body of the code. However, there is something called an initialization block (this gets run in the body of the constructors of the object). I think an example might clarify. Like,
public class Main {
public static void main(String[] args) {
new Main(); // <-- instantiate an instance of Main
}
public void lyrics() {
System.out.println("some lyrics here");
}
{ // <-- this is an initialization block
lyrics();
}
}
The above uses the default constructor, we can add an explicit one. Like,
public Main() {
super();
System.out.println("In Main constructor");
}
Note how the output changes.
They can also be static (and run when the class is first referenced). Like,
public class Main {
public static void main(String[] args) {
}
public static void lyrics() {
System.out.println("some lyrics here");
}
static {
lyrics();
}
}
Your code is nearly correct. Your lyrics() method must be static if you want to call it inside main method because main method is static. Non static members cannot be accessed from static method (without creating an instance to invoke it).
public class Main {
public static void main(String[] args) {
lyrics();
}
public static void lyrics() {
System.out.println("some lyrics here");
}
}
You can invoke non-static methods from static method by creating an instance of the class containing non-static method inside your main method as mentioned in comments by Elliott Frisch.
new Main().lyrics();
Since you're learning Java, you must remember that the only way to call a non-static method from a static method is to have an instance of the class containing the non-static method.
Or you can simply make your function static. Also, you need to call the function inside the main block.
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
Happy coding!
The method should be declared as static and function call should be within main method. The correct code should look like as follows:
public class Main {
public static void main(String[] args)
{
lyrics();
}
public static void lyrics()
{
System.out.println("some lyrics here");
}
}
You need to move the call to lyrics() into the main method where code is actually executed. Where you have it now, the compiler is expecting a new method defination.
public class Main {
public static void main(String[] args) {
// execution begins here.
new Main().lyrics();
}
public void lyrics() {
System.out.println("some lyrics here");
}
}
EDIT: created new class Main class to avoid errors.
Basically which one will execute first the main method or the constructor?
public class ConstructorExp {
public ConstructorExp() {
System.out.println("Ctt");
}
public static void main(String[] args) {
System.out.println("Inside Main Methos");
System.out.println("Main");
}
}
The main method will always be excecuted first, because it is a special static method that will be called from Java itself to start an application.
For more about the main method please read Java main() Method Explained for example.
Constructors will be created on object creation - in your case no object creation happens - so the constructor will never be executed.
You could modify your example to also execute the constructor:
public class ConstructorExp {
public ConstructorExp() {
System.out.println("Ctt");
}
public static void main(String[] args) {
System.out.println("Inside Main Methos");
ConstructorExp example = new ConstructorExp();
System.out.println("Main");
}
}
Be carefully, because the example object is never used the constructor call might be eliminated by some kind of optimization depending on the compiler you are using.
Considering the standard java initialization order rules it is not clear to me why the following code
public class Foo {
static { new Foo(); }
static{ System.out.println("static code"); }
{ System.out.println("non static code"); }
public Foo() { System.out.println("constructor"); }
public static void main(String[] args) {}
}
outputs this:
non static code
constructor
static code
So, the static block will execute as soon as the class loader loaded the class. So, your first static block static { new Foo(); } execute first which further calls the constructor new Foo();. As per the java docs the non-static block will be copied to every constructor by the compiler which means System.out.println("non static code"); will be copied to the constructor public Foo() { System.out.println("constructor"); }. So, it will print non static code first then constructor. After the execution of first static block it will execute the second static block which prints the last static code.
After compilation your code looks similar to below code:
public class Foo {
static { new Foo(); }
static{ System.out.println("static code"); }
public Foo() {
System.out.println("non static code");
System.out.println("constructor");
}
public static void main(String[] args) {}
}
The JLS says that
The static blocks and static variable initializations will be executed in program source code order when a class is initialized.
The instance blocks and instance variable initializations will be executed in program source code order when an instance is initialized. This happens after super instance initialization and before the constructor body is executed.
In your example, the first static creates an instance of Foo. This cause the instance block for Foo to be executed while the first static block is being executed. So, the sequence is:
The class is loaded
Static initialization for Foo is triggered
The first static block is executed which does a new Foo().
The instance block is executed - prints "non static code"
The constructor is executed - prints "constructor"
The first static block finishes.
The second static block is executed - prints "static code".
The main method is called.
Well, to refactor the code, do the following steps:
1) remove non-static initialisation block - the compiler puts it before the code in the actual constructor
public class Foo {
static { new Foo(); }
static{ System.out.println("static code"); }
public Foo() {
System.out.println("non static code");
System.out.println("constructor");
}
public static void main(String[] args) {}
}
2) Join static initialisation blocks - see here:
A class can have any number of static initialization blocks, and they
can appear anywhere in the class body. The runtime system guarantees
that static initialization blocks are called in the order that they
appear in the source code.
public class Foo {
static {
new Foo();
System.out.println("static code");
}
public Foo() {
System.out.println("non static code");
System.out.println("constructor");
}
public static void main(String[] args) {}
}
3) From there, it should be obvious.
I want to print "Hello" even before main() is executed in Java Program. Is there any way for doing this?
What you need is a static keyword. One of the options is to use static function as initializer to static variable.
class Main {
public static int value = printHello();
public static int printHello() {
System.out.println("Hello");
return 0;
}
public static void main(String[] args) {
System.out.println("Main started");
}
}
value is a static variable so initialized before main function execution. This program prints:
Hello
Main started
Moreover, you can even simplify this by calling printHello() even without variable initialization like in the following:
static {
printHello();
}
public class Sample {
static {
System.out.println("Hello first statement executed first ");
}
public static void main(String[] args) {
System.out.println("Main started");
}
}
Use a static block:
static {
System.out.println("hello");
}
public static void main(String[]args) {
System.out.println("After hello");
}
Output:
hello
after hello
public class Test {
static {
System.out.println("Hello");
}
public static void main(String[] args) {
System.out.println("Inside Main");
}
}
Outputs
Hello
Inside Main
Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method. And it will be executed only once.
Apart from using static block, you can also try instrumentation and premain
http://docs.oracle.com/javase/7/docs/api/java/lang/instrument/package-summary.html
import java.io.*;
class ABCD {
public static int k= printit();
public static int printit(){
System.out.println("Hello it will be printed before MAIN");
return 0;
}
public static void main (String[] args) {
System.out.println("Main method is Executed");
}
}
Static variables are initialized in the start of execution of program . So to initialize it will call printit(); function which will be executed and "Hello it will be printed before MAIN" will be printed and in last function will return value '0' and finally after this main block will be executed.
Final Output :
Hello it willl be printed before MAIN
Main method is Executed
Here is another way:
class One{
public One() {
System.out.println("Before main");
}
}
class Two extends One{
public Two() {
super();
}
public static void main(String[] args) {
Object abj = new Two();
System.out.println("in the main");
}
}
Here in run configuration, class Two would be the main class.