Ibm Java Inter

Download as pdf or txt
Download as pdf or txt
You are on page 1of 16

ItsRunTym

JAVA Developer Fresher


IBM interview questions/answers

1. What is Exception Handling? Write a Program

Exception handling in Java is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc. ,
allowing the normal flow of the application to be maintained. It uses try,
catch, finally, and throw keywords.

Major reasons why an exception Occurs

• Invalid user input


• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file

public class ExceptionHandlingExample {


public static void main(String[] args) {
try {
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException:
Division by Zero.");
} finally {
System.out.println("This block is always
executed.");
}
}
}

Finally- Always executed whether an exception is


handled or not, providing a way to clean up
resources.
2. How will you make threads synchronize?

In Java, synchronization is used to control the access of multiple threads to


shared resources. The synchronized keyword is used to synchronize
methods or blocks.

class Counter {
private int count = 0;

public synchronized void increment() {


count++;
}

public int getCount() {


return count;
}
}

public class SynchronizationExample {


public static void main(String[] args) throws
InterruptedException {
Counter counter = new Counter();

Thread t1 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

Thread t2 = new Thread(() -> {


for (int i = 0; i < 1000; i++) {
counter.increment();
}
});

t1.start();
t2.start();

t1.join();
t2.join();

System.out.println("Count: " +
counter.getCount());
}
}

3. Types of Constructors in Java, Which Constructor Compiler


Automatically Make

There are three types of constructors in Java:

• Default Constructor: A no-argument constructor automatically created by


the compiler if no constructor is defined.
• No-argument Constructor: Explicitly defined by the user with no
parameters.
• Parameterized Constructor: A constructor that takes arguments.

The compiler automatically provides a default constructor if no other


constructors are defined.

Example:

public class ConstructorExample {


private int value;

// No-argument constructor
public ConstructorExample() {
this.value = 0;
}

// Parameterized constructor
public ConstructorExample(int value) {
this.value = value;
}

public int getValue() {


return value;
}

public static void main(String[] args) {


ConstructorExample obj1 = new
ConstructorExample();
ConstructorExample obj2 = new
ConstructorExample(10);
System.out.println("Default Constructor: " +
obj1.getValue()); // Output: 0
System.out.println("Parameterized
Constructor: " + obj2.getValue()); // Output: 10
}
}

4. What is Pass by Value and Pass by Reference in Java

Java is strictly "pass by value".

• Pass by Value: The method receives a copy of the argument passed.


Changes to the parameter do not affect the argument.
• Pass by Reference: The method receives a reference to the argument
passed, meaning changes to the parameter affect the argument.

In Java, when you pass an object, you pass the reference to that object by value,
meaning the reference itself is copied. Hence, changes to the object affect the
original object.

Example:

public class PassByValueExample {


public static void main(String[] args) {
int x = 5;
modifyValue(x);
System.out.println("After modifyValue: " +
x); // Output: 5

MyObject obj = new MyObject();


obj.value = 5;
modifyObject(obj);
System.out.println("After modifyObject: " +
obj.value); // Output: 10
}

public static void modifyValue(int a) {


a = 10;
}

public static void modifyObject(MyObject o) {


o.value = 10;
}
}

class MyObject {
int value;
}

➔ if we pass array, it will be pass by value or pass by reference?

In Java, when you pass an array to a method, it is passed by value, but this can
be a bit misleading due to how references work. Specifically, the reference to
the array is passed by value, meaning the method gets a copy of the reference.
This means changes to the array elements inside the method will affect the
original array, but changing the reference itself will not affect the original
reference.

Let's illustrate this with an example:

Example to Demonstrate Array Passing

public class PassArrayExample {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};

// Print the original array


System.out.println("Original array:");
printArray(arr);

// Modify the array


modifyArray(arr);

// Print the modified array


System.out.println("Modified array:");
printArray(arr);

// Change the array reference


changeArrayReference(arr);

// Print the array after trying to change its


reference
System.out.println("Array after attempting to
change reference:");
printArray(arr);
}

// Method to print the array


public static void printArray(int[] arr) {
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
}

// Method to modify array elements


public static void modifyArray(int[] arr) {
for (int i = 0; i < arr.length; i++) {
arr[i] = arr[i] * 2; // Modify array
elements
}
}

// Method to change array reference


public static void changeArrayReference(int[]
arr) {
arr = new int[]{10, 20, 30, 40, 50}; //
Attempt to change reference
System.out.println("Inside
changeArrayReference method:");
printArray(arr);
}
}

Output:

Original array:
1 2 3 4 5
Modified array:
2 4 6 8 10
Inside changeArrayReference method:
10 20 30 40 50
Array after attempting to change reference:
2 4 6 8 10

Explanation:

1. Original array: We print the original array [1, 2, 3, 4, 5].


2. modifyArray Method: This method doubles each element in the array.
Since the array reference is passed by value (the reference itself is
copied), the modifications to the array elements affect the original array.
3. changeArrayReference Method: This method attempts to change the
reference of the array to a new array [10, 20, 30, 40, 50].
However, this change is local to the method because the reference itself is
passed by value. The original reference in the main method still points to
the modified array [2, 4, 6, 8, 10].

Thus, when passing an array to a method in Java:

• The reference to the array is passed by value.


• Changes to the array elements affect the original array.
• Changing the reference itself inside the method does not affect the
original reference.

5. Output of this:

int a = 1;
System.out.println((a++) * (++a)); // Output will be
3

1. a++: (Postincrement) This returns the current value of a (which is 1), and
then a is incremented to 2.
2. ++a: (Preincrement) This increments a to 3 and then returns the new
value of a (which is 3).

So the expression (a++) * (++a) becomes 1 * 3, which results in 3.

public class ExpressionEvaluation {


public static void main(String[] args) {
int a = 1;
System.out.println((a++) * (++a)); // Output
will be 3
// Explanation: a++ returns 1 (a becomes 2),
++a increments to 3, so 1 * 3 = 3.
}
}

6. What is Abstract Function in Java?

Abstract functions (or abstract methods) in Java are methods that are declared
without an implementation. These methods are defined in abstract classes,
which cannot be instantiated on their own. Instead, subclasses of the abstract
class must provide implementations for all abstract methods.
The primary use of abstract functions is to enforce a contract for subclasses.
They ensure that any subclass that extends the abstract class provides
implementations for the specified abstract methods, thus maintaining a
consistent interface.

Example Use of Abstract Function

Let's consider an example involving an abstract class Animal and its


subclasses Dog and Cat.

Abstract Class and Abstract Method Example

abstract class Animal {


// Abstract method (does not have a body)
abstract void makeSound();

// Regular method
void sleep() {
System.out.println("Sleeping...");
}
}

class Dog extends Animal {


// Providing implementation for abstract method
void makeSound() {
System.out.println("Bark");
}
}

class Cat extends Animal {


// Providing implementation for abstract method
void makeSound() {
System.out.println("Meow");
}
}

public class AbstractFunctionExample {


public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.makeSound(); // Outputs: Bark


myDog.sleep(); // Outputs: Sleeping...
myCat.makeSound(); // Outputs: Meow
myCat.sleep(); // Outputs: Sleeping...
}
}

7. What is Polymorphism?

Polymorphism is a fundamental concept in object-oriented programming (OOP)


that allows objects of different classes to be treated as objects of a common
superclass. It enables one interface to be used for a general class of actions,
allowing the same method to behave differently based on the object that invokes
it. This facilitates code reusability and flexibility.

Benefits of Polymorphism:

• Code Reusability: Promotes the reuse of code and reduces redundancy.


• Flexibility and Scalability: Makes it easier to extend and maintain code.
New functionality can be added with minimal changes to existing code.
• Decoupling: Reduces the dependency between the client code and the
actual implementation, making the system more modular and easier to
manage.

8. What is Compile-time & Runtime Polymorphism?

1. Compile-time Polymorphism (Static Binding): This is achieved


through method overloading, where multiple methods have the same
name but different parameters. The method to be invoked is determined at
compile time.
2. Runtime Polymorphism (Dynamic Binding): This is achieved through
method overriding, where a subclass provides a specific implementation
of a method that is already defined in its superclass. The method to be
invoked is determined at runtime.

Example of Compile-time Polymorphism

Method Overloading: Define multiple methods with the same name but
different parameters.

class MathOperation {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add three integers
int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two double values


double add(double a, double b) {
return a + b;
}
}

public class CompileTimePolymorphism {


public static void main(String[] args) {
MathOperation math = new MathOperation();

System.out.println("Sum of 10 and 20: " +


math.add(10, 20)); // Calls add(int, int)
System.out.println("Sum of 10, 20, and 30: "
+ math.add(10, 20, 30)); // Calls add(int, int, int)
System.out.println("Sum of 10.5 and 20.5: " +
math.add(10.5, 20.5)); // Calls add(double, double)
}
}

Example of Runtime Polymorphism

Method Overriding: Subclass provides a specific implementation of a method


defined in its superclass.

class Animal {
void sound() {
System.out.println("Animal sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Bark");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("Meow");
}
}

public class RuntimePolymorphism {


public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.sound(); // Outputs: Bark


myCat.sound(); // Outputs: Meow
}
}

