Automation QA Testing Course Content

The water jug puzzle

 

'image.png' failed to upload. TransportError: There was an error during the transport or processing of this request. Error code = 103, Path = /_/BloggerUi/data/batchexecute
water pouring puzzle’.

You have an 8 litre jug full of water and two smaller jugs, one that contains 5 litres and the other 3 litres. None of the jugs have markings on them, nor do you have any additional measuring device.You have to divide the 8 litres of water equally between your two best friends, so that each gets 4 litres of water. How can you do this?

Wait! Try and solve this puzzle before reading on.

The water jug puzzle – solution

  • First, water is poured from the 8 litre jug into the 5 litre jug, leaving 3 litres of water in the original 8 litre jug.
  • Next, water is poured from the 5 litre jug into the 3 litre jug, so we now have 3 litres of water in the 8 litre jug, 2 litres of water in the 5 litre jug and 3 litres of water in the 3 litre jug.
  • The 3 litre jug is emptied into the 8 litre jug, so the 8 litre jug now contains 6 litres of water.
  • The 2 litres of water in the 5 litre jug are now poured into the empty 3 litre jug.
  • Water is poured from the 8 litre jug (which at this stage contains 6 litres) into the empty 5 litre jug. We now have 5 litres of water in the 5 litre jug, 2 litres of water in the 3 litre jug and 1 litre of water in the 8 litre jug.
  • Water is poured from the 5 litre jug to fill the 3 litre jug which already contains at this stage 2 litres of water.
  • We are left with 4 litres of water in the 5 litre jug which is given to one friend, and 3 litres of water in the 3 litre jug that is poured back into the 8 litre jug that already contains 1 litre of water. This gives 4 litres of water which are given to the second friend.
The whole scenario can be summarised using numbers in brackets to denote the litres of water at each stage in each of the 8 litre, 5 litre and 3 litre jugs, respectively:



Java Interview questions

 ClassNotFoundException is an exception that occurs when you try to load a class at run time using Class.forName() or loadClass() methods and mentioned classes are not found in the classpath.

NoClassDefFoundError is an error that occurs when a particular class is present at compile time, but was missing at run time.

For example, the below program will throw ClassNotFoundException if the mentioned class “oracle.jdbc.driver.OracleDriver” is not found in the classpath.

If you run the above program without updating the classpath with required JAR files, you will get an exception akin to:


NoClassDefFoundError

NoClassDefFoundError is an error that is thrown when the Java Runtime System tries to load the definition of a class, and that class definition is no longer available. The required class definition was present at compile time, but it was missing at runtime. For example, compile the program below.

When you compile the above program, two .class files will be generated. One is A.class and another one is B.class. If you remove the A.class file and run the B.class file, Java Runtime System will throw NoClassDefFoundError like below:


Recap

ClassNotFoundException

NoClassDefFoundError

It is an exception. It is of type java.lang.Exception.

It is an error. It is of type java.lang.Error.

It occurs when an application tries to load a class at run time which is not updated in the classpath.

It occurs when java runtime system doesn’t find a class definition, which is present at compile time, but missing at run time.

It is thrown by the application itself. It is thrown by the methods like Class.forName(), loadClass() and findSystemClass().

It is thrown by the Java Runtime System.

It occurs when classpath is not updated with required JAR files.

It occurs when required class definition is missing at runtime.

JAVA TRICKY INTERVIEW QUESTIONS?

1)Can we define an abstract class with no abstract methods in Java?
Ans)yes, you can declare abstract class without defining an abstract method in it. Once you declare a class abstract it indicates that the class is incomplete and, you cannot instantiate it.

2)Can we define a parameterized constructor in an abstract class in Java?

Ans)Yes, we can define a parameterized constructor in an abstract class.

Conditions for defining a parameterized constructor in an abstract class

  • We need to make sure that the class which is extending an abstract class have a constructor and it can call the superclass parameterized constructor.
  • We can call the superclass parameterized constructor in a subclass by using super() call.
  • If we are not placing super() call in the subclass constructor, a compile-time error will occur.
