0% found this document useful (0 votes)
26 views

Java Question Bank

Java important... question

Uploaded by

chintucharan438
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views

Java Question Bank

Java important... question

Uploaded by

chintucharan438
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

What is the result of the following ternary operation?

int result =( (5 > 3) ? 10 : 20)

Write the syntax for Scanner Class with example.

Define type casting.

List the purpose of the final keyword for variables in Java.

What is encapsulation in Java ?

Compare next() and nextLine() in Java’s Scanner class.

List out the various types of operators in Java.

Differentiate between a default constructor and a parameterized constructor.

What are the types of nested classes in Java?

Compare method and constructor in Java .

a) Differentiate between the ternary operator and a traditional if-else statement.

b)List out the basic principles of Object-Oriented Programming (OOP) in Java.

Illustrate the concept behind constructor overloading in Java with an example code in
detail.

Develop a Java class that uses multiple inner classes to simulate a banking system
where each inner class represents different types of accounts (e.g., savings, checking)
and has specific operations.

Build a class Book that has attributes title, author, and price. Demonstrate a method
applyDiscount(double percentage) that reduces the price of the book by the given
percentage. Create an object of Book and apply the discount.

Demonstrate how a constructor initializes object attributes. Create a class Employee


with attributes name and salary. Create parameterized constructor to initialize these
attributes and create multiple Employee objects to display their details.

What is the output of the following program?


public class Op
{
public static void main(String[] args)
{
int x = 10; int y = 20;
int z = x + y * 2 - x / y;
System.out.println("Result: " + z);
System.out.println("Is x greater than y? " + (x > y));
}
}

List out the various access modifiers in java.

Explain about various concepts in the OOP (Java).

Develop a Java program to determine the grade of a student based on marks using a
switch statement.

Build a class Employee with attributes name and salary.

Write a constructor that uses this keyword to differentiate between instance variables
and constructor parameters

Demonstrate how to control access to private members using methods in the same class
with example.

Develop a class Person with attributes name and age, and write a method displayInfo() to
print the details of the person. Instantiate two objects of this class and call the
displayInfo() method.

OOP Concepts in Java - Questions and Answers


What is a class in Java?
A class in Java is a blueprint for creating objects. It defines properties (attributes) and
behaviors (methods) that the objects of the class will have.
Example:

```java
class Car {
String model;
int year;

void drive() {
System.out.println("The car is driving");
}
}
```

What is an object in Java?


An object is an instance of a class. It is a real-world entity with attributes and behaviors defined
by its class.
Example:

```java
Car car1 = new Car(); // car1 is an object of the Car class
```
What is inheritance in Java, and what are its types?
Inheritance is the process by which one class (child class) acquires the properties and
behaviors of another class (parent class). This allows code reuse and supports hierarchical
relationships between classes.

Types of Inheritance in Java:


- Single Inheritance: One class inherits from another.
- Multilevel Inheritance: A class inherits from a class, which itself inherits from another class.
- Hierarchical Inheritance: Multiple classes inherit from a single parent class.

Java does not support multiple inheritance (a class cannot inherit from more than one class) to
avoid ambiguity. However, it supports multiple inheritance through interfaces.

What is method overriding in Java?


Method overriding occurs when a subclass provides its own implementation of a method that
is already defined in its superclass. The method in the subclass must have the same name,
return type, and parameters as in the superclass.
Example:

```java
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}
```

What is method overloading in Java?


Method overloading is a feature in Java where multiple methods can have the same name but
differ in parameters (type, number, or both). It allows methods to perform similar tasks but with
different inputs.
Example:

```java
class Calculator {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}
```

What is the difference between method overloading and method overriding?


**Method Overloading**:
- Methods have the same name but differ in parameters.
- It occurs within the same class.
- Compile-time polymorphism.

**Method Overriding**:
- Methods have the same name, same return type, and same parameters but different
implementations in parent and child classes.
- It occurs between a superclass and a subclass.
- Runtime polymorphism.

What is encapsulation in Java?


Encapsulation is the process of bundling data (variables) and methods that operate on the data
into a single unit, typically a class. It helps protect data by restricting access to certain
components using access modifiers like `private`.
Example:

```java
class Person {
private String name; // private field

public String getName() {


return name; // Public getter
}

public void setName(String name) {


this.name = name; // Public setter
}
}
```

What is abstraction in Java, and how is it achieved?


Abstraction is the concept of hiding complex implementation details and showing only the
necessary parts of the object. In Java, abstraction is achieved using abstract classes and
interfaces.

**Abstract Class**:
- A class that cannot be instantiated and may contain abstract methods (methods without a
body) as well as concrete methods.

**Interface**:
- A reference type in Java, similar to a class, that can contain only abstract methods (before
Java 8) or default/static methods (from Java 8 onwards). A class can implement multiple
interfaces.

Example of an Abstract Class:


```java
abstract class Vehicle {
abstract void start(); // Abstract method
}

class Car extends Vehicle {


@Override
void start() {
System.out.println("Car is starting");
}
}
```

Example of an Interface:
```java
interface Animal {
void sound();
}

class Cat implements Animal {


@Override
public void sound() {
System.out.println("Cat meows");
}
}
```

What is a constructor in Java?


A constructor is a special method that is called when an object is instantiated. It is used to
initialize the object's state. In Java, a constructor has the same name as the class and no
return type.
Example:

```java
class Car {
String model;

// Constructor
Car(String model) {
this.model = model;
}
}

Car car = new Car("Toyota");


```

What is the difference between a constructor and a method in Java?


