Category: Core Java

finalize method in Java

What is finalize() method in Java?

 

  • finalize( ) method is a method of Object class which is called just before the destruction of an object by the garbage collector.
  • After finalize( ) method gets executed completely, the object automatically gets destroyed.
  • The purpose of calling finalize method is to perform activities related to clean up, resource deallocation etc.

 

Prototype-

 

Rules for finalize() method-

 

Rule-01:

 

We can override finalize( ) method in our class based on our requirements to define our own clean up activities.

finalize( )
{
    // Clean up activities
    // Resource deallocation activities
}

 

Rule-02:

 

When garbage collector calls the finalize( ) method, it is called on that object which has to be destroyed and the finalize( ) method of corresponding class gets executed.

 

Example-

Consider the following program-

class Test
{
    public static void main(String[ ] args)                   // A "main thread" gets introduced
    {
        String s = new String("Gate Vidyalay");               // A String object gets created
        s = null;                                             // String Object becomes eligible for garbage collection
        System.gc( );                                         // A request is made to JVM for running garbage collector ; A "gc thread" gets introduced
        System.out.println("End of main method");
    }

    public void finalize( )                                   // Test class finalize( ) method
    {
        System.out.println("Finalize method of Test class");
    }
}

Output-

End of main method

 

Analysis-

 

  • In the above program, we first created a new String object and then made it eligible for garbage collection by nullifying its reference variable. We then requested the JVM to run the garbage collector for collecting the String object.
  • According to rule-02, because a String object has become eligible for garbage collection, so we expect the garbage collector to call String class finalize( ) method which is known to have empty implementation and not the finalize( ) method of Test class.
  • The output of the program clearly shows that the finalize( ) method of String class gets executed and not the finalize( ) method of Test class because the print statement of finalize( ) method of Test class does not get executed.

This justifies our rule-02.

 

Rule-03:

 

We can call the finalize( ) method explicitly based on our requirements.

If called explicitly, finalize( ) method will execute as a normal method and object will not be destroyed. The object will be destroyed only when the finalize( ) method is called by the garbage collector itself.

 

Example-

Consider the following program-

class Test
{
   public static void main(String[ ] args)         // A "main thread" gets introduced
   {
      Test t = new Test( );                        // A Test object gets created
      t.finalize( );                               // Finalize( ) method is called explicitly
      t = null;                                    // Test object becomes eligible for garbage collection
      System.gc( );                                // A request is made to JVM for running garbage collector ; A "gc thread" gets introduced
      System.out.println("End of main method");
   }

   public void finalize( )                         // Test class finalize( ) method
   {
      System.out.println("Finalize method called");
   }
}

Output-

There are two possible outputs-

Finalize method called
End of main method
Finalize method called

         OR

Finalize method called 
Finalize method called 
End of main method

 

Analysis-

 

  • In the above program, we first created a new Test object and then called the finalize( ) method explicitly which executed the finalize( ) method of Test class and “Finalize method called” got printed on the console but the object did not get destroy. This justifies our rule-03.
  • Then, we made the Test object eligible for garbage collection by nullifying its reference variable and then introduced a gc thread in the system which requested the JVM to run the garbage collector for collecting the Test object.
  • Then, two threads got introduced in the system- main thread and gc thread.
  • We can’t predict exactly which thread completes its execution first. So, two outputs are possible as shown.

 

Rule-04:

 

  • If finalize( ) method is called explicitly by the programmer and while executing that finalize( ) method if any kind of exception occurs which is uncaught i.e. no catch block is present to catch the exception, then the program will terminate abnormally by raising that exception.
  • If finalize( ) method is called by the garbage collector and while executing that finalize( ) method if any kind of exception occurs which is uncaught i.e. no catch block is present to catch the exception, then JVM will ignore that exception and rest of the program will be executed normally.

 

Example-

Consider the following program-

class Test
{
   public static void main(String[ ] args)
   {
      Test t = new Test( );                              // A Test object gets created
      t.finalize( );                                     // Statement-01 (say)
      t = null;                                          // Test object becomes eligible for garbage collection
      System.gc( );                                      // A request is made to JVM for running garbage collector
      System.out.println("End of main method");
   }

   public void finalize( )                               // Test class finalize( ) method
   {
      System.out.println("Finalize method called");
      System.out.println(10/0);                          // This statement gives rise to Arithmetic Exception
   }
}

 

