top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

I want to print "Hello" even before main() is executed. How can we achieve that?

+1 vote
493 views
I want to print "Hello" even before main() is executed. How can we achieve that?
posted Jan 4, 2017 by Dhaval Vaghela

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

+1 vote

One of the options is to use static function as initializer to static variable. Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main() method.

What you need is a static keyword. One of the options is to use static function as initializer to static variable.

class Main {
  public static int value = printHello();
  public static int printHello() { 
    System.out.println("Hello"); 
    return 0;
  }
  public static void main(String[] args) {
    System.out.println("Main started");
  }
}

value is a static variable so initialized before main function execution. This program prints:

Hello
Main started

Moreover, you can even simplify this by calling printHello() even without variable initialization like in the following:

static {
  printHello();
}
answer Jan 4, 2017 by Karthick.c
0 votes

yes u can do this by static block. for better understood i give a simple example......

public class Test2 {
    static{
        System.out.println("hello");
        //System.exit(0);
    }   
    public static void main(String args[])
    {
        System.out.println("I am a bad codder");
    }
}
answer Jun 26, 2017 by Ajay Kumar
Similar Questions
+3 votes

Rohit's teacher has asked him to write a function that takes as input parameters the first parameter will be an integer number representing. The number whose digitSum needs to be found the second parameter will be a char representing the
option which would either be 'e' or 'o' representing 'even' or 'odd' respectively.

Function signature public int digitSum(int n, char ch);

digitSum(9625, 'o')
Example 1: if given number is 9625 and the option is 'o' we must add only the odd digit i.e. 9+5=14
digitSum(2134, 'e')
Example 2: if given number is 2134 and the option  is 'e' we must add only the odd digit i.e. 2+4=6
...