3)Can we create an object of an abstract class in Java?
Ans)No, we can't create an object of an abstract class. But we can create a reference variable of an abstract class. The reference variable is used to refer to the objects of derived classes (subclasses of abstract class).
If you try to instantiate an abstract class a compile time error is generated saying “class_name is abstract; cannot be instantiated”.

4)Can we declare an abstract method final or static in java?
Ans)A method which does not have body is known as abstract method. It contains only method signature with a semi colon and, an abstract keyword before it.
public abstract myMethod();

To use an abstract method, you need to inherit it by extending its class and provide implementation to it.

Declaring abstract method static

If you declare a method in a class abstract to use it, you must override this method in the subclass. But, overriding is not possible with static methods. Therefore, an abstract method cannot be static.

If you still, try to declare an abstract method static a compile time error is generated saying “illegal combination of modifiers − abstract and static”.

Declaring abstract method final

Similarly, you cannot override final methods in Java.
But, in-case of abstract, you must override an abstract method to use it.
Therefore, you cannot use abstract and final together before a method.

If, you still try to declare an abstract method final a compile time error is generated saying “illegal combination of modifiers: abstract and final”.

5)Can we declare an interface with in another interface in java?

Ans)Yes we can define

Nested interfaces

Java allows declaring interfaces within another interface, these are known as nested interfaces.

While implementing you need to refer to the nested interface as outerInterface.nestedInterface.


interface Cars4U_Services {
   interface CarRentalServices {
      public abstract void lendCar();
      public abstract void collectCar();
   }
   interface CarSales{
      public abstract void buyOldCars();
      public abstract void sellOldCars();
   }
}
public class Cars4U implements Cars4U_Services.CarRentalServices,
Cars4U_Services.CarSales {
   public void buyOldCars() {
      System.out.println("We will buy old cars");
   }
   public void sellOldCars() {
      System.out.println("We will sell old cars");
   }
   public void lendCar() {
      System.out.println("We will lend cars for rent");
   }
   public void collectCar() {
      System.out.println("Collect issued cars");
   }
   public static void main(String args[]){
      Cars4U obj = new Cars4U();
      obj.buyOldCars();
      obj.sellOldCars();
      obj.lendCar();
   }
}

Output

We will buy old cars
We will sell old cars
We will lend cars for rent

6)Can we declare constructor as final in java?
Ans)No, 

declaring constructor as final

In inheritance whenever you extend a class. The child class inherits all the members of the superclass except the constructors.

In other words, constructors cannot be inherited in Java, therefore, you cannot override constructors.

So, writing final before constructors make no sense. Therefore, java does not allow final keyword before a constructor.

If you try, make a constructor final a compile-time error will be generated saying “modifier final not allowed here”

7)Can we synchronize abstract methods in Java?

Ans)Synchronization − If a process has multiple threads running independently at the same time (multi-threading) and if all of them trying to access the same resource an issue occurs.

To resolve this, Java provides synchronized blocks/ synchronized methods. If you define a resource (variable/object/array) inside a synchronized block or a synchronized method, if one thread is using/accessing it, other threads are not allowed to access.

synchronized (Lock1) {
   System.out.println("Thread 1: Holding lock 1...");
}

Synchronizing abstract methods

No, you can’t synchronize abstract methods in Java. When you synchronize a method that implies that you are synchronizing the code in it, i.e. when one thread is accessing the code of a synchronized method no other thread is allowed to access it. So synchronizing abstract methods doesn’t make sense, if you still try to do so a compile-time error will be generated.

8)Can we declare an abstract method, private, protected, public or default in java?

Ans)

Declaring an abstract method private

If a method of a class is private, you cannot access it outside the current class, not even from the child classes of it.

But, incase of an abstract method, you cannot use it from the same class, you need to override it from subclass and use.

Therefore, the abstract method cannot be private.

If, you still try to declare an abstract method final a compile time error is generated saying “illegal combination of modifiers − abstract and private”.

Declaring an abstract method protected

Yes, you can declare an abstract method protected. If you do so you can access it from the classes in the same package or from its subclasses.

(Any you must to override an abstract method from the subclass and invoke it.)

9)Can abstract method declaration include throws clause in java?

Ans)Yes, you can throw and exception from an abstract class.

10)If a method in parent class “throws Exception”, can we remove it in overridden method in java?

