7.What is method overriding in Java? How does it work? Can you give example?
Method overriding in Java This happens in a scenario in which the child class overrides one of its specific implementations that may already exist within the superclass. The overriding method must share similar names have the same type of return value as well as its parameter list and the one appearing in the superclass. This thus enables the providing of subclass behaviour for the defined method of its parent class.
Example:
public class Animal
{
public void sound(){}
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks");
}
}
Here, the sound() method in Dog overrides the sound() method in Animal. When sound() is called on a Dog object, it prints "Dog barks".
8.What does a return statement do in a method and to what effect?
The return statement in Java is used to exit a method and optionally return a value to the caller. It is very important for methods with a non void return type since it specifies the value that the method will return. If the return type of the method is void then the return statement can be used to exit the method without returning any value.
Example:
public int add(int a, int b)
{
return a + b; /* returns the sum of a and b*/
}
In this example, return exits the method add and returns the result of a + b. The return statement also ends the execution of the method.
9.How do you call a method in Java and how do you pass arguments to a method?
To call a method in Java you first need to have an instance of the class (for instance methods) or use the class name (for static methods). You then specify the method name followed by parentheses containing the arguments.
For example:
// Calling an instance method
MyClass obj = new MyClass();
obj.methodName(arg1, arg2);
// Calling a static method
MyClass.methodName(arg1, arg2);
When you invoke a method, you pass arguments that match the parameter types declared for the method.
For example, if the method accepts an int and a String argument you need to pass an integer and a string when invoking the method.
10.What does the void keyword do in a Java method?
In Java, the keyword void is declared for methods with no return values. A void method does not require a return statement since there is no need to return something to the calling function. Often, void keyword is used with methods that just do something but they need not return the data.
For example:
public void printMessage() {
System.out.println("Hello, World!");
}
In this case, printMessage() does not return anything, so it is declared as void. The method simply performs an action (printing a message to the console).
11.How are instance methods and static methods different in Java?
Mainly, static methods and instance methods differ in their association with an object. An instance method belongs to an instance (object) of the class. Instance methods have access to instance variables and methods and need an object to be invoked.
Example:
public void instanceMethod() {
System.out.println("This is an instance method.");
}
Static methods are part of the class itself. They can be invoked without creating an object. They can only refer to static variables and other static methods.
Example:
public static void staticMethod() {
System.out.println("This is a static method.");
}
Static methods are very useful for utility functions or operations that do not depend on object state.
12.What is the main method in Java and why is it special?
The entry point of the program is a main method in Java.
It is declared as follows:
public static void main(String[] args) {
// Code to run
}
It is special because it is the first method called when a Java application is launched. The main method has to be static because it is called by the JVM without creating an instance of the class. Also, it accepts a String array as a parameter allowing command-line arguments to be passed to the program.
13.Rules for method overloading in Java
Method overloading in Java: Multiple methods are having the same name but differs in the number or types of parameters.
Rules for overloading:
•Methods should have the same name.
•Different parameter lists by number, type or both.
•Return type is not considered when distinguishing between overloaded methods.
For example:
public int add(int a, int b)
{
return a + b;
}
public double add(double a, double b)
{
return a + b;
}
This example, the methods add are distinguished by their parameter types (int vs. double).
14.How does Java support variable arguments in methods (varargs)?
In Java, variable arguments (varargs) allow a method to accept a variable number of arguments. Varargs are passed as an array and it must be the last parameter in the method signature.
The syntax for varargs is:
public void displayNumbers(int.... numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
Here, int.... numbers enables you to pass any number of integers (including none) to the method. Varargs is handy for use when you don't know in advance how many arguments will be passed.
15.What is recursion in Java and give an example of a recursive method?
Recursion in Java is a method that calls itself to solve smaller versions of the same problem. A recursive method typically has two parts:
1. Base case: The condition when the method stops calling itself.
2. Recursive case: The part where the method calls itself with modified parameters.
Example: Calculation of the factorial using recursion:
public int factorial(int n) {
if (n == 0) {
return 1; // Base case
} else
return n * factorial(n - 1); // Recursive case
}
In this example, factorial calls itself until n equals 0.
16.What is the difference between this and super keyword when used in methods?
In Java, both this and super are used within methods but they serve different purposes:
•this refers to the current object. It is used to access instance variables, methods, or constructors of the current class.
Example:
public void printName() {
System.out.println(this.name);
}
super refers to the parent class. It is used to call methods or constructors from the parent class or to access inherited variables.
Example:
public void callSuperMethod() {
super.printDetails();
}
17.What is the use of final keyword with methods in Java?
The final keyword in Java when used with the method prevents overriding of that method by any class. It makes sure that for a specific class you may not change its behavior in sub-classes.
Example:
public final void display() {
System.out.println("This method cannot be overridden.");
}
Here, display() cannot be overridden in any class that extends the class containing this method.
18.How does Java handle method parameters passed by value or reference?
In Java, method parameters are always passed by value. However the value passed differs based on whether it is a primitive type or an object:
•Primitive types: The method receives a copy of the value, so any changes made to the parameter inside the method do not affect the original value.
•Object references: The method receives a copy of the reference (not the object itself). Although the reference cannot be changed the object it points to can be modified.
Example:
public void modify(int x){
x = 10; // Alters local copy, not the original value
}
19.Why is return type important in the declaration of methods in Java?
The return type in a method declaration specifies the type of value the method will return to the caller. If the method does not return anything the return type is void. The return type helps the compiler enforce type safety by ensuring that the correct type of value is returned.
For example:
public int add(int a, int b) {
return a + b;
}
In this case, the return type int indicates that the method will return an integer.
19.Can a method return an array in Java? If so, how?
Yes, a method in Java can return an array. The method declaration includes the array type as the return type. The method will return the array to the caller.
Example:
public int[] getArray() {
int[] numbers = {1, 2, 3, 4};
return numbers;
}
In this example, the getArray() method returns an array of integers. The return type int[] indicates an array of integers.
20.How do you handle exceptions inside a method in Java using try catch blocks?
In Java, you can handle exceptions using try catch blocks in a method. Code that might throw an exception is placed in the try block and the exception is caught and handled in the catch block. Optionally, you can use a finally block to execute code regardless of whether an exception occurs.
Example:
public void readFile() {
try {
// Code that might throw an exception
FileReader fr = new FileReader("file.txt");
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} finally {
System.out.println("This block always executes.");
}
}
22.What is method chaining in Java and how is it implemented?
Java is the programming language that involves multiple methods calls over the same object in one line. Every method returns the object it is working with (or any other object). So the following method call may be called after the current method call on that object. The method chaining pattern is applied with builder patterns mostly.
Example
public class Car {
public Car start() {
System.out.println("Car started");
public Car return this; // Returns the current object
}
public Car drive() {
System.out.println("Car is driving");
return this;
}
}
Method chaining enables you to write:
Car car = new Car();
car.start().drive();
23. Which are default methods in interfaces in Java and have a relation with methods in the Java language?
Default Methods in Java allow methods with their body to define within an interface. They come into existence starting from Java 8 to backward compatibility with all previous versions as well. Such a method, declared using default keyword does have a method body.
As such, methods can have implementations.
Example :
interface Vehicle {
default void start( ) {
System.out.println("Vehicle starting.");
}
Unlike abstract methods, default methods can have a method body and can be inherited by implementing classes.
24. How do you pass multiple values to a method using an array or collection in Java?
To pass multiple values to a method, you can use an array or collection (like List, Set, etc.). Arrays are useful when the number of values is fixed while collections are better for dynamic sizes.
Example with an array:
public void displayNumbers(int[] numbers) {
for (int number : numbers) {
System.out.println(number);
}
}
Example with a collection:
public void displayNames(List<String> names) {
for (String name : names) {
System.out.println(name);
}
}
25.How does Java handle method visibility and access modifiers (e.g., public, private, protected)?
Java uses access modifiers to control the visibility of methods:
•public: The method is accessible from any class.
•private: The method is accessible only within the class it is defined.
•protected: The access of the method is available in the same package or by the subclasses.
•default (no modifier): The
access of the method is available in the same package.
Example:
public void publicMethod()
{
/* Accessible anywhere */
}
private void privateMethod()
{
/* Accessible only within the class */
}
protected void protectedMethod()
{
/* Accessible within the package or subclasses */
}
Previous Topic==> Java Strings FAQ. || Next Topics==> Basic Java OOPS Interview Questions
Other Topic==>
Banking Account Management Case Study in SQL
Top SQL Interview Questions
Employee Salary Management SQL FAQ!. C FAQ
Top 25 PL/SQL Interview Questions
Joins With Group by Having
Equi Join
Joins with Subqueries
Self Join
Outer Join