Prev Next

Java / Methods

1. Is the main() method required for all java classes? 2. Can a main method be declared final? 3. Difference between arguments and parameters in Java. 4. What is the return type of main() method? 5. Why does the main() method declared static? 6. What is the the argument for main() method? 7. Can a main() method be overloaded? 8. When no command line arguments are passed, does the String array parameter of main() method be null? 9. Can we invoke a static method on a null object reference in Java? 10. Explain the Default method for interfaces in Java 8. 11. Advantages of default method in Interface feature in Java 8. 12. Explain the static interface methods feature in Java 8. 13. Advantages of using static interface method in Java 8. 14. Difference between default and static methods in Java interface. 15. Explain pass by reference and pass by value in Java? 16. Difference between System.exit(0), exit (1) and exit(-1) in Java. 17. What is virtual function/method in Java? 18. Can we define a static method in a Java interface? 19. What is fluent interface in Java? 20. Explain method chaining in Java. 21. What is synthetic method in Java? 22. What is bridge method in Java? 23. What is a method reference in Java 8? 24. Types of method references in Java 8. 25. Are Java static calls less expensive than non-static calls? 26. What is lambda expression in Java 8? 27. What is the target type of lambda expression? 28. Can you Serialize lamda expression in Java8? 29. What is System.out::println expression? 30. Other names for default methods in Java 8. 31. Is abstract modifier allowed in default method? 32. What is the scope of default methods in Java8? 33. How do I extend Interfaces that contain Default Methods? 34. Explain the scenario how Default Method can cause Multiple Inheritance Ambiguity Problem. 35. Why Java doesn't allow overriding of static methods? 36. Explain public static void main(String args[]) method signature. 37. How to call a default method of an interface in a class? 38. How to invoke a static method of an interface? 39. Explain System.out.println().
Could not find what you were looking for? send us the question and we would be happy to answer your question.

1. Is the main() method required for all java classes?
Posted on Apr 1, 2016 by Senthil Kumar.

No. main() method is defined only if the java class is an application and has to execute.

2. Can a main method be declared final?
Posted on Apr 1, 2016 by Senthil Kumar.

Yes, so that the subclass cannot override main() method.

3. Difference between arguments and parameters in Java.

A parameter is that appears in the definition of the method. An argument is the instance or value passed to the method during runtime when the method is invoked.

4. What is the return type of main() method?
Posted on Apr 1, 2016 by Senthil Kumar.

void. main() method does not return any value.

5. Why does the main() method declared static?
Posted on Apr 1, 2016 by Senthil Kumar.

JVM need to access the main() method even before the class instantiation so begin the execution. so it is declared static.

6. What is the the argument for main() method?
Posted on Apr 1, 2016 by Senthil Kumar.

There is only one argument that main() method accepts.

main() method accepts a vararg/array of string object as an argument.

7. Can a main() method be overloaded?
Posted on Apr 1, 2016 by Senthil Kumar.

Yes.

8. When no command line arguments are passed, does the String array parameter of main() method be null?

It is an empty Array with zero elements and not null.

public class MainMethodClass {

	public static void main(String[] args) {

		System.out.println("Size of the Arg Array=" + args.length);
	}
}

Output: 0

9. Can we invoke a static method on a null object reference in Java?

Yes. The compiler optimizes the code to invoke the static method using null object reference since object instance is not required to invoke a static method.

public class StaticMethodUsingNull {

	static void printWelcomeMessage() {
		System.out.println("Welcome to javapedia.net!");
	}

	public static void main(String[] args) {
		StaticMethodUsingNull myRef = null;
		myRef.printWelcomeMessage(); /*Message will be printed sucessfully*/

	}

}

In case of calling a non-static (instance) method using null object reference, it will throw NullPointerException.

10. Explain the Default method for interfaces in Java 8.

In Java 8, a new feature "default method implementation for interfaces" is introduced that facilitates backward compatibility for the old interfaces to leverage the lambda expression capability of Java 8 and also existing libraries implementing these interfaces need not have to provide its implementation for the new functionality/method added to the interface.

For example, java.util.List or Collection interface does not have forEach method declaration. Thus, calling such methods will break the collection framework implementations. Java 8 introduces default method so that List/Collection interface can have a default implementation of forEach method, and the class implementing these interfaces need not have to implement the same.

Thus default methods enable you to add new functionality to the interfaces of your libraries and ensure backward compatibility with the codes written using the older versions of those interfaces without having to implement the new functionality.

For creating a default method in Java interface, we need to use default keyword with the method signature.

public interface Fruits {
   default void nature(){
      System.out.println("I am Sweet.");
   }
}

The default methods are non-static and can be accessed from the Implementing class object as shown in the below example.

public class OrangeClass implements Fruits {

	public static void main(String[] args) {
		Fruits fruit = new OrangeClass();
		
		fruit.nature();
	}

}

Java interface default methods are also known as Defender Methods or Virtual extension methods.

A default method cannot override a method from java.lang.Object class as interfaces does not extend Object.

Compilation error occurs when a class tries to implement two or more interfaces having a default method with the same signature.

Other than multiple inheritance, there is no significant difference between an abstract class and an interface in Java 8 by the addition of default method feature.

11. Advantages of default method in Interface feature in Java 8.
  • Using default methods for interfaces eliminates the need for utility classes, for example, the java.util.Collections utility class is not required when all of its methods are provided in the Collection interface itself as default methods.
  • It helps in extending interfaces without the concern of breaking the implementation classes.
  • Default methods in interfaces enhances the Collections API in Java 8 to support lambda expressions.
  • Java interface default methods has bridged down the differences between interface and abstract class.
  • Interface implementing concrete classes can choose which default method to override and can use interface default implementation itself.
12. Explain the static interface methods feature in Java 8.

The interface static methods are concrete methods implemented in the interface that prevents the implementation classes from overriding to ensure the proper and uniform implementation being used across all the implementation classes.

The static interface method has method body and marked with static keyword in the method signature.

public interface Fruits {
	static void eat() {
		System.out.println("Enjoy!");
	}
}

Java interface static methods are visible to interface methods only and it can be invoked by interface name itself.

public class OrangeClass implements Fruits {

	public static void main(String[] args) {
		
		Fruits.eat();
	}
}

13. Advantages of using static interface method in Java 8.
  • Java interface static methods are suitable for providing utility function and acts as utility methods, for example sorting a Collection, validations, reversing a collection etc.
  • Java interface static method ensures quality and security by preventing the implementation classes to override them.
14. Difference between default and static methods in Java interface.

Default method.Static method.
default method are used as a default implementation for classes that implements that interface.static method in interface is used as Helper methods.
default methods can be invoked by the implementation class objects. static methods are similar to static class methods and can be invoked using Interface name.

15. Explain pass by reference and pass by value in Java?

When an object is passed by value, this means that a copy of the object is passed. Thus, even if changes are made to that object, it doesn't affect the original value. When an object is passed by reference, this means that the actual object is not passed, rather a reference of the object is passed. Thus, any changes made by the external method, are also reflected in all places.

16. Difference between System.exit(0), exit (1) and exit(-1) in Java.

Zero represents that the program ended successfully. Any number greater than zero represents program execution failed. Number less than zero represents program execution error.

17. What is virtual function/method in Java?

In Java, all non-static methods are considered as virtual functions. The Final methods cannot be overridden and the private methods cannot be inherited so it is considered as non-virtual.

18. Can we define a static method in a Java interface?

With Java 8, interfaces can have static methods. They can also have concrete instance methods, but not instance fields.

19. What is fluent interface in Java?

The fluent interface enables to apply multiple properties/setters on an object just by using dots(.) without having to use the actual object reference.

Fluent interface is also known as fluent API.

new Employee().setName("Jacob")
                          .setAge(46)
                          .setActive(true);

20. Explain method chaining in Java.

Method chaining is a mean by which fluent API could be used so that multiple setters on a method be invoked continuously by just using dot(.) that improves readability and less code.

To achieve method chaining update the setters to return the object instance or by using this keyword.

21. What is synthetic method in Java?

Synthetic method is a compiler created method after the type erasure on the generic methods.

22. What is bridge method in Java?

Java compiler creates a synthetic method known as bridge method when compiling a class or interface that extends a parameterized class or interface as part of type erassure.

23. What is a method reference in Java 8?