Ans)While a superclass method throws an exception while overriding it you need to follow the certain rules.

  • The sub class method Should throw Same exception or, sub type −
  • It should not throw an exception of super type −
  • You may leave the method in sub class Without throwing any exception

According to the 3rd rule, if the super-class method throws certain exception, you can override it without throwing any exception.

Example

In the following example the sampleMethod() method of the super-class throws FileNotFoundException exception and, the sampleMethod() method does not throw any exception at all. Still this program gets compiled and executed without any errors.

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
abstract class Super{
   public void sampleMethod()throws FileNotFoundException{
      System.out.println("Method of superclass");
   }
}
public class ExceptionsExample extends Super{
   public void sampleMethod() {
      System.out.println("Method of Subclass");
   }
   public static void main(String args[]) {
      ExceptionsExample obj = new ExceptionsExample();
      obj.sampleMethod();
   }
}

Output

Method of Subclass

11)Can a class in Java be both final and abstract?
Ans)An abstract cannot be instantiated. Therefore to use an abstract class you need to create another class and extend the abstract class and use it.

If a class is final you can’t extend it further.

So, you cannot declare a class both final and abstract

12)Can we override default methods in Java?

Ans)An interface in Java is similar to class but, it contains only abstract methods and fields which are final and static.

Since Java8 static methods and default methods are introduced in interfaces. Unlike other abstract methods these are the methods can have a default implementation. If you have default method in an interface, it is not mandatory to override (provide body) it in the classes that are already implementing this interface.

In short, you can access the default methods of an interface using the objects of the implementing classes.


13)How to write/declare an interface inside a class in Java?

Ans)

Nested interfaces

Java allows writing/declaring interfaces within another interface or, within a class these are known as nested interfaces.

Example

In the following Java example, we have a class with name Sample which contains a nested interface named myInterface.

In the class Sample we are defining a nested class named InnerClass and implementing the nested interface.

 Live Demo

public class Sample {
   interface myInterface{
      void demo();
   }
   class InnerClass implements myInterface{
      public void demo(){
         System.out.println("Welcome to Ramesh Tutorials blog");
      }
   }
   public static void main(String args[]){
      InnerClass obj = new Sample().new InnerClass();
      obj.demo();
   }
}

Output

Welcome to Ramesh Tutorials blog

You can also implement the nested interface using class name as −

Example

 Live Demo

class Test {
   interface myInterface{
      void demo();
   }
}
public class Sample implements Test.myInterface{
   public void demo(){
      System.out.println("Hello welcome to Ramesh qa automation blog ");
   }
   public static void main(String args[]){
      Sample obj = new Sample();
      obj.demo();
   }
}

Output

Hello welcome to  Ramesh qa automation blog

13)Can we declare an interface as final in java?
Ans)If you make an interface final, you cannot implement its methods which defies the very purpose of the interfaces. Therefore, you cannot make an interface final in Java. Still if you try to do so, a compile time exception is generated saying “illegal combination of modifiers − interface and final”.

14)Can we declare a constructor as private in Java?
Ans)Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.

Conditions for Private Constructor

  • private constructor does not allow a class to be subclassed.
  • private constructor does not allow to create an object outside the class.
  • If all the constant methods are there in our class we can use a private constructor.
  • If all the methods are static then we can use a private constructor.
  • If we try to extend a class which is having private constructor compile time error will occur
15)Can we declare a main method as private in Java?
Ans)Yes, we can declare the main method as private in Java.

It compiles successfully without any errors but at the runtime, it says that the main method is not public.

Example:

class PrivateMainMethod {
   private static void main(String args[]){
       System.out.println("Welcome to Ramesh qa automation platfomr blog ");
    }
}

The above code is working successfully at compile time but it will throw an error at the runtime.

Output:

Error: Main method not found in class PrivateMainMethod, please define the main
method as:
public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

16)Can We declare main() method as Non-Static in java?
Ans)The public static void main(String ar[]) method is the entry point of the execution in Java. When we run a .class file JVM searches for the main method and executes the contents of it line by line.

You can write the main method in your program without the static modifier, the program gets compiled without compilation errors. 

But, at the time of execution JVM does not consider this new method (without static) as the entry point of the program.  It searches for the main method which is public, static, with return type void, and a String array as an argument.

public static int main(String[] args){
}

If such a method is not found, a run time error is generated.

Example

In the following Java program in the class Sample, we have a main method which is public, returns nothing (void), and accepts a String array as an argument. But, not static.

 Live Demo

import java.util.Scanner;
public class Sample{
   public void main(String[] args){
      System.out.println("This is a sample program");
   }
}

Output

On executing, this program generates the following error −

Error: Main method is not static in class Sample, please define the main method as − public static void main(String[] args)

17)Can we declare the main () method as final in Java?
Ans)Yes, we can declare the main () method as final in Java. The compiler does not throw any error.
  • If we declare any method as final by placing the final keyword then that method becomes the final method.
  • The main use of the final method in Java is they are not overridden.
  • We can not override final methods in subclasses.
  • If we are using inheritance and we need some methods not to overridden in subclasses then we need to make it final so that those methods can't be overridden by subclasses.
  • We can access final methods in the subclass but we can not override final methods.

Example

class BaseClass {
   public final void show(Object o) {
      System.out.println("BaseClass method");
   }
}
class DerivedClass extends BaseClass {
   public void show(Integer i) {
      System.out.println("DerivedClass method");
   }
}
public class Test {
   public static final void main(String[] args) { // declaring main () method with final keyword.
      BaseClass b = new BaseClass();
      DerivedClass d = new DerivedClass();
      b.show(new Integer(0));
      d.show(new Integer(0));
   }
}

Output

BaseClass method
DerivedClass method

18)Can we declare the method of an Interface final in java?

Ans)you cannot declare the method of an interface final.

19)Can we declare final variables without initialization in java?
Ans)

Declaring final variable without initialization

If you declare a final variable later on you cannot modify or, assign values to it. Moreover, like instance variables, final variables will not be initialized with default values.

Therefore, it is mandatory to initialize final variables once you declare them.

Still, if you try to declare final variables without initialization that will generate a compilation error saying "variable variable_name not initialized in the default constructor"

Example

In the following Java program, the class Student contains two final variables name and age and they have not been initialized.

 Live Demo

public class Student {
   public final String name;
   public final int age;
   public void display(){
      System.out.println("Name of the Student: "+this.name);
      System.out.println("Age of the Student: "+this.age);
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Compile time error

On compiling, this program generates the following error.

Output

Student.java:3: error: variable name not initialized in the default constructor
private final String name;
^
Student.java:4: error: variable age not initialized in the default constructor
private final int age;
^
2 errors

To resolve this, you need to initialize the declared final variables as −

Example

 Live Demo

public class Student {
   public final String name;
   public final int age;
   public Student(){
      this.name = "Raju";
         this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Output

Name of the Student: Raju
Age of the Student: 20


20)Can we declare the variables of a Java interface private and protected?
Ans)

Private fields of an interface

If the fields of the interface are private, you cannot access them in the implementing class.

If you try to declare the fields of an interface private, a compile time error is generated saying “modifier private not allowed here”.

Example

In the following Java example, we are trying to declare the field and method of an interface private.

public interface MyInterface{
   private static final int num = 10;
   private abstract void demo();
}

Compile time error

On compiling, the above program generates the following error

Output

MyInterface.java:2: error: modifier private not allowed here
   private static final int num = 10;
                          ^
MyInterface.java:3: error: modifier private not allowed here
   private abstract void demo();
^
2 errors

Protected fields of an interface

In general, the protected fields can be accessed in the same class or, the class inheriting it. But, we do not inherit an interface we will implement it.

Therefore, cannot declare the fields of an interface protected. If you try to do so, a compile time error is generated saying “modifier protected not allowed here”.

Example

In the following Java example, we are trying to declare the field and method of an interface protected.

public interface MyInterface{
   protected static final int num = 10;
   protected abstract void demo();
}

Output

MyInterface.java:2: error: modifier protected not allowed here
   protected static final int num = 10;
^
MyInterface.java:3: error: modifier protected not allowed here
   protected abstract void demo();

21)Why do we need private methods in an interface in Java 9?
Ans)An interface supports default methods since Java 8 version. Sometimes these default methods may contain a code that can be common in multiple methods. In those situations, we can write another default method and make code reusability. When the common code is confidential then it's not advisable to keep them in default methods because all the classes that implement that interface can access all default methods.

An interface can have private methods since Java 9 version. These methods are visible only inside the class/interface, so it's recommended to use private methods for confidential code. That's the reason behind the addition of private methods in interfaces.

In an interface, there is a possibility of writing common code on more than one default method that leads to code duplication. The introduction of private methods avoids this code duplication.

Advantages of private methods in an interface

  • Avoiding code duplication.
  • Ensuring code re-usability.
  • Improving code readability.

Syntax

private void methodName() {
   // some statementscode
}

Example

interface Operation {
   default void addition() {
      System.out.println("default method addition");
   }
   default void multiply() {
      division();
      System.out.println("default method multiply");
   }
   private void division() {         // private method
      System.out.println("private method division");
   }
}

class PrivateMethodTest implements Operation {
   public static void main(String args[]) {
      PrivateMethodTest test = new PrivateMethodTest();
      test.multiply();
   }
}

Output

private method division
default method multiply


22)Can we initialize blank final variable in Java

Ans)Yes! You can initialize a blank final variable in constructor or instance initialization block.

23)What is blank final variable? What are Static blank final variables in Java?
Ans)

Static variables − Static variables are also known as class variables. You can declare a variable static using the keyword. Once you declare a variable static there would only be one copy of it in the class, regardless of how many objects are created from it.

public static int num = 39;

Instance variables − These variables belong to the instances (objects) of a class. These are declared within a class but outside methods. These are initialized when the class is instantiated. They can be accessed from any method, constructor or blocks of that particular class.

You must access instance variables using an object. i.e. to access an instance variable you need to create an object of the class and using this object you need to access these variables.

final − Once you declare a variable final you cannot reassign value to it.

Blank variables

A final variable which is left without initialization is known as blank final variable. Like instance variables, final variables will not be initialized with default values. Therefore, it is mandatory to initialize final variables once you declare them.

Still, if you try to use blank variables in your code, a compile time error will be generated.

Example

In the following Java program, the class Student contains two final variables name and age and they have not been initialized.

public class Student {
   public final String name;
   public final int age;
   public void display(){
      System.out.println("Name of the Student: "+this.name);
      System.out.println("Age of the Student: "+this.age);
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Compile time error

On compiling, this program generates the following error.

Student.java:3: error: variable name not initialized in the default constructor
   private final String name;
                        ^
Student.java:4: error: variable age not initialized in the default constructor
   private final int age;
                     ^
2 errors

Solution

To resolve this, you need to initialize the declared final variables as −

public class Student {
   public final String name;
   public final int age;
   public Student(){
      this.name = "Raju";
      this.age = 20;
   }
   public void display(){
      System.out.println("Name of the Student: "+this.name );
      System.out.println("Age of the Student: "+this.age );
   }
   public static void main(String args[]) {
      new Student().display();
   }
}

Output

Name of the Student: Raju
Age of the Student: 20

Static blank final variable

In the same way if you declare a static variable final without initializing it, it is considered as static final variable.

When a variable is declared both static and final you can initialize it only in a static block, if you try to initialize it elsewhere, the compiler assumes that you are trying to reassign value to it and generates a compile time error −

Example

class Data{
   static final int num;
   Data(int i){
      num = i;
   }
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of the constant: "+Data.num);
   }
}

Compile time error

ConstantsExample.java:4: error: cannot assign a value to final variable num
   num = i;
   ^
1 error

Example

Therefore, it’s a must to initialize a static final variable in a static block.

To make the above program work you need to initialize the final static variable in a static block as −

class Data{
   static final int num;
   static{
      num = 1000;
   }
}
public class ConstantsExample {
   public static void main(String args[]) {
      System.out.println("value of the constant: "+Data.num);
   }
}

Output

value of the constant: 1000

24)Can we declare a try catch block within another try catch block in Java?
ANs)Yes, we can declare a try-catch block within another try-catch block, this is called nested try-catch block

25)Can we have a try block without a catch block in Java?
Ans)Yes, It is possible to have a try block without a catch block by using a final block.

