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

1

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

Horsey answered 11/8, 2013 at 11:32 Comment(5)
I think from Java 7 onwards your second approach will not print (and we call it is static block, not method)Biggers
@Nambari what makes you say that?!Cambodia
The question is not clear. Do you mean without ever using main()? #2 and #3 do not work unless some main() method was ever called that loaded a class containing such declarations.Mcspadden
@BoristheSpider: There was interesting question regarding System.out in static block few days ago (assuming no main method, only static block inside your program and try to run it. Less than Java7, it runs).Biggers
Dear Sean Owen, What i was trying to ask is, Is there any way to print a simple message on console. Without using static method, static variable, static block and main().Horsey
D
7

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
Deltadeltaic answered 11/8, 2013 at 11:36 Comment(5)
Can you please throw some more light on How System.out.println("Foo instance statement"); is working.Will it be executed every time we create objects of this class?Mahaffey
@Mahaffey exacly. Every new instance of Foo, the instance statement is executed.Deltadeltaic
But how it is working,it is neither part of a constructor or anything else,it is just a simple block.Mahaffey
@Mahaffey the documentation tells it better than I can. The explanation is at the bottom of the page, with the instance member initialization section.Deltadeltaic
@Deltadeltaic does new Foo() use Foo.class.newInstance()? or some other reflection based method?Eu

© 2022 - 2024 — McMap. All rights reserved.