-3

I want to call a method when my application starts. I know it's easy to accomplish on android with "oncreate", but strange enough, I can't find anything about how to accomplish this with Java not on Android.

Raedwald
  • 46,613
  • 43
  • 151
  • 237
Mdlc
  • 7,128
  • 12
  • 55
  • 98

5 Answers5

7

Static initializer will be called even before main, like this:

public class Main{
    static{
        System.out.println("I'll be printed before main!");
    }
    public static void main(String[] args){
        System.out.println("This is main!");
    }
}
johnchen902
  • 9,531
  • 1
  • 27
  • 69
2

Have the method be called in the main method as the first thing should accomplish this

public static void main(String[] args){
  yourMethod();
}
Zavior
  • 6,412
  • 2
  • 29
  • 38
  • Thank you, like the main method in java is the oncreate in android? – Mdlc May 26 '13 at 11:52
  • No, these two are not equal. See here for more details - http://stackoverflow.com/questions/4221467/how-can-android-source-code-not-have-a-main-method-and-still-run – Zavior May 26 '13 at 12:12
1

Standalone java applications start execution with the main() method. Inside the main method , the flow of control is linear by default so any method calls in it should execute accordingly. Make sure that the method is in your jar application's main class specified by your manifest file.

Your main() construct :

public static void main(String args[]){
    //method calls here will execute one by one.
    method1();
    method2();
}
EnKrypt
  • 777
  • 8
  • 23
0

It is main method of course......

In desktop java applications, JVM always tries to call static method public static void main(String[]) otherwise an exception is thrown. So, whatever the starter method you want to call call it from main method.

In your main class:

public static void main(String args[]){
    //call what you want to call when your app starts here.............
}
johnchen902
  • 9,531
  • 1
  • 27
  • 69
pinkpanther
  • 4,770
  • 2
  • 38
  • 62
0

Every Java program starts from one main Method. Simply add you method you want to execute first as the first line in your main method.

public class StartClass{
  public static void main(String[] args){
    firstMethod();
  }
}
Simulant
  • 19,190
  • 8
  • 63
  • 98