As we know, a final block will always execute even there is an exception occurred in a try block, except System.exit() it will execute always.

Example 1

public class TryBlockWithoutCatch {
   public static void main(String[] args) {
      try {
         System.out.println("Try Block");
      } finally {
         System.out.println("Finally Block");
      }
   }
}

Output

Try Block
Finally Block

A final block will always execute even though the method has a return type and try block returns some value.

Example 2

public class TryWithFinally {
   public static int method() {
      try {
         System.out.println("Try Block with return type");
         return 10;
      } finally {
         System.out.println("Finally Block always execute");
      }
   }
   public static void main(String[] args) {
      System.out.println(method());
   }
}

Output

Try Block with return type
Finally Block always execute
10

26)Can a try block have multiple catch blocks in Java?
Ans)Yes, you can have multiple catch blocks for a single try block.

27)Is it possible to have multiple try blocks with only one catch block in java?
Ans)

Multiple try blocks:

You cannot have multiple try blocks with a single catch block. Each try block must be followed by catch or finally. Still if you try to have single catch block for multiple try blocks a compile time error is generated.

Example

The following Java program tries to employ single catch block for multiple try blocks.

class ExceptionExample{
   public static void main(String args[]) {
      int a,b;
      try {
         a=Integer.parseInt(args[0]);
         b=Integer.parseInt(args[1]);
      }
      try {
         int c=a/b;
         System.out.println(c);
      }catch(Exception ex) {
         System.out.println("Please pass the args while running the program");
      }
   }
}

Compile time exception

ExceptionExample.java:4: error: 'try' without 'catch', 'finally' or resource declarations
   try {
   ^
1 error

28)Is it possible to catch multiple Java exceptions in single catch block?
Ans)Yes

In this, you need to specify all the exception classes to be handled separated by “ | ” as shown below −

catch(ArrayIndexOutOfBoundsException | ArithmeticException exp) {
   System.out.println("Warning: Enter inputs as per instructions ");
}

29)Can we have an empty catch block in Java?
Ans)Yes, we can have an empty catch block. But this is a bad practice to implement in Java

30)Can we have a return statement in the catch or, finally blocks in Java?

Ans)Yes, we can write a return statement of the method in catch and finally block.
  • There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.
  • If we return a value in the catch block and we can return a value at the end of the method, the code will execute successfully.
  • If we return a value in the catch block and we can write a statement at the end of the method after return a value, the code will not execute so it became unreachable code as we know Java does not support unreachable codes.
  • If we return a value in the final block and no need of keeping a return value at the end of the method.

Example 1

public class CatchReturn {
   int calc() {
      try {
         int x=12/0;
      } catch (Exception e) {
         return 1;
      }
      return 10;
   }
   public static void main(String[] args) {
      CatchReturn cr = new CatchReturn();
      System.out.println(cr.calc());
   }
}

Output

1

Example 2

public class FinallyReturn {
   int calc() {
      try {
         return 10;
      } catch(Exception e) {
         return 20;
      } finally {
         return 30;
      }
   }
   public static void main(String[] args) {
      FinallyReturn fr = new FinallyReturn();
      System.out.println(fr.calc());
   }
}

Output

30

31)Will a finally block execute after a return statement in a method in Java?

Ans)Yes, the finally block will be executed even after a return statement in a method. 

The finally block will always execute even an exception occurred or not in Java. If we call the System.exit() method explicitly in the finally block then only it will not be executed. There are few situations where the finally will not be executed like JVM crashpower failuresoftware crash and etc. Other than these conditions, the finally block will be always executed.

Example

public class FinallyBlockAfterReturnTest {
   public static void main(String[] args) {
      System.out.println(count());
   }
   public static int count() {
      try {
         return 1;
      } catch(Exception e) {
         return 2;
      } finally {
         System.out.println("Finally block will execute even after a return statement in a method");
      }
   }
}

Output

Finally block will always excute even after a return statement in a method
1

32)Is there a case when finally block does not execute in Java?
Ans)when thread is dead
 when exception throws in finally block
when we call System.exit()

33)How to execute a static block without main method in Java?
Ans)

VM first looks for the main method (at least the latest versions) and then, starts executing the program including static block. Therefore, you cannot execute a static block without main method.