Case-01: When statement-01 is not commented-

 

  • When statement-01 is not commented, t.finalize( ); statement remains active which calls the finalize( ) method explicitly.
  • Finalize( ) method tries to evaluate the expression 10/0 which gives rise to an arithmetic exception and program terminates by raising that exception as shown by the output.

 

Output-

finalize method called
"Exception in thread "main" java.lang.ArithmeticException: / by zero"

 

Case-02: When statement-01 is commented-

 

  • When statement-01 is commented, t.finalize( ); statement goes dead and thus no explicit call is made to the finalize( ) method.
  • Now, the arithmetic exception raised by the implicit call to finalize( ) method is ignored by the JVM and the rest of the program executes normally as shown by the output.
  • Two outputs are possible because two threads exist in the system – main thread and gc thread and these threads can complete their execution in any order.

 

Output-

finalize method called
End of main method

        OR

End of main method
finalize method called

 

Rule-05:

 

Garbage collector calls the finalize( ) method only once on any object even though that object becomes eligible for garbage collection multiple times.

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.

Constructors in Java

Elements of a class in Java-

Java is a class based language where the entire code is written inside a class.

Any class written in Java consists of the following 5 elements-

  1. Variables
  2. Methods
  3. Constructors
  4. Instance blocks
  5. Static blocks

 

In this post, we will discuss about the constructors of Java in detail.

 

Constructors in Java-

 

Constructor is an element of a class which serves the following two purposes-

  1. Constructors can be used to initialize the instance variables during object creation. (Main purpose)
  2. Constructors can also be used to write the logic of the program which has to be executed automatically on the creation of the objects.

 

When do constructors execute?

 

Constructors are automatically executed on the creation of the objects. Whenever any new object gets created, the constructor corresponding to it is automatically executed.

 

Rules for writing the constructors in Java-

 

There are some rules which we must keep in our minds while working with the constructors. They are as follows-

 

Rule-01:

 

The constructor name and the class name must always be same. So, the while naming the constructor, always make sure that it is same as class name.

 

Rule-02:

 

Constructors can never have any return type (not even void) and that’s why constructors can not return any value explicitly.

However, constructors return instance of the current class implicitly.

 

Note-

If we mention some return type of the constructor by mistake, then we will not get any compile time error or run time error. Compiler considers it as a normal instance method.

 

Example-

 

So, it is perfectly legal to have a method in class having exactly same name as class name but it is not recommended.

 

Rule-03:

 

Only the following listed modifiers can be used for constructors-

  • public
  • private
  • protected
  • default

If we try to use any other modifier, then compiler generates a compile time error saying-

“modifier xxx is not allowed here”

 

Rule-04:

 

The very first line inside every constructor (whether default or parameterized) has to be either this( ) or super( ) with or without arguments where this( ) calls the current class constructor and super( ) calls the super class constructor.

If we don’t mention any of these calling methods, compiler always calls the super class constructor method automatically by writing super( ) as a first statement inside every constructor.

 

Types of Constructors in Java-

 

Constructors are mainly classified into 2 types-

  1. Default constructor
  2. Parameterized constructors

 

 

1. Default Constructor-

 

  • Default constructor is a 0 argument constructor which contains a no argument call to super class constructor.
  • To assign default values to the newly created objects is the main responsibility of default constructor.
  • Compiler writes a default constructor in the code only if the programmer does not write any constructor in the class.
  • The access modifier of default constructor is always same as class modifier. But this rule is applicable only for “public” and “default” modifiers.

 

Syntax-

 

When will compiler add a default constructor?

 

Compiler adds a default constructor to the code only when the programmer writes no constructor in his code from his side.

If programmer writes any constructor in his code, then the compiler does not add any constructor from its side.

Then, it is the responsibility of the programmer to write the default constructor in his code if he requires it.

In that case, it’s no more called a default constructor rather it is called a 0 argument constructor as it is written by the programmer and not added by default by the compiler.

So, It is important to note that-

 

Every default constructor is a 0 argument constructor but every 0 argument constructor is not a default constructor.

 

2. Parameterized Constructors-

 

  • Parameterized constructors are the constructors having specific number of arguments passed to them.
  • The purpose of parameterized constructors is to assign user-wanted specific values to the instance variables of different objects.

 

Difference between default constructor and parameterized constructors-

 

Default ConstructorParameterized Constructors
Default constructor is always a 0 argument constructor.Parameterized constructor have specific number of arguments passed to them.
Default constructor is written by the compiler.Parameterized constructor is written explicitly by the programmer.
Default constructor initializes the instance variables of every object with the same values which are the predefined default values of the variables.Parameterized constructor initializes the instance variables of every object with the different values which are the values passed to the constructor by the programmer while creating the objects.

 

