简体   繁体   中英

Can we print a java message on console without using main method, static variable and static method?

public class Test {

/**
 * @param args
 */

// 1st way
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Test....!!!!!");
}

// 2nd way
static{
System.out.println("Test....!!!!!");
System.exit(1);
}

// 3rd way
private static int i = m1();
public static int m1(){
    System.out.println("Test...!!!!");
    System.exit(0);
    return 0;
}

Other than this, can we print message any other way.

Of course you can, from a class constructor, method or instance block for instance.

However if you're talking about launching a simple program with the command line (eg java -jar myProgram ), you'll still need to instantiate the class where the instance code printing to console resides, in a main method.

For instance, with given class Foo :

public class Foo {
    // Initializer block Starts
    { 
        System.out.println("Foo instance statement");
    }
    // Initializer block Ends

    public Foo() {
        System.out.println("Foo ctor");
    }
    public void doSomething() {
        System.out.println("something done from this Foo");
    }
}

... now from the main method of your Main class:

public static void main(String[] args) {
    new Foo().doSomething();
}

Output:

Foo instance statement
Foo ctor
something done from this Foo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM