In java constructor and main which one will execute first? - java

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.

Related

Instance and Static control-flow with inheritance and overriding/method-hiding

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();

Unable to call function in java

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.

Error of simple calculating process [duplicate]

I've learnt that the only public class in a Java file must also have the main method. However, below you can see the main method inside an inner class instead?
What is the rule with regard to the main method definition in a source file?
public class TestBed {
public TestBed() {
System.out.println("Test bed c'tor");
}
#SuppressWarnings("unused")
private static class Tester {
public static void main(String[] args) {
TestBed tb = new TestBed();
tb.f();
}
}
void f() {
System.out.println("TestBed::f()");
}
}
If you want to start a class with java (the Java launcher: java test.MyClass) then this class must have a main method with the well known signature.
You can have a main method with the same signature anywhere you want. But don't expect that the launcher will find it.
P.S. The name of the language is Java, not JAVA.
There is a minor detail:
You may do this:
package test;
public class Test {
/**
* #param args the command line arguments
*/
static public class A {
public static void main(String[] args) {
System.err.println("hi");
}
}
}
java test.Test$A
but this is non standard ...
Any class that can have a static method can have a public static void main(String[] args).
This includes:
top-level classes (whether public or not), e.g.
public class Foo {
public static void main(String[] args) {
System.out.println("Hello");
}
}
and inner static classes (whether public or not) (like your example).
It does not include:
anonymous classes
inner non-static classes
So both of these are illegal:
public class Foo {
private Object bar = new Object() {
public static void main(String[] args) {
System.out.println("Hello");
}
};
}
public class Foo {
private class Bar {
public static void main(String[] args) {
System.out.println("Hello");
}
};
}
Every Java application must have a main method. It’s the starting point for the execution of the code in the application. Its method signature is:
public static void main(String[] args)
A static inner class is a class that is defined inside of a different class's definition and marked as being static.
For example, if the outer class is named TestBed, then an inner class of TestBed, which is named Tester, would be compiled into TestBed$Tester.class. The separation of .class files means that you can keep the supplemental, nested code tightly coupled to the primary, outer class.
They are in the same source file, and the inner class is actually inside the outer class. All that and you don't have to pay any sort of deployment or run time cost.
By using static inner classes, you can add additional support functionality to your systems for capabilities such as testing, while incurring no penalties in normal, production deployment.
To execute the main() method of that TestBed.Tester class,
% java TestBed$Tester
This is interesting as the code will compile and run in Eclipse, but will just compile from using commmand line. When you run from eclipse it will find the static main method from within the inner class and run it.
But when running java TestBed from the command line you will get error - Exception in thread "main" java.lang.NoSuchMethodError: main which is a valid error as you have not defined your main method in main class.
Why would you want to define your main method in an inner class? Your main method should be defined in public class, this is not a rule but common practice.
In below code I've moved the main method into outer class which works both in Eclipse & command line :
public class TestBed {
public TestBed() {
System.out.println("Test bed c'tor");
}
#SuppressWarnings("unused")
private static class Tester {
}
public static void main(String[] args) {
TestBed tb = new TestBed();
tb.f();
}
void f() {
System.out.println("TestBed::f()");
}
}

Invoke java class static initialization via VM option

Is there any way to force static initialization of some class B before entering the main() method of class A, without changing class A, using only VM options?
I'm not aware of any way to do it without code. In code it's easy of course.
public class C {
static {
// Fetch and throw away an instance of B to make sure it is loaded
B.getInstance();
}
static void main(String[] args) {
// Do stuff, B is initialized
A.main(args);
}
}
In fact you could just do
public class C {
static void main(String[] args) {
B.getInstance();
A.main(args);
}
}
Your request doesn't make a lot of sense though. Ask a question about the problem you are trying to solve by doing this and you will hopefully get a much more useful answer.
you could create a class that initializes other classes and then calls the real main method, e.g:
public static void main(String[] args) throws Exception {
Class<?> mainClass = Class.forName(System.getProperty("mainClass"));
for (String className : System.getProperty("initClasses").split(";")) {
Class.forName(className);
}
Method main = mainClass.getMethod("main", String[].class);
main.invoke(null, new Object[] { args });
}
Then you would start the application with that class as the main class and specify the real main class and the classes to be initialized via properties.

java: calling a method

I am just learning how to create a subroutine/method in java, and I am having the problem that I can't call my method with the compiler thinking that my call (playGame();) is an attempted definition of a method of itself. So i get the error "invalid method declaration; return type required". As I am a beginner I am sure that it is a stupid mistake, but I have tried rewriting many times to fix it and I cannot figure it out.
public class GUI {
public static void main(String[] args){
}
public static void playGame() {
}
playGame();
}
You can only call a method from within another method, not from the body of a class. Move the line
playGame();
inside the main method:
public static void main(String[] args){
playgame();
}
Your method call should be inside another method , in this case main (or) You can call from playGame() also, but that would be recursion and may end up in infinite loop.
public static void main(String[] args){
playGame();
}
See Essentials of the Java Programming Language to learn more about how to write java program.
You can not call methods from class body directly the way you are doing. You need to call method playGame() from main method. Like :
public class GUI {
public static void main(String[] args){
playGame();
}
public static void playGame() {
// some statements
}
}
As you are new Start Reading Java Tutorial.

Categories