Programmer Code and Compiler Generated Code-

 

It is interesting to know how the code written by the programmer is modified by the compiler after the compilation.

Based on the rules and concepts mentioned above, compiler modifies the programmer’s code.

This has been illustrated with the help of following cases-

 

Case-01:

 

Here, the programmer does not write any constructor inside the class from his side. So, compiler adds the default constructor from its side as shown.

 

Case-02:

 

This case is similar to case-01 except that here the class has been declared with modifier “public” by the programmer. So, compiler adds the modifier “public” to the default constructor that it adds from its side.

(Refer rule-03 above)

 

Case-03:

 

Here, the programmer writes a 0 argument constructor explicitly. So, compiler does not add the default constructor from its side.

However, because inside every constructor, first statement has to be either this( ) or super( ) and because programmer does not write anything out of these from his side so compiler adds the super( ) statement from its side which is a call to the super class constructor.

(Refer rule-04 above)

 

Program illustrating the use of constructors in Java-

class Student
{  
    int roll_no;  
    String stu_name;  
      
    Student(int i , String n)               // Parameterized constructor
    {  
       roll_no = i;                         // Instance Variable
       stu_name = n;                        // Instance Variable
    }  

    void display()
    {
       System.out.println(roll_no+" "+stu_name);
    }  
   
    public static void main(String args[])
    {  
       Student s1 = new Student(1,"Akshay");  
       Student s2 = new Student(2,"Rajat");  
       s1.display();  
       s2.display();  
    }  
}

Output-

1 Akshay
2 Rajat

 

Analysis-

 

In the above program, programmer defines one parameterized constructor with 2 parameters. So, now compiler adds no default constructor to the code and neither the programmer has written any 0 argument constructor.

So, in the above code if we write the following statement in the main method-

Student s3 = new Student( );

Then, a compile time error would be raised by the compiler because there is no 0 argument constructor Student( ) in the code.

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.

Instance blocks in Java

Elements of a class in Java-

Java is a class based language where the entire code is written inside a class.

Any class written in Java consists of the following 5 elements-

  1. Variables
  2. Methods
  3. Constructors
  4. Instance blocks
  5. Static blocks

 

In this post, we will discuss about the instance blocks of Java in detail.

 

Instance blocks in Java-

 

Instance block is an element of a class which serves the same two purposes as served by the constructors.

These two purposes are-

  1. Just like constructors, instance blocks can be used to initialize the instance variables during object creation.
  2. Just like constructors, instance blocks can also be used to write the logic of the program which has to be executed automatically for all objects during their creation. (Main Purpose)

 

When do instance blocks execute?

 

If any instance block exists in the program, then for every object during its creation, first of all that instance block will be executed and then its specific constructor will be executed.

 

Need of instance blocks-

 

Because instance blocks are executed whenever the object of any kind is created, so if we want to write a logic which we want to execute on the creation of all kinds of objects, then using instance blocks is a good idea to avoid writing the same logic inside every constructor.

 

Note-

 

Although instance blocks can be used for the initialization of objects but we generally don’t use them for the initialization of objects because they can not accept the parameters.

However, if we still use instance blocks for the purpose of initialization, then all the objects will have to be initialized with the same values which is practically useless.

That is why, we mainly use constructors for the initialization of objects.

 

Syntax-

{
   // This is called as instance block
}

 

Program illustrating the use of instance blocks-

class Test
{
   Test( )                                            // This constructor will get executed for 1st kind of object 
   {
      System.out.println("0 argument constructor");
   }

   Test(int a)                                        // This constructor will get executed for 2nd kind of object
   {
      System.out.println("1 argument constructor");
   }

   Test(int a , int b)                                // This constructor will get executed for 3rd kind of object
   {
      System.out.println("2 arguments constructor");
   }

   {                                                  // Creation of an instance block
      System.out.println("Instance block");          
   }

   public static void main(String[ ] args)
   {
      new Test( );                                      // Object of 1st kind
      new Test(10);                                     // Object of 2nd kind
      new Test(10,20);                                  // Object of 3rd kind
   }
}

OUTPUT-

Instance block
0 argument constructor
Instance block
1 argument constructor
Instance block
2 arguments constructor

 

It can be clearly observed from the above program that whenever any object gets created, first of all instance block is executed and then its specific constructor is executed.

 

Multiple instance blocks-

 

  • It is possible to have multiple instance blocks inside a single class.
  • The execution of these multiple instance blocks take place from top to bottom.

 

Program illustrating the use of multiple instance blocks-

class Test
{
   Test( )
   {
      System.out.println("0 argument constructor");
   }

   Test(int a)
   {
      System.out.println("1 argument constructor");
   }

   {
      System.out.println("Instance block-01");
   }

   {
      System.out.println("Instance block-02");
   }

   public static void main(String[ ] args)
   {
      new Test( );
      new Test(10);
   }
}

OUTPUT-

Instance block-01
Instance block-02
0 argument constructor
Instance block-01
Instance block-02
1 argument constructor

 

Important Points to note-

 

  • Instance block will be executed only once for each object during its creation.
  • So, the number of times an instance block is executed signifies the number of objects created in the program.
  • The execution of instance block depends only on the object creation and not on the execution of a constructor.

 

Comparison between instance block and constructor-

 

Instance blockConstructor
Instance block logic are common for all the objects.Constructor logic are specific to the objects.
Instance block will be executed only once for each object during its creation.We can execute the constructors multiple times for a single object by placing the call to them in other constructors.
Instance block will be executed only as many times as there are number of objects created in the program.It is not necessary for the constructors as they may be called explicitly.
Instance blocks are mainly used for writing the common logic which we want to execute for all the objects.Constructors are mainly used for the initializing of objects.

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.

Variables in Java with examples

Elements of a class in Java-

Java is a class based language where the entire code is written inside a class.

Any class written in Java consists of the following 5 elements-

  1. Variables
  2. Methods
  3. Constructors
  4. Instance blocks
  5. Static blocks

 

In this post, we will discuss about the variables of Java in detail.

Variables in Java-

 

  • Variable is an element of a class that is used for storing the values.
  • It is basically a name that is assigned to a memory location where a particular value is stored.

 

Concept of Areas in Java-

In any java program, the area can be classified into 2 types-

  1. Instance Area
  2. Static Area

 

1. Instance area-

Instance area is the area inside instance methods or instance blocks or constructors.

Example-

void m1( )           // "Instance Method" 
{ 
   // This area is called "Instance Area" 
}

 

2. Static area-

Static area is the area inside static methods or static blocks.

Example-

static void m1( )   // Static Method
{
   // This area is called "Static Area"
}

 

Types of Variables in Java-

 

Variables in Java can be broadly classified into following three types-

 

 

1. Local Variables-

 

  • Variables declared inside the methods or constructors or blocks are called as local variables.
  • The scope of local variables is within that particular method or constructor or block in which they have been declared.
  • Local variables are allocated memory when the method or constructor or block in which they are declared is invoked and memory is released after that particular method or constructor or block is executed.
  • Stack memory is allocated for storing local variables.
  • JVM takes no responsibility for assigning default value to the local variables. It is the responsibility of the programmer to initialize the local variables explicitly before using them otherwise syntax error is raised. It is important to note that no error will be raised as long as the uninitialized local variables are not used.

 

How to access local variables?

 

  • They can be called directly with their names.

 

2. Instance Variables-

 

  • Variables declared outside the methods or constructors or blocks but inside the class are called as instance variables.
  • The scope of instance variables is inside the class and therefore all methods, constructors and blocks can access them.
  • Instance variables are allocated memory during object creation and memory is released during object destruction. If no object is created, then no memory is allocated.
  • For each object, a separate copy of instance variable is created.
  • Heap memory is allocated for storing instance variables.
  • It is the responsibility of the JVM to assign default value to the instance variables as per the type of variable.

 

How to access instance variables?

 

  • Instance variables can be called directly inside the instance area.
  • Instance variables can not be called directly inside the static area and necessarily requires an object reference for calling them.

 

3. Static Variables-

 

  • Variables declared with “static” modifier outside the methods or constructors or blocks but inside the class are called as static methods.
  • The scope of static variables is inside the class and therefore all methods, constructors and blocks can access them.
  • Static variables are allocated memory during loading of .class file by the JVM and memory is released during unloading of .class file.
  • A single copy gets created for the static variables and this single copy is shared by all the objects belonging to that class.
  • Non-heap memory is allocated for storing static variables.
  • It is the responsibility of the JVM to assign default value to the static variables as per the type of variable.

 

Since, static variables are associated with the entire class, they are popularly called as class variables.

 