**Constructor**:
- Used to initialize an object.
- Does not have a return type.
- Called automatically when an object is created.
- The name is the same as the class name.
**Method**:
- Used to perform an action or operation on an object.
- Has a return type (or can be void).
- Called explicitly using an object or class name.
- The name can be anything.

What is polymorphism in Java?


Polymorphism is the ability of an object to take many forms. In Java, polymorphism allows a
single method to behave differently depending on the object calling it. Polymorphism can be
achieved through method overloading (compile-time) and method overriding (runtime).

**Compile-time Polymorphism** (Method Overloading):


```java
class Calculator {
int add(int a, int b) {
return a + b;
}

int add(int a, int b, int c) {


return a + b + c;
}
}
```

**Runtime Polymorphism** (Method Overriding):


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

class Dog extends Animal {


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

Animal obj = new Dog(); // Runtime polymorphism


obj.sound(); // Output: Dog barks
```

Can we overload the main() method in Java?


Yes, we can overload the `main()` method in Java. However, the JVM will only call the
`main(String[] args)` method to start the execution of the program. Other overloaded `main()`
methods can be called explicitly like any other method.

Example:
```java
public class MainOverload {
public static void main(String[] args) {
System.out.println("Main with String[]");
main(5); // Calling overloaded main method
}

public static void main(int a) {


System.out.println("Overloaded main with int: " + a);
}
}
```

What is the `Scanner` class in Java?


The `Scanner` class is part of the `java.util` package and is used to get user input. It reads
various types of input, including strings, numbers, and primitive data types like `int`, `double`,
`float`, etc.

Example of importing and using `Scanner`:


```java
import java.util.Scanner;

public class Example {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name);
}
}
```

How do you create a `Scanner` object in Java?


To create a `Scanner` object, you need to import the `java.util.Scanner` package and then
instantiate the `Scanner` object.

Example:
```java
Scanner sc = new Scanner(System.in);
```
What are some common methods of the `Scanner` class?
- **nextInt()**: Reads an `int` value.
- **nextDouble()**: Reads a `double` value.
- **nextLine()**: Reads a `String` until the end of the line.
- **next()**: Reads a single word (until a space).
- **hasNext()**: Returns true if there's another token.
- **hasNextInt()**: Returns true if the next token is an integer.

Example:
```java
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
int num = sc.nextInt();

System.out.println("Enter a double: ");


double d = sc.nextDouble();

sc.nextLine(); // Consume the newline left by nextDouble

System.out.println("Enter a string: ");


String str = sc.nextLine();
```

How do you read a string input using `Scanner`?


- To read a full line of input, use `nextLine()`:
```java
Scanner sc = new Scanner(System.in);
System.out.println("Enter a sentence: ");
String sentence = sc.nextLine();
```

- To read a single word, use `next()`:


```java
Scanner sc = new Scanner(System.in);
System.out.println("Enter a word: ");
String word = sc.next();
```

How do you check if the input is of a specific type (e.g., integer) using `Scanner`?
You can use the `hasNextInt()`, `hasNextDouble()`, etc., to check if the next input is of the
expected type.

Example:
```java
Scanner sc = new Scanner(System.in);

System.out.println("Enter an integer: ");


if (sc.hasNextInt()) {
int num = sc.nextInt();
System.out.println("You entered: " + num);
} else {
System.out.println("That's not an integer!");
}
```

What is the purpose of `sc.nextLine()` after reading numeric input?


When reading numeric input (e.g., `nextInt()` or `nextDouble()`), a newline character is left in the
input buffer. Using `sc.nextLine()` clears that newline character, ensuring it doesn't interfere with
subsequent `nextLine()` calls.

Example:
```java
Scanner sc = new Scanner(System.in);
System.out.println("Enter an integer: ");
int num = sc.nextInt();

// Consume the newline character left by nextInt()


sc.nextLine();

System.out.println("Enter your name: ");


String name = sc.nextLine();
```

What happens if the user enters an invalid input for a number?


If the user enters a non-numeric value when a numeric input is expected (e.g., `nextInt()`), the
`InputMismatchException` will be thrown.

Example:
```java
Scanner sc = new Scanner(System.in);
try {
System.out.println("Enter an integer: ");
int num = sc.nextInt();
System.out.println("You entered: " + num);
} catch (InputMismatchException e) {
System.out.println("Invalid input, please enter an integer.");
}
```

Can you use the `Scanner` class to read input from a file?
Yes, you can use the `Scanner` class to read input from a file by passing a `File` object to the
`Scanner` constructor.

Example:
```java
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;

public class ReadFile {


public static void main(String[] args) {
try {
File file = new File("example.txt");
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
String line = sc.nextLine();
System.out.println(line);
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
}
}
}
```

What is the difference between `next()` and `nextLine()`?


**next()**: Reads a single word (delimited by spaces) and moves the scanner to the next token.

**nextLine()**: Reads the entire line, including spaces, and moves the scanner to the next line.

Example:
```java
Scanner sc = new Scanner(System.in);

System.out.println("Enter a word: ");


String word = sc.next();

System.out.println("Enter a sentence: ");


String sentence = sc.nextLine();
```

How do you close a `Scanner` object and why is it important?


You should close the `Scanner` object using `sc.close()` to release the resources associated
with it, especially if you are reading from files or other streams. Leaving the `Scanner` open can
cause resource leaks.

Example:
```java
Scanner sc = new Scanner(System.in);
// Use scanner...
sc.close(); // Close the scanner when done
.

You might also like