Explanation of the Example:

1. Compile-time Polymorphism:
o The add method is overloaded with different parameter lists.
o The compiler determines which add method to call based on the
method signature and the arguments provided.
2. Runtime Polymorphism:
o The sound method in the Animal class is overridden by the Dog
and Cat classes.
o The actual method to be called is determined at runtime based on
the object's runtime type (Dog or Cat).

9. What are Interfaces? How are they useful in Java?

In Java, an interface is a reference type, similar to a class, that can contain only
constants, method signatures, default methods, static methods, and nested types.
Interfaces cannot contain instance fields or constructors. Interfaces provide a
way to achieve abstraction and multiple inheritance in Java.

Key Characteristics of Interfaces:

• Abstract Methods: All methods in an interface are abstract (do not have
a body) by default unless they are static or default methods.
• Default Methods: Interfaces can have default methods, which have a
default implementation.
• Static Methods: Interfaces can have static methods, which can be called
independently of any instance.
• Constants: All variables in an interface are implicitly public,
static, and final.
• Multiple Inheritance: A class can implement multiple interfaces,
overcoming the limitation of single inheritance in Java.

How Are Interfaces Useful in Java?

1. Achieving Abstraction: Interfaces allow you to define methods that must


be implemented by any class that implements the interface, thus
providing a way to enforce certain functionalities without specifying how
they should be implemented.
2. Multiple Inheritance: Java does not support multiple inheritance of
classes, but a class can implement multiple interfaces. This allows a class
to inherit the behavior from multiple sources.
3. Loose Coupling: By using interfaces, you can decouple the definition of
methods from their implementations. This makes the code more modular
and easier to manage, as you can change the implementation without
affecting the code that uses the interface.
4. Polymorphism: Interfaces enable polymorphic behavior. A variable of
an interface type can reference any object that implements the interface,
allowing for flexible and interchangeable use of objects.