How to access static variables?

 

  • It is allowed to call static variables by using class name and dot operator. (Recommended)
  • It is allowed to call static variables directly within the same package.
  • It is allowed to call static variables by using object reference and dot operator.

 

NOTE-

 

  • Although static variables can be accessed using object reference and dot operator but it is not recommended because it does not make it clear that we are talking about the class variables.

Always make a habit of calling the static variables using class name and dot operator.

 

Default values of the variables-

 

JVM assigns default value to the instance and static variables automatically when the programmer does not initialize the variables with some value.

However, JVM takes no responsibility for initializing the local variables with default values.

The default values are assigned as per the following table-

 

Data Type of the variableDefault Value
byte0
short0
int0
long0
float0.0
double0.0
char<single space>
BooleanFalse
classNull

 

Real life example illustrating where to use what kind of variable-

 

  • We must declare the variable as instance variable if the value of that variable will be different for different objects.
  • We must declare the variable as static variable if the value of that variable will be same for different objects so as to save the memory.

 

Example-01:

 

  • If we are creating a class ‘Student‘, then in that class all the Student objects will obviously have different names but the school name for all the students will be definitely same.
  • So, we can declare the variable ‘student_name’ as instance variable and variable ‘school_name‘ as static variable.
  • If we would have declared variable ‘school_name‘ as instance variable, then one copy of it would have been created for each Student object and the memory would be wasted unnecessarily.

 

class Student
{
   static String school_name;
   String student_name;
}

 

Example-02:

 

  • If we are creating a class ‘Employee‘, then in that class all the Employee objects will obviously have different names but the company name for all the employees will be definitely same.
  • So, we can declare the variable ’employee_name’ as instance variable and variable ‘company_name‘ as static variable.
  • If we would have declared variable ‘company_name‘ as instance variable, then one copy of it would have been created for each Employee object and the memory would be wasted unnecessarily.

 

class Employee
{
   static String company_name;
   String employee_name;
}

 

Comparison table of different types of variables in Java-

 

 Local VariablesInstance VariablesStatic Variables
Declaration placeInside the methods or constructors or blocks.Outside the methods or constructors or blocks but inside the class.Outside the methods or constructors or blocks but inside the class.
ScopeWithin that particular method or constructor or block in which they have been declared.Inside the class.Inside the class.
Time of memory allocationMemory is allocated when the method or constructor or block in which they are declared is invoked.Memory is allocated during object creation.Memory is allocated during loading of .class file by the JVM.
Time of memory deallocationMemory is released after that particular method or constructor or block is executed.Memory is released during object destruction.Memory is released during unloading of .class file.
Storing placeStack memoryHeap memoryNon-heap memory
Assigning of default valuesResponsibility of programmer to initialize with values.

JVM takes no responsibility for initializing with default values.

Responsibility of JVM to initialize with default valuesResponsibility of JVM to initialize with default values
Accessing methodCan be called directly with name.Can be called directly inside the instance area but inside the static area requires an object reference.Recommended way is by using class name and dot operator.

 

Program illustrating how to use different kinds of variables-

class Test
{
   int a = 10;                              // "Instance Variable"
   static int b = 20;                       // "Static Variable"

   void print( )                            // "Instance method"
   {
      System.out.println(a);                // "Accessing instance variable directly in instance area"
   }

   public static void main(String[ ] args)
   {
      Test t = new Test( );                 // "Object Creation"
      System.out.println(t.a);              // "Accessing instance variable using object reference in static area"
      System.out.println(b);                // "Accessing static variable directly within same package"
      System.out.println(t.b);              // "Accessing static variable using object reference"
      System.out.println(Test.b);           // "Accessing static variable using class name and dot operator"
      t.print();                            // "Accessing instance method using object reference in static area"
   }
}

OUTPUT-

10
20
20
20
10

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.

main method in Java

What is main method in Java?

 

  • main method is a starting point in the program from where the code execution is started by the JVM.
  • If JVM does not find the main method inside the code according to the specifications configured inside it, it raises an error.

 

Syntax of main method in Java-

 

JVM always looks for the main method having the following signatures-

public static void main (String[ ] args)

 

  • main method is public so that it can be accessed from anywhere and is available to other programs like JVM.
  • main method is static so that it can be accessed even without objects and this allows JVM to access this method as there exists no object in the starting.
  • main method is void because it does not return anything to the JVM.
  • main method has been named main because this name is configured inside the JVM.
  • main method contains the arguments list String[ ] args which are “command line arguments” to store the values which are passed to the main method.

 