A method reference is a Java 8 construct that can be used for referencing a method without invoking it. It is used for treating methods as Lambda Expressions.

They can only be used to replace a single-method lambda expression.

The general syntax of a method reference: Object :: methodName

In method reference, you place the object (or class) that contains the method before the :: operator and the name of the method after it without arguments.

24. Types of method references in Java 8.
  • A method reference to a static method.
  • A method reference to an instance method of an object of a particular type.
  • A method reference to an instance method of an existing object.
  • A method reference to a constructor.
25. Are Java static calls less expensive than non-static calls?

Static methods are usually faster (comparatively) as we don't need 'this' object reference for static calls. However, the performance is negligible when compared to the non-static method calls and no decision should be made based on performance when choosing static methods vs non-static methods.

26. What is lambda expression in Java 8?

A lambda expression is an anonymous function that you can use to create delegates or expression tree types. By using lambda expressions, you can write local functions that can be passed as arguments or returned as the value of function calls. A lambda expression is the most convenient way to create that delegate.

27. What is the target type of lambda expression?

The data type that the methods expect is called the target type. To determine the type of a lambda expression, the Java compiler uses the target type of the context or situation in which the lambda expression was found.

28. Can you Serialize lamda expression in Java8?

Yes. You can serialize a lambda expression if its target type and its captured arguments are serializable. However the serialization of lambda expressions is strongly discouraged.

29. What is System.out::println expression?

System.out::println method in Java 8 is a static method reference to println method of out object of System class.

30. Other names for default methods in Java 8.

Default method is also known as defender method or virtual extension method.

31. Is abstract modifier allowed in default method?

No, we encounter compile time error. default modifier is used for methods with implementation.

32. What is the scope of default methods in Java8?

All the method declarations in an interface, including default methods, are implicitly public, so you can omit the public modifier.

33. How do I extend Interfaces that contain Default Methods?

When you extend an interface that contains a default method, you may do one of the following:

  • Not mention the default method at all, which lets your extended interface inherit the default method.
  • Redeclare the default method to make it abstract.
  • Redefine the default method to override it.
34. Explain the scenario how Default Method can cause Multiple Inheritance Ambiguity Problem.

Java class can implement multiple interfaces and each interface can define default method with same method signature, therefore, the inherited methods can conflict with each other.

public interface Interface1 { 
    default void myDefaultMethod(){ 
        System.out.println("Interface One default method"); 
    } 
}
public interface Interface2 {
    default void myDefaultMethod(){
        System.out.println("Interface Two default method");
    }
}
public class ImplClass implements Interface1, Interface2  {
}

The above code will fail to compile with the error. To fix this class, we need to provide default method implementation.

public class ImplClass implements Interface1, Interface2  {
    public void myDefaultMethod() {
     }
}

Additionally, we may invoke default implementation provided by any of super interface by using super keyword as shown below.

public class ImplClass implements Interface1, Interface2  {
    public void myDefaultMethod() {
        Interface2.super.myDefaultMethod();
     }
}
35. Why Java doesn't allow overriding of static methods?

Overriding depends on having an instance of an class and static method is not associated to instance of the class.

36. Explain public static void main(String args[]) method signature.

public access modifier specify who can access this method. Public will be accessible by any Class from any package.

static keyword identifies it is class based and it can be invoked without creating a class instance.

void is the return type of the method. Void indicates that the method does not return any value.

main is the name of the method which is invoked by JVM as a starting point of execution for an application.

String args[] holds the command line parameters passed to the main method.

37. How to call a default method of an interface in a class?

Use super keyword along with interface name to invoke a default method.

public interface Animal {
    default void feed() {
        System.out.println("Feed some food to animals");
    }
}

public class Dog  implements Animal{
    public void feed() {
        Animal.super.feed();
    }
}

38. How to invoke a static method of an interface?

Invoke the static method using the name of the interface.

public interface Animal {
    static void doSwim() {
        System.out.println("Animal can swim");
    }
}
public class Dog implements Animal {
    public void canSwim() {
        Animal.doSwim();
    }
}

39. Explain System.out.println().

System.out.println() is used to print the message on the console. System is a class present in java.lang package. The "out" is the static variable of type PrintStream class present in the System class. println() is the method present in the PrintStream class.

«
»
Data types

Comments & Discussions