10. Write a code for interfaces?

// Define an interface
interface Animal {
void sound(); // Abstract method
default void sleep() { // Default method
System.out.println("Sleeping...");
}
}

// Implementing the interface in a class


class Dog implements Animal {
@Override
public void sound() {
System.out.println("Bark");
}
}

// Implementing the interface in another class


class Cat implements Animal {
@Override
public void sound() {
System.out.println("Meow");
}
}

public class InterfaceExample {


public static void main(String[] args) {
Animal myDog = new Dog();
Animal myCat = new Cat();

myDog.sound(); // Outputs: Bark


myDog.sleep(); // Outputs: Sleeping...

myCat.sound(); // Outputs: Meow


myCat.sleep(); // Outputs: Sleeping...
}
}

Explanation of the Example:

1. Interface Definition:
o The Animal interface defines an abstract method sound() and a
default method sleep().
2. Implementation of Interface:
o The Dog and Cat classes implement the Animal interface by
providing their own implementations of the sound() method.
3. Usage:
o In the main method, instances of Dog and Cat are created and
assigned to variables of type Animal.
o The sound() method is called on these instances, demonstrating
polymorphic behavior.
o The sleep() method (a default method in the interface) is also
called on these instances.

11. What is Lambda Expression?

Lambda expressions in Java are a way to represent anonymous functions


(function literals) concisely. They were introduced in Java 8 and provide a
means to implement the abstract method of a functional interface directly inline,
without needing to define a separate class or even an anonymous class.

Functional Interface
An interface which has only one abstract method is called functional interface.
Java provides an anotation @FunctionalInterface, which is used to declare an
interface as functional interface.

Why use Lambda Expression


1. To provide the implementation of Functional interface.
2. Less coding.

Java Lambda Expression Syntax


(argument-list) -> {body}

@FunctionalInterface //It is optional

interface Drawable{

public void draw();

public class LambdaExpressionExample2 {

public static void main(String[] args) {

int width=10;

//with lambda

Drawable d2=()->{

System.out.println("Drawing "+width);

};

d2.draw();

12. Write a program for palindrome?


public boolean isPalindrome(String s) {

s= s.toLowerCase(); //ask if it should be


case sensitive or not

int n = s.length();

for(int i=0;i<n/2;i++){

if(s.charAt(i) != s.charAt(n-1-i)){

return false;

return true;

13. Write a program to find the number of occurrences of each character in


a given string?

import java.util.HashMap;
import java.util.Map;

public class CharacterCount {


public static void main(String[] args) {
String str = "hello world";

// Create a HashMap to store character counts


Map<Character, Integer> charCountMap = new
HashMap<>();

// Convert the string to char array


char[] charArray = str.toCharArray();
// Iterate through each character in the
array
for (char c : charArray) {
// If the character is already present in
the map, increment its count
if (charCountMap.containsKey(c)) {
charCountMap.put(c,
charCountMap.get(c) + 1);
} else {
// If the character is encountered
for the first time, add it to the map with count 1
charCountMap.put(c, 1);
}
}

// Print the character counts


for (Map.Entry<Character, Integer> entry :
charCountMap.entrySet()) {
System.out.println(entry.getKey() + ": "
+ entry.getValue());
}
}
}