0% found this document useful (0 votes)
52 views9 pages

Java Questions

Uploaded by

Warren Smith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views9 pages

Java Questions

Uploaded by

Warren Smith
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

JAVA QUESTIONS

1. Explain the concept of object oriented programming in java and briefly


describe its four main principles
2. Write a java programme that prompt the user to write their name and
out put the greeting message
3. What is the difference between JDK, JRE and JVM? Explain the role of
each in the execution of java programs
4. Describe what a constructor is in java. How does it differ from a
method?
5. Explain the use of the final keyword in java. Provide examples for
A) A final variable
B) A final method
C) A final class
6. Write a java program that uses a for loop to print the numbers from 1
to 100. Modify the program to skip the numbers that are divisible by
both 3 and 4
7. Explain the difference between ArrayList and LinkedList. When would
you prefer to use one over the other?
8. Write a java program that takes a list of integers from the user and sorts
it using the bubble sort algorithm
9. What is the significance of the break and continue statements in loops?
Provide examples of each.
10.Write a java program that uses a switch statement to implement a basic
calculator that performs addition, subtraction, multiplication or division
based on user input.

ANSWERS
Here are the answers to your Java questions:

### 1. Object-Oriented Programming (OOP) in Java


Object-oriented programming is a programming paradigm that structures a program around objects
rather than functions or logic. OOP in Java revolves around the concept of **classes** and **objects**.
The four main principles are:

- **Encapsulation**: Wrapping data (variables) and methods (functions) into a single unit, known as a
class, and restricting direct access to some of the object’s components. Example: Using private variables
and public getter/setter methods.

- **Inheritance**: Mechanism by which one class acquires properties (fields and methods) of another.
This allows for code reusability. Example: `class Dog extends Animal`.

- **Polymorphism**: The ability to perform a single action in different ways. There are two types:

- **Compile-time polymorphism**: Method overloading.

- **Run-time polymorphism**: Method overriding.

- **Abstraction**: Hiding the implementation details and showing only the functionality. Achieved using
abstract classes and interfaces.

### 2. Java Program to Greet User by Name

```java

import java.util.Scanner;

public class Greeting {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

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

String name = scanner.nextLine();

System.out.println("Hello, " + name + "! Welcome.");

scanner.close();

}
```

### 3. Difference Between JDK, JRE, and JVM

- **JDK (Java Development Kit)**: A software development environment used for developing Java
applications. It includes JRE, development tools like a compiler (`javac`), and libraries for development.

- **JRE (Java Runtime Environment)**: It provides libraries and other components to run applications
written in Java. It includes the JVM but does not include development tools like the compiler.

- **JVM (Java Virtual Machine)**: The engine that runs Java bytecode. It converts the compiled Java
code into machine code to be executed by the machine. JVM is platform-dependent but Java is
platform-independent because of JVM.

**Execution of Java Programs**:

1. Java code is written and compiled into bytecode (.class file) by JDK.

2. JRE, through the JVM, interprets and runs the bytecode.

### 4. Constructor in Java

A **constructor** is a special method used to initialize objects. It is called when an object of a class is
created. A constructor differs from a method in these ways:

- A constructor has the same name as the class and no return type (not even `void`).

- It is invoked automatically when an object is created.

Example:

```java

class Dog {

String name;

Dog(String name) {

this.name = name;

}
}

```

### 5. `final` Keyword in Java

- **Final Variable**: A variable that cannot be changed after initialization.

```java

final int MAX_SPEED = 120;

```

- **Final Method**: A method that cannot be overridden by subclasses.

```java

public final void display() {

System.out.println("Final method cannot be overridden");

```

- **Final Class**: A class that cannot be extended (inherited).

```java

public final class Calculator {

// Code here

```

### 6. Java Program to Print Numbers 1 to 100, Skipping Numbers Divisible by Both 3 and 4

```java

public class PrintNumbers {

public static void main(String[] args) {

for (int i = 1; i <= 100; i++) {

if (i % 3 == 0 && i % 4 == 0) {
continue; // Skip numbers divisible by both 3 and 4

System.out.println(i);

```

### 7. Difference Between `ArrayList` and `LinkedList`

- **ArrayList**: Internally backed by an array. It offers fast random access but slow insertions and
deletions (especially in the middle of the list) because elements need to be shifted.

- **LinkedList**: Implemented as a doubly linked list. It provides faster insertions and deletions but
slower random access (because each element must be traversed sequentially).

**Use Cases**:

- Use `ArrayList` when you need frequent access to elements via index.

- Use `LinkedList` when you need frequent insertions and deletions.

### 8. Java Program for Bubble Sort

```java

import java.util.Scanner;

public class BubbleSort {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.println("Enter the number of elements:");

int n = scanner.nextInt();

int[] arr = new int[n];


System.out.println("Enter the elements:");

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

arr[i] = scanner.nextInt();

// Bubble Sort

for (int i = 0; i < n - 1; i++) {

for (int j = 0; j < n - 1 - i; j++) {

if (arr[j] > arr[j + 1]) {

int temp = arr[j];

arr[j] = arr[j + 1];

arr[j + 1] = temp;

System.out.println("Sorted list:");

for (int num : arr) {

System.out.print(num + " ");

scanner.close();

```

### 9. `break` and `continue` Statements in Loops

- **break**: Terminates the loop entirely.

- **continue**: Skips the current iteration and moves to the next iteration.
Example:

```java

public class BreakContinueExample {

public static void main(String[] args) {

for (int i = 1; i <= 10; i++) {

if (i == 5) {

break; // Terminates the loop when i equals 5

System.out.println(i);

for (int i = 1; i <= 10; i++) {

if (i == 5) {

continue; // Skips the iteration when i equals 5

System.out.println(i);

```

### 10. Java Program for a Basic Calculator Using `switch`

```java

import java.util.Scanner;

public class BasicCalculator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);


System.out.println("Enter first number:");

double num1 = scanner.nextDouble();

System.out.println("Enter second number:");

double num2 = scanner.nextDouble();

System.out.println("Choose operation: +, -, *, /");

char operator = scanner.next().charAt(0);

double result;

switch (operator) {

case '+':

result = num1 + num2;

break;

case '-':

result = num1 - num2;

break;

case '*':

result = num1 * num2;

break;

case '/':

if (num2 != 0) {

result = num1 / num2;

} else {

System.out.println("Division by zero is not allowed.");

return;

}
break;

default:

System.out.println("Invalid operator.");

return;

System.out.println("The result is: " + result);

scanner.close();

```

Let me know if you need further explanations or modifications!

You might also like