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

console, java, println

Solution

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 (e.g. `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

Problem

``` 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.

Original source