Example

public class Sample {
   static {
      System.out.println("Hello how are you");
   }
}

Since the above program doesn’t have a main method, If you compile and execute it you will get an error message.

C:\Sample>javac StaticBlockExample.java
C:\Sample>java StaticBlockExample
Error: Main method not found in class StaticBlockExample, please define the main method as: public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application

If you want to execute static block you need to have Main method and, static blocks of the class gets executed before main method.

Example

Live Demo

public class StaticBlockExample {
   static {
      System.out.println("This is static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

Output

This is static block
This is main method

34)Why main() method must be static in java?
Ans)Static − If you declare a method, subclass, block, or a variable static it is loaded along with the class.

In Java whenever we need to call an (instance) method we should instantiate the class (containing it) and call it. If we need to call a method without instantiation it should be static. Moreover, static methods are loaded into the memory along with the class.

In the case of the main method, it is invoked by the JVM directly, so it is not possible to call it by instantiating its class. And, it should be loaded into the memory along with the class and be available for execution. Therefore, the main method should be static.

When the main method is non-static

The public static void main(String ar[]) method is the entry point of the execution in Java. When we run a .class file JVM searches for the main method and executes the contents of it line by line.

You can write the main method in your program without the static modifier, the program gets compiled without compilation errors. But, at the time of execution JVM does not consider this new method (without static) as the entry point of the program.

It searches for the main method which is public, static, with return type void, and a String array as an argument.

public static int main(String[] args){
}

If such a method is not found, a run time error is generated.

Example

In the following Java program in the class Sample, we have a main method which is public, returns nothing (void), and accepts a String array as an argument. But, not static.

 Live Demo

import java.util.Scanner;
public class Sample{
   public void main(String[] args){
      System.out.println("This is a sample program");
   }
}

Output

On executing, this program generates the following error −

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

35)Why "this" keyword cannot be used in the main method of java class?
Ans)The static methods belong to the class and they will be loaded into the memory along with the class. You can invoke them without creating an object. (using the class name as reference).

Example

public class Sample{
   static int num = 50;
   public static void demo(){
      System.out.println("Contents of the static method");
   }
   public static void main(String args[]){
      Sample.demo();
   }
}

Output

Contents of the static method

The "this" keyword is used as a reference to an instance. Since the static methods doesn’t have (belong to) any instance you cannot use the "this" reference within a static method. If you still, try to do so a compile time error is generated.

And main method is static therefore, you cannot use the "this" reference in main method.

Example

public class Sample{
   int num = 50;
   public static void main(String args[]){
      System.out.println("Contents of the main method"+this.num);
   }
}

Compile time error

Sample.java:4: error: non-static variable this cannot be referenced from a static context
   System.out.println("Contents of the main method"+this.num);
                                                    ^
1 error

ACCENTURE INTERVIEW QUESTIONS:

1. Tell me about yourself?
2. Tell me about your roles and responsibilities?
3. which framework you are using?
4. Which jar file you are using for Datadriven and explain?
5. How to get column from excel 3 coloumn, 2 row?
6. How to write and send the values to text box?
7. What is the difference between single / and // explain?
8. How many ways identify the filed in selenium?
9. Which is fastest?
10. What is difference between implicit wait and explicit wait?
11. Xpath questions?
12. What is interface? What is the use of interface?
13. What is abstract class?
14. What is the difference between interface and abstract?
15. What is static block?
16. What is purpose of static in main method? Without static main method class will be
working or not?
17. One static block, one main method, one constructor what is the execution flow? 18. What is web driver? Why we use web driver?
19. Which jar file you are using for web driver?
20. Webdriver define in which class?
21. What is difference between list and set?
22. Which class define in list and set?
23. How to select a particular value from drop down with examples and what is the
difference between select by value and select by visible text? 24. What is hash map and hash table in collections?
25. Class a {
result()
}
Class b extends a {
Result()
}
• In this scenario we calling class b method what is the output?
• In this case how to define super keyword in your class?
26. How to create/ call obj in interface?
27. How to create object for static class?
28. How to call/invoke the method of class b from your program?
29. What are the different methods in mouse events?
30. How to handle hover menus?
31. What is the difference between final and finally and finalize?