Note-

 

The above syntax is very strict and if we try to modify it, run time error is generated saying-

"Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)"

However, there are some acceptable changes which can be made.

 

Acceptable changes in the syntax of main method in Java-

 

Change-01:

 

Because in Java, the order in which the modifiers appear is not important, so instead of “public static“, we can comfortably write “static public“.

 

Change-02:

 

We can declare String[ ] args in any valid form such as-

  • String [ ]args
  • String args[ ]

 

Change-03:

 

Instead of args, we can use any valid java identifier.

 

Change-04:

 

In place of of String[ ], var-arg String parameter can be taken as String…

So, String[ ] args is same as String… args

 

Change-05:

 

We can also declare the main method with the following modifiers-

  • final
  • synchronized
  • strictfp

 

Rules to remember while using main method in Java-

 

Rule-01:

 

The concept of method overloading can be used for the main method but JVM will always execute only that main method implicitly which satisfies the specifications configured inside it.

It is the responsibility of the programmer to call other modified versions of the main method explicitly.

Example-

class Test
{
   public static void main(String[ ]  args)
   {
      System.out.println("main method called implicitly by the JVM");
   }

   public static void main(int[ ]  args)
   {
      System.out.println("main method called explicitly by the programmer");
   }
}

Output-

main method called implicitly by the JVM

This output clearly justifies our rule-01.

 

Rule-02:

 

We can use the concept of inheritance for all the static methods including the main method.

Thus, if there exists a child class not containing the main method, then while executing the child class, main method of the parent class will be executed.

 

Rule-03:

 

It appears as if the concept of overriding is applicable for static methods but it is not overriding, it is actually method hiding.

 

Rule-04:

 

It is possible to configure our own method in JVM instead of main method but for that customization of JVM is required i.e. some changes will have to be made inside the JVM.

 

Interview Questions based on main method in Java-

 

Question-01:

Is it possible to compile the java code successfully without main method?

Answer-

Yes, the java code compiles successfully even without the main method in it.

Reason-

Compiler is just responsible to check whether the code written follows the syntax rules or not. So, if the code is written following the correct syntax rules, it will not raise any error.

Example-

public class Test
{
   // statements
}

Clearly, the above class does not contain any main method.

Now, if we try to compile the above code, it compiles successfully without raising any error.

 

Question-02:

Is it possible to execute the java code successfully without main method?

Answer-

Although the java code compiles successfully even without the main method but it does not execute successfully without main method.

Reason-

At run time, JVM always looks for the main method having particular syntax which is configured inside it to start the execution of the program and if it does not find that main method, it raises an error.

 

NOTE-

Till JDK version 1.6, it was allowed to execute a class not containing a main method but from version 1.7 on wards, it has been made compulsory to have a main method inside the class for executing it.

 

Example-

public class Test
{
   // statements
}

Clearly, the above class does not contain any main method.

Now, if we try to execute the above code, it does not execute successfully and raises the following error-

Output-

"Error: Main method not found in class Test, please define the main method as:
   public static void main(String[] args)"

 

Question-03:

Is it possible to print some statements successfully on the console without main method?

Answer-

  • It was possible till JDK version 1.6 only by writing those statements inside the static block because till version 1.6, the static blocks were executed irrespective of the fact whether we have main method inside our program or not.
  • But from JDK version 1.7 on wards, the static blocks are executed only if we have main method in our program.
  • So, now it is not possible to print any statement without having main method in our program.

 

Question-04:

Which of the following main method declarations are valid in java?

  1. public static void main (String… args)
  2. static final synchronized strictfp public void main (String[ ] args)
  3. public static void main (String args)
  4. final synchronized strictfp public void main (String[ ] args)
  5. public static void Main (String[ ] args)
  6. public static int main (String[ ]  args)
  7. final synchronized strictfp public static void main (String[ ] args)
  8. public void main (String[ ]  args)

Answer-

  1. Valid
  2. Valid
  3. Invalid (We need a String array to pass as argument and not String type variable)
  4. Invalid (static keyword is absent)
  5. Invalid (‘M’ must be small in spelling of main)
  6. Invalid (Return type of main method must be void)
  7. Valid
  8. Invalid (static keyword is absent)

Note-

  • In none of the above declarations, we will get compile time error. All declarations will compile successfully.
  • Except in (1), (2) and (7), we will get run time error.

 

Get more notes and other study material of Core Java.

Watch video lectures by visiting our YouTube channel LearnVidFun.