[go: up one dir, main page]

0% found this document useful (0 votes)
10 views43 pages

JAVA QUESTION ANSWERS

Uploaded by

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

JAVA QUESTION ANSWERS

Uploaded by

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

JAVA QUESTION’S ANSWERS

2 MARKS
Q1 What is Object Oriented programming?
Ans.
Object-Oriented Programming or OOPs refers to languages that use objects in
programming. Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is
to bind together the data and the functions that operate on them so that no other
part of the code can access this data except that function.

Q2 List the Java programming language Features.


Ans.
A List of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform Independent
5. Secured
6. Robust
7. Architecture Neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Q3 What is Type Casting in Java.


Ans.
Typecasting is the process of converting the value of a single data type (such as an
integer [int], float, or double) into another data type. This conversion is done either
automatically or manually. The compiler performs the automatic conversion, and a
programmer does the manual conversion.

Q4 List the keywords in Java.


Ans.
1. abstract
2. boolean
3. break
4. byte
5. case
6. char
7. class
8. continue
9. default
10. do
11. double
12. else
13. float
14. for
15. if
16. import
17. int
18. long
19. new
20. package
21. private
22. public
23. return
24. static
25. short
26. protected
27. void
28. while
29. switch
30. extends

Q5 List the various syntax of creating array in java.


Ans.
In Java, there are a few ways to create an array based on the data type you are
working with:
1. Single-dimensional array:
- Syntax for creating an array of integers:
`int[] myIntArray = new int[5];`
- Syntax for creating an array of strings:
`String[] myStringArray = new String[3];’
2. Multi-dimensional array:
- Syntax for creating a 2D array of integers:
`int[][] my2DArray = new int[3][4];`
- Syntax for creating a 2D array of strings:
`String[][] myString2DArray = new String[2][2];`
3. Array initialization:
- Syntax for initializing an array of integers:
`int[] myIntArray = {1, 2, 3, 4, 5};`
- Syntax for initializing an array of strings:
`String[] myStringArray = {"apple", "banana", "orange"};`
Remember, in Java, arrays are zero-indexed, meaning the first element of an array is
at index 0.

Q6 Write java program to perform constructor overloading in java.


Ans.
public class ConstructorOverloading {
private int number;
public ConstructorOverloading() {
this.number = 0;
System.out.println("Default constructor called. Number is: " + number);
}
public ConstructorOverloading(int num) {
this.number = num;
System.out.println("Parameterized constructor called. Number is: " + number);
}
public static void main(String[] args) {
ConstructorOverloading obj1 = new ConstructorOverloading();
ConstructorOverloading obj2 = new ConstructorOverloading(5);
}
}

Q7 List any four built-in packages from Java.


Ans.
Some of the built-in packages in Java are:
1. `java.lang`: This package provides classes essential to the Java programming
language, such as Object, String, Math, and more.
2. `java.util`: This package contains the collection framework, legacy collection
classes, event model, date and time facilities, and more.
3. `java.io`: This package provides classes for input and output operations, such as
reading and writing data to files or other sources.
4. `java.awt`: This package contains classes for creating and managing graphical user
interfaces (GUI) components, like windows, buttons, and menus.

Q8 How to declared constant in java using ‘final’ keyword.


Ans.
In Java, you can declare a constant using the final keyword. The final keyword ensures
that the value of the variable cannot be changed once it is assigned. Here's how you
can do it:
public class Main {
public static void main(String[] args) {
final int MY_CONSTANT = 10;
System.out.println(MY_CONSTANT);
}
}

Q9 What is thread priority in Java.


Ans.
Thread priority is a feature that allows you to indicate the relative importance of a
thread compared to other threads. The Java Virtual Machine (JVM) uses thread
priority as a hint to determine the order in which threads are scheduled for execution.
Higher priority threads are more likely to be executed before lower priority threads if
they are ready to run.

Q10 Define term thread in java.


Ans.
In Java, a thread can be defined as a lightweight sub-process, a separate path of
execution within a program. Threads allow concurrent execution of tasks, enabling
different parts of a program to run independently and simultaneously. By utilizing
threads, Java programs can achieve multitasking and better utilize system resources
efficiently. Threads in Java are instances of the `Thread` class or objects that
implement the `Runnable` interface, providing a way to execute code concurrently.

Q11 Give the difference between C++ and Java.


Ans.

Comparison C++ Java


Index

Platform- C++ is platform-dependent. Java is platform-independent.


independent

Mainly used C++ is mainly used for system Java is mainly used for application
for programming. programming. It is widely used in Windows-
based, web-based, enterprise, and mobile
applications.

Design Goal C++ was designed for systems and Java was designed and created as an interpreter
applications programming. It was an for printing systems but later extended as a
extension of the C programming support network computing. It was designed to
language. be easy to use and accessible to a broader
audience.

Goto C++ supports the goto statement. Java doesn't support the goto statement.

Multiple C++ supports multiple inheritance. Java doesn't support multiple inheritance
inheritance through class. It can be achieved by
using interfaces in java.

Operator C++ supports operator overloading. Java doesn't support operator overloading.
Overloading
Pointers C++ supports pointers. You can write Java supports pointer internally. However, you
a pointer program in C++. can't write the pointer program in java. It means
java has restricted pointer support in java.

Q12 Write java program to check given year is leap year or not.
Ans.
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}
scanner.close();
}
}

Q13 List the data types in java.


Ans.
here is the list of data types in Java:
Primitive Data Types
1. byte
2. short
3. int
4. long
5. float
6. double
7. char
8. boolean
Reference Data Types
1. Classes
2. Interfaces
3. Arrays
4. Enums

Q14 Define the implicit & explicit type casting java.


Ans.
Implicit Type Casting
Converting a lower data type into a higher one is called widening type casting. It is
also known as implicit conversion or casting down. It is done automatically. It is safe
because there is no chance to lose data.
Explicit Type Casting
Converting a lower data type into a higher one is called widening type casting. It is
also known as implicit conversion or casting down. It is done automatically. It is safe
because there is no chance to lose data.

Q15 Define the array in java.


Ans.
Java array is an object which contains elements of a similar data type. Additionally,
The elements of an array are stored in a contiguous memory location. It is a data
structure where we store similar elements. We can store only a fixed set of elements
in a Java array.
Q16 Write java program to perform Method overloading in java.
Ans.
public class OverloadingExample {

// Method with one int parameter


public int add(int a) {
return a + 10;
}

// Method with two int parameters


public int add(int a, int b) {
return a + b;
}

// Method with two double parameters


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

public static void main(String[] args) {


OverloadingExample example = new OverloadingExample();

// Calling different overloaded methods


System.out.println("add(int a): " + example.add(5));
System.out.println("add(int a, int b): " + example.add(5, 10));
System.out.println("add(double a, double b): " + example.add(5.5, 10.5));
}
}
Q17 Define the term polymorphism in java.
Ans.
Polymorphism is one of the fundamental concepts of object-oriented programming. It
allows us to perform a single action in different ways. It is derived from the Greek
words "poly" and "morph" which means "many" and "forms" respectively.
In Java, polymorphism is achieved through method overriding and method
overloading.

Q18 What is the use of ‘this’ keyword in java.


Ans.
The this keyword refers to the current object in a method or constructor. The most
common use of the this keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed
by a method or constructor parameter).

Q19 List the states of thread life cycle.


Ans.
Here is the list of thread lifecycle states in Java:
1. NEW
2. RUNNABLE
3. BLOCKED
4. WAITING
5. TIMED_WAITING
6. TERMINATED

Q20 What is the meaning of process multitasking.


Ans.
Process multitasking, also known as process-level multitasking, refers to the ability of
an operating system to execute multiple processes (programs) concurrently. In this
context, a process is an independent program running in its own address space, with
its own memory and resources.

Q21 Write java program to find factorial of ‘4’ using for loop.
Ans.
public class FactorialExample {
public static void main(String[] args) {
int number = 4; // Number for which we need to find the factorial
int factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i; // factorial = factorial * i;
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
}

Q22 Give the relationship between JDK, JRE and JVM.


Ans.
• JDK (Java Development Kit): Includes tools for developing Java applications and
the JRE.
• JRE (Java Runtime Environment): Provides the libraries and JVM to run Java
applications.
• JVM (Java Virtual Machine): Executes Java bytecode and provides a runtime
environment.
JDK is for Java development, including JRE and development tools. JRE is for running
Java applications and includes the JVM. JVM is the virtual machine that executes Java
bytecode. Each plays a crucial role in the Java ecosystem.

Q23 What is Constructor in Java.


Ans.
A constructor in Java is a special type of method that is automatically called when an
instance (object) of a class is created. It is used to initialize the newly created object
and can accept parameters to set initial values for instance variables. Constructors
have the same name as the class and do not have a return type.

Q24 List the different types of Inheritance used in Java.


Ans.
Here are the different types of inheritance used in Java:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (Through Interfaces)
5. Hybrid Inheritance

Q25 How multiple inheritance possible in java using interface.


Ans.
In Java, multiple inheritance is not directly supported for classes, but it can be
achieved through interfaces. Here's how it works:
Interfaces:
• Java allows a class to implement multiple interfaces.
• An interface can declare methods and constants, but it cannot implement them.
• A class implementing multiple interfaces effectively inherits the abstract
methods and constants defined in those interfaces.

Q26 What is the use of ‘super’ keyword in java.


Ans.
The 'super' keyword in Java is used to refer to the immediate parent class object. It is
typically used to access the members of the superclass (parent class) when there is a
superclass-subclass relationship.
It can be used in several contexts:
1. Accessing Parent Class Members
2. Invoking Parent Class Constructor
3. Overriding Parent Class Methods

Q27 What are the different ways to create thread in Java.


Ans.
Here are the different ways to create a thread in Java:
1. Extending the “Thread” class
2. Implementing the “Runnable” interface
3. Using Lambda Expressions
4. Using Executor Framework

Q28 Define the term multi-threading in java.


Ans.
Multithreading in Java refers to the concurrent execution of two or more threads
within a single process. It allows a program to perform multiple tasks simultaneously
by dividing them into smaller threads of execution. Each thread operates
independently, sharing the same memory space, allowing for efficient resource
utilization and improved program responsiveness. Multithreading is a key feature of
Java that enables developers to write concurrent and efficient programs.
10 marks
Q1 Explain the various features about object oriented programming language.
Ans.
In Java, object-oriented programming (OOP) is facilitated by various features that
promote modularity, reusability, and organized code development. Here are some key
features:
Abstraction
The concept allows us to hide the implementation from the user but shows only
essential information to the user. Using the concept developer can easily make
changes and added over time.
Encapsulation
Encapsulation is a mechanism that allows us to bind data and functions of a class into
an entity. It protects data and functions from outside interference and misuse.
Therefore, it also provides security. A class is the best example of encapsulation.
Inheritance
The concept allows us to inherit or acquire the properties of an existing class (parent
class) into a newly created class (child class). It is known as inheritance. It provides
code reusability.
Polymorphism
The word polymorphism is derived from the two words i.e. ploy and morphs. Poly
means many and morphs means forms. It allows us to create methods with the same
name but different method signatures. It allows the developer to create clean,
sensible, readable, and resilient code.
Object
An object is a real-world entity that has attributes, behavior, and properties. It is
referred to as an instance of the class. It contains member functions, variables that
we have defined in the class. It occupies space in the memory. Different objects have
different states or attributes, and behaviors.
Class
A class is a blueprint or template of an object. It is a user-defined data type. Inside a
class, we define variables, constants, member functions, and other functionality. it
binds data and functions together in a single unit. It does not consume memory at run
time.

Q2 Write java program to display given number is positive or negative.[no taken from
user using Scanner class]
Ans.
import java.util.Scanner;

public class PositiveNegative {


public static void main(String[] args) {
// Create a Scanner object to read input from the user
Scanner scanner = new Scanner(System.in);

// Prompt the user to enter a number


System.out.print("Enter a number: ");

// Read the number entered by the user


int number = scanner.nextInt();

// Check if the number is positive, negative, or zero


if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}

// Close the scanner to prevent resource leak


scanner.close();
}
}

Q3 Explain Relational & Logical operator in java.


Ans.
1. Relational Operators:
o Relational operators are used to establish relationships between two
operands and evaluate to a boolean value (true or false).
o Common relational operators include:
▪ == (equal to): Returns true if the operands are equal.
▪ != (not equal to): Returns true if the operands are not equal.
▪ > (greater than): Returns true if the left operand is greater than the
right operand.
▪ < (less than): Returns true if the left operand is less than the right
operand.
▪ >= (greater than or equal to): Returns true if the left operand is
greater than or equal to the right operand.
▪ <= (less than or equal to): Returns true if the left operand is less
than or equal to the right operand.
2. Logical Operators:
o Logical operators are used to perform logical operations on boolean
operands and evaluate to a boolean value.
o Common logical operators include:
▪ && (logical AND): Returns true if both operands are true.
▪ || (logical OR): Returns true if at least one of the operands is true.
▪ ! (logical NOT): Returns true if the operand is false, and vice versa.

Relational and logical operators are fundamental in decision-making and flow control
constructs such as if, while, for, etc., in Java programming.

Q4 What are the various decision making construction in java.


Ans.
In Java, decision-making constructs allow you to control the flow of execution based
on certain conditions. Some of the common decision-making constructs include:
1. if Statement:
o The if statement executes a block of code if a specified condition is true.
o It may be followed by an optional else statement, which executes a block
of code if the condition is false.
o Example:
if (condition) {
// code block to be executed if the condition is true
} else {
// code block to be executed if the condition is false
}

2. if-else if-else Statement:


o The if-else if-else statement allows you to specify multiple conditions to
be tested sequentially.
o It executes the block of code associated with the first true condition
encountered.
o Example:
if (condition1) {
// code block to be executed if condition1 is true
} else if (condition2) {
// code block to be executed if condition2 is true
} else {
// code block to be executed if none of the conditions are true
}

3. switch Statement:
o The switch statement evaluates an expression and executes the code
block associated with the matched case.
o It provides an alternative to multiple if-else if statements when testing the
same variable.
o Example:
switch (expression) {
case value1:
// code block to be executed if expression matches value1
break;
case value2:
// code block to be executed if expression matches value2
break;
default:
// code block to be executed if expression doesn't match any case
}

4. Ternary Operator (Conditional Operator):


o The ternary operator ? : provides a compact way to write simple if-else
statements.
o It evaluates a boolean expression and returns one of two values based on
whether the condition is true or false.
o Example:
variable = (condition) ? expression1 : expression2;

These decision-making constructs enable you to write Java programs that can make
choices based on specific conditions, allowing for flexible and controlled execution
paths.

Q5 How to create object of Student class using new keyword and call default
constructor.
Ans.
To create an object of the Student class using the new keyword and call the default
constructor, follow these steps:
1. Define the Student class with a default constructor (a constructor with no
parameters).
2. Use the new keyword followed by the class name and parentheses to
instantiate the object.
3. Assign the newly created object to a reference variable of type Student.
4. Optionally, access the methods or fields of the Student class through the object
reference variable.
Here's an example:
// Define the Student class
class Student {
// Default constructor
public Student() {
System.out.println("Default constructor called");
}
}

public class Main {


public static void main(String[] args) {
// Create an object of the Student class using the new keyword
Student student = new Student();

// Now the default constructor of the Student class will be called


}
}
In this example, the Student class has a default constructor that prints a message
when called. In the Main class, we create an object of the Student class using the new
keyword, and the default constructor is automatically invoked.

Q6 Give the importance of ‘this’ keyword for changing the scope of the variables.
Ans.
The this keyword in Java is primarily used to refer to the current instance of the class.
While it's not directly used to change the scope of variables, it plays a crucial role in
disambiguating between instance variables and local variables with the same name,
thereby preventing shadowing and ensuring correct variable resolution.
Importance of this Keyword:
1. Disambiguation:
o In methods or constructors where local variables have the same name as
instance variables, using this allows you to differentiate between them.
o It helps resolve naming conflicts and ensures that the correct variable is
accessed or modified.
2. Clarity and Readability:
o Explicitly using this makes the code more readable by clearly indicating
that the variable being referenced belongs to the current object.
o It improves code comprehension and reduces ambiguity, especially in
large codebases or when collaborating with others.
3. Avoiding Shadowing:
o Without this, if a local variable shadows an instance variable, the instance
variable becomes inaccessible within that scope.
o By using this, you can access the instance variable even if it's shadowed
by a local variable, thus avoiding unintentional variable hiding.
4. Constructor Chaining:
o In constructors, this can be used to call another constructor in the same
class, facilitating constructor chaining.
o This allows for code reuse and helps in initializing objects with different
parameters while avoiding duplicate initialization logic.
5. Passing the Current Object:
o In certain scenarios, such as passing the current object as an argument to
another method or constructor, this is used to refer to the current
instance.
While the primary role of this is not to change the scope of variables, it plays a critical
role in maintaining clarity, avoiding variable shadowing, and ensuring correct variable
resolution in object-oriented Java programming.

Q7 What is single level inheritance? Explain with suitable example.


Ans.
Single-level inheritance, also known as simple inheritance, refers to the inheritance
relationship where a subclass (or derived class) inherits from only one superclass (or
base class). In other words, there's a single level of inheritance between classes.
Example of Single-level Inheritance:
// Superclass
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
// Subclass inheriting from Animal
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
public class Main {
public static void main(String[] args) {
// Create an object of the subclass Dog
Dog dog = new Dog();

// Call methods from both superclass and subclass


dog.eat(); // Output: Animal is eating
dog.bark(); // Output: Dog is barking
}
}
In this example:
• The Animal class serves as the superclass with a method eat().
• The Dog class is the subclass of Animal and inherits the eat() method.
• Additionally, the Dog class defines its own method bark().
• When we create an object of the Dog class, it can access both the inherited
method eat() from the superclass and its own method bark().
This demonstrates single-level inheritance, where Dog inherits from Animal, forming a
single level of hierarchy.

Q8 What is meant by interface? State its need and write syntax and features of
interface.
Ans.
An interface in Java is like a contract or a blueprint that defines a set of methods that
a class must implement. It establishes a way for classes to adhere to a specific set of
behaviors without specifying how those behaviors are implemented.

Need for Interfaces:


1. Achieving Abstraction: Interfaces allow you to achieve abstraction by defining a set
of methods without providing the implementation details. This helps in separating
what needs to be done from how it is done.

2. Achieving Multiple Inheritance: Java doesn't support multiple inheritance with


classes, but a class can implement multiple interfaces. This allows a class to inherit
behaviors from multiple sources through interfaces.
Syntax of Interface:

public interface MyInterface {


// Constant variables (static and final by default)
int MAX_VALUE = 100;

// Abstract methods (methods without a body)


void method1();
int method2(int x, int y);
}

Features of Interface:
1. Methods: Interfaces can have abstract methods that do not have a method body.
These methods must be implemented by the classes that implement the interface.

2. Constants: Interfaces can have constants, which are implicitly static and final. These
constants can be accessed using the interface name.

3. Default Methods: Starting from Java 8, interfaces can have default methods with a
default implementation. Classes implementing the interface can choose to override
these default methods.

4. Static Methods: Interfaces can also have static methods that are associated with
the interface itself and can be called using the interface name.

5. Multiple Inheritance: A class can implement multiple interfaces, allowing it to


inherit behaviors from multiple sources.

By using interfaces, you can define a contract that classes must adhere to, promoting
code reusability and flexibility in your Java programs. If you have any more questions
or need further clarification, feel free to ask!

Q9 Explain the different states in life cycle of Thread?


Ans.
In the life cycle of a thread in Java, there are several states that a thread can be in, as
it progresses from creation to completion or termination. These states are:
1. New: When a thread is created, it is in the new state. The Thread object has
been instantiated, but the start() method has not yet been called to begin
execution.
2. Runnable: After calling the start() method, the thread enters the runnable state.
In this state, the thread is eligible to be executed by the CPU, but it may or may
not actually be running at any given moment due to scheduling decisions made
by the JVM.
3. Blocked/Waiting: A thread can transition to a blocked or waiting state under
various conditions:
o Blocked: A thread is waiting for a monitor lock to enter a synchronized
block or method.
o Waiting: A thread is waiting indefinitely for another thread to perform a
specific action, such as calling notify() or notifyAll() on the same object.
4. Timed Waiting: Similar to the blocked or waiting state, but with a specified
timeout period. Threads can enter timed waiting states by invoking methods
like sleep(), join(), or wait() with a timeout parameter.
5. Terminated/Dead: A thread enters the terminated state when it completes
execution or when an uncaught exception occurs within its run() method. Once
terminated, a thread cannot be restarted.

Q10 What are the differences between Multithreading and Multitasking?


Ans.

S.NO Multitasking Multithreading

While in multithreading, many threads


In multitasking, users are allowed to
1. are created from a process through which
perform many tasks by CPU.
computer power is increased.

While in multithreading also, CPU


Multitasking involves often CPU
2. switching is often involved between the
switching between the tasks.
threads.

In multitasking, the processes share While in multithreading, processes are


3.
separate memory. allocated the same memory.

The multitasking component While the multithreading component


4.
involves multiprocessing. does not involve multiprocessing.

In multitasking, the CPU is provided While in multithreading also, a CPU is


5. in order to execute many tasks at a provided in order to execute many
time. threads from a process at a time.
S.NO Multitasking Multithreading

In multitasking, processes don’t


share the same resources, each While in multithreading, each process
6.
process is allocated separate shares the same resources.
resources.

Multitasking is slow compared to


7. While multithreading is faster.
multithreading.

In multitasking, termination of a While in multithreading, termination of


8.
process takes more time. thread takes less time.

Isolation and memory protection Isolation and memory protection does not
9.
exist in multitasking. exist in multithreading.

It helps in developing efficient It helps in developing efficient operating


10.
programs. systems.

Involves dividing a single process into


Involves running multiple multiple threads that can execute
11.
independent processes or tasks concurrently

Multiple threads within a single process


Multiple processes or tasks run
share the same memory space and
12. simultaneously, sharing the same
resources
processor and resources

Threads share the same memory space


Each process or task has its own
13. and resources of the parent process
memory space and resources

Used to manage multiple processes Used to manage multiple processes and


14.
and improve system efficiency improve system efficiency

Examples: running multiple Examples: splitting a video encoding task


15. applications on a computer, running into multiple threads, implementing a
multiple servers on a network responsive user interface in an application
Q11 What is object? Give one example of object with its properties & methods in
java.
Ans.
In Java, an object is an instance of a class. A class is a blueprint for creating objects,
and an object is a concrete instance of a class. Objects have properties and methods.
Properties are the data that the object stores, and methods are the actions that the
object can perform.
In Java, let's consider an example of an object like a Car.
Properties of a Car object:
1. Model (String): Represents the model of the car, e.g., "Toyota Camry".
2. Year (int): Indicates the manufacturing year of the car, e.g., 2022.
3. Color (String): Describes the color of the car, e.g., "Red".
4. Speed (int): Represents the current speed of the car in km/h.
5. FuelLevel (double): Indicates the amount of fuel in the car's tank.

Methods of a Car object:


1. accelerate(int speedIncrease): Increases the speed of the car by the specified
amount.
2. brake(): Slows down the car by decreasing the speed.
3. refuel(double amount): Adds fuel to the car's tank by the specified amount.
4. honk(): Produces a honking sound from the car's horn.
5. displayInfo(): Displays information about the car, such as model, year, color, current
speed, and fuel level.
This is just a basic example to illustrate how properties and methods can be
associated with an object like a Car in Java.

Q12 Write java program to display multiplication table of 4 using for loop.
Ans.
public class MultiplicationTable {
public static void main(String[] args) {
int number = 4; // The number for which we want to print the multiplication
table

System.out.println("Multiplication Table of " + number);

// Using a for loop to print the multiplication table


for (int i = 1; i <= 10; i++) {
System.out.println(number + " x " + i + " = " + (number * i));
}
}
}

Q13 Explain structure of for loop with suitable example.


Ans.
A for loop in Java is used to repeatedly execute a block of code for a specified number
of times. It consists of three main parts: initialization, condition, and
increment/decrement. Here's a detailed explanation of each part, along with an
example:
Structure of a for Loop
The general structure of a for loop is as follows:
for (initialization; condition; update) {
// body of the loop
}
1. Initialization: This part initializes the loop control variable(s) and is executed
only once, at the beginning of the loop.
2. Condition: This is a boolean expression that is evaluated before each iteration
of the loop. If the condition evaluates to true, the loop body is executed. If it
evaluates to false, the loop terminates.
3. Update: This part is executed after each iteration of the loop body. It usually
updates the loop control variable(s).
Example
Here’s a simple example of a for loop that prints the numbers from 1 to 5:
public class ForLoopExample {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Number: " + i);
}
}
}
Explanation of the Example
1. Initialization: int i = 1;
o Here, i is initialized to 1. This happens only once at the start of the loop.
2. Condition: i <= 5;
o Before each iteration, the condition i <= 5 is checked. If it is true, the loop
body executes. If it is false, the loop terminates.
3. Update: i++
o After each iteration of the loop body, i is incremented by 1 using the i++
statement.
4. Loop Body: System.out.println("Number: " + i);
o This statement is the body of the loop and is executed every time the
condition is true.
The output of the above code will be:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5

Q14 Explain the various features of java programming language.


Ans.
Java is a versatile, object-oriented programming language that has several key
features making it a popular choice for developers.
Here are some of the most important features of Java:
1. Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2. Object-oriented
Java is an object-oriented programming language. Everything in Java is an object.
Object-oriented means we organize our software as a combination of different types
of objects that incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3. Platform Independent
Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a
program runs.
4. Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
5. Robust
The English mining of Robust is strong. Java is robust because:
o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual
Machine to get rid of objects which are not being used by a Java application
anymore.
o There are exception handling and the type checking mechanism in Java. All
these points make Java robust.
6. Architecture-neutral
Java is architecture neutral because there are no implementation dependent features,
for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of
memory for both 32 and 64-bit architectures in Java.
7. Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It
doesn't require any implementation.
8. High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled
languages, e.g., C, C++, etc.
9. Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications. This feature of Java makes
us able to access files by calling the methods from any machine on the internet.
10. Multi-threaded
A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads. The main
advantage of multi-threading is that it doesn't occupy memory for each thread. It
shares a common memory area. Threads are important for multi-media, Web
applications, etc.
11. Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means
classes are loaded on demand. It also supports functions from its native languages,
i.e., C and C++.
Java supports dynamic compilation and automatic memory management (garbage
collection).

Q15 Write java program to perform addition of two matrix.


Ans.
Here is a simple Java program to add two matrices:
public class MatrixAddition {
public static void main(String[] args) {
// Define the dimensions of the matrices
int rows = 3;
int columns = 3;

// Initialize the first matrix


int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Initialize the second matrix


int[][] matrix2 = {
{9, 8, 7},
{6, 5, 4},
{3, 2, 1}
};

// Create a result matrix to store the sum


int[][] resultMatrix = new int[rows][columns];

// Perform matrix addition


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

// Print the result matrix


System.out.println("The sum of the matrices is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}

Q16 How to achieved abstraction using abstract class in java.


Ans.
Abstraction is a feature of OOPs. The feature allows us to hide the implementation
detail from the user and shows only the functionality of the programming to the user.
Because the user is not interested to know the implementation. It is also safe from
the security point of view.
Using Abstract Class:
Abstract classes are the same as normal Java classes the difference is only that an
abstract class uses abstract keyword while the normal Java class does not use. We use
the abstract keyword before the class name to declare the class as abstract.

Note: Using an abstract class, we can achieve 0-100% abstraction.


Remember that, we cannot instantiate (create an object) an abstract class. An
abstract class contains abstract methods as well as concrete methods. If we want to
use an abstract class, we have to inherit it from the base class.

If the class does not have the implementation of all the methods of the interface, we
should declare the class as abstract. It provides complete abstraction. It means that
fields are public static and final by default and methods are empty.

The syntax of abstract class is:


public abstract class ClassName
{
public abstract methodName();
}
It is used to define generic types of behavior at the top of an OOPs class hierarchy and
use its subclasses to provide implementation details of the abstract class.

Q17 Write a java program to implement multilevel inheritance with 2 levels of


hierarchy.
Ans.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking");
}
}

class Labrador extends Dog {


void color() {
System.out.println("Labrador is golden in color");
}
}

public class Main {


public static void main(String[] args) {
Labrador myLabrador = new Labrador();
myLabrador.eat();
myLabrador.bark();
myLabrador.color();
}
}

Q18 What is package? State how to create and access user defined package in Java.
Ans.
A package in Java is a namespace that organizes related classes and interfaces. Similar
to the folders on your computer, packages are a way to group related Java classes and
interfaces. This makes it easier to find, locate, and use them. User-defined packages
are similar to built-in packages. They can be imported into other classes and used in
the same way as built-in packages.
To create a user-defined package in Java, you need to follow these steps:
1. Create a directory with the package name.
2. Place the Java files (classes) inside this directory.
3. Add the package declaration at the beginning of each Java file.
• Here is an example of creating a user-defined package named com.example:
// File: com/example/MyClass.java
package com.example;

public class MyClass {


// Class implementation
}
• To access classes from a user-defined package in Java, you can use
the import statement in your Java file. For example, to access MyClass from
the com.example package:
import com.example.MyClass;

public class Main {


public static void main(String[] args) {
MyClass myObject = new MyClass();
// Access MyClass methods or fields
}
}
By following these steps, you can effectively create and access user-defined packages
in Java to organize and manage your code efficiently.

Q19 Explain the benefits of Multithreading?


Ans.
Multithreading in Java offers several benefits:
1. Concurrency: Multithreading allows multiple tasks to execute concurrently
within a single process. This enables efficient utilization of CPU resources by
executing multiple tasks simultaneously, which can lead to improved
performance and responsiveness in applications.
2. Responsiveness: By separating tasks into multiple threads, Java applications can
remain responsive even when performing CPU-intensive or long-running
operations. For example, in a graphical user interface (GUI) application,
multithreading ensures that the user interface remains responsive while other
tasks, such as data processing or network communication, are being performed
in the background.
3. Parallelism: Multithreading enables parallel execution of tasks on
multiprocessor systems, where multiple threads can execute simultaneously on
different CPU cores. This can lead to significant performance gains for compute-
intensive tasks, as they can be divided into smaller subtasks that can execute
concurrently.
4. Resource Sharing: Threads within the same process share the same memory
space, allowing them to easily communicate and share data with each other.
This facilitates efficient data sharing and communication between different
parts of an application.
5. Simplified Task Management: Multithreading simplifies the management of
complex tasks by allowing them to be divided into smaller, more manageable
threads. This can improve code organization and maintainability by separating
concerns and encapsulating different parts of the application logic within
separate threads.
6. Asynchronous Programming: Multithreading enables asynchronous
programming, where tasks can execute independently of each other and
communicate through mechanisms such as message passing or shared data
structures. This is particularly useful for handling I/O-bound operations, such as
network communication or disk I/O, without blocking the execution of other
tasks.
Overall, multithreading in Java provides developers with a powerful tool for building
responsive, scalable, and efficient applications that can take advantage of modern
hardware architectures. However, it also requires careful attention to concurrency
issues such as race conditions and synchronization to ensure correct and reliable
behavior.

Q20 Explain different methods supported by Thread class in java.


Ans.
The Thread class in Java offers various methods to control and manage threads
effectively. Here are some of the key methods supported by the Thread class:

1. start(): This method is used to start the execution of a thread. When start() is
called, the JVM calls the run() method of the thread.
2. run(): The run() method contains the code that constitutes the thread's task. It is
where the actual work of the thread is defined.

3. sleep(long millis): This method pauses the execution of the current thread for the
specified number of milliseconds. It's commonly used for introducing delays in a
thread's execution.

4. join(): The join() method allows one thread to wait for the completion of another
thread. When a thread calls join() on another thread, it waits until that thread
completes its execution.

5. isAlive(): This method checks if a thread is still alive. A thread is considered alive
from the moment start() is called until the run() method completes execution.

6. interrupt(): The interrupt() method interrupts a thread, causing it to stop what it's
doing and either throw an InterruptedException or exit.

7. yield(): The yield() method suggests to the scheduler that the current thread is
willing to yield its current use of the processor. It's a way to give other threads a
chance to run.

These methods provide developers with powerful tools to control thread execution,
synchronization, and communication in Java programs.

Q21 Why java is not a fully object oriented programming language? Elaborate your
answer.
Ans.
Java is often considered an object-oriented programming (OOP) language, and it does
adhere to many principles of object-oriented design. However, it's also true that Java
is not a "pure" or "fully" object-oriented language. Here's why:

1.Primitive Data Types: Java includes primitive data types like int, double, boolean,
etc., which are not objects. These primitive types do not inherit from a common class,
unlike objects, and do not have methods or fields.

2. Static Members: Java allows the use of static methods and variables, which belong
to the class itself rather than to instances of the class. Static members are not
associated with objects and can be accessed without creating an instance of the class.
3. Procedural Programming: Java supports procedural programming concepts
alongside object-oriented programming. This means you can write code that focuses
on procedures and functions rather than solely on objects and classes.

4. Direct Memory Manipulation: Java does not allow direct memory manipulation like
some lower-level languages do. In pure object-oriented languages, all operations are
performed on objects, and direct memory access is restricted.

5. Static Initialization Blocks: Java allows static initialization blocks to be executed


when a class is loaded, providing a mechanism for executing code that is not
associated with any particular instance of the class.

Despite these aspects, Java is predominantly object-oriented in its design and


encourages the use of objects, classes, inheritance, and polymorphism. It provides a
robust object model and supports key principles of OOP like encapsulation,
inheritance, and polymorphism.

While Java may not be entirely object-oriented due to the presence of primitive types
and static members, it remains a powerful language for building object-oriented
applications.

Q22 Explain the working of ‘continue’ and ‘break’ keywords in java.


Ans.
In Java, the continue and break keywords are used to control the flow of execution
within loops (such as for, while, and do-while) and switch statements. Here's how
they work:
1. continue Keyword:
o When continue is encountered within a loop, it causes the current
iteration of the loop to be prematurely terminated.
o Control immediately jumps to the next iteration of the loop, skipping any
remaining code within the loop body for the current iteration.
o If the loop condition (for for and while loops) or the loop expression (for
do-while loops) evaluates to true, the loop proceeds to the next iteration.
o The continue statement is typically used when you want to skip the
current iteration of the loop based on some condition, but continue with
the next iteration.
Example:
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) {
continue; // Skip even numbers
}
System.out.println(i);
}
2. break Keyword:
• When break is encountered within a loop or a switch statement, it causes
immediate termination of the innermost enclosing loop or switch statement.
• Control jumps to the statement immediately following the loop or switch.
• If there are multiple nested loops or switches, break only terminates the
innermost one in which it is located.
• The break statement is commonly used when you want to exit a loop
prematurely based on some condition.
Example:
int[] numbers = {1, 2, 3, 4, 5, 6};
for (int num : numbers) {
if (num == 4) {
break; // Exit loop when 4 is encountered
}
System.out.println(num);
}

Q23 Write java program to perform factorial of given number [ no taken from user by
using Scanner class]
Ans.
import java.util.Scanner;

public class FactorialCalculator {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number to calculate its factorial: ");
int number = scanner.nextInt();
long factorial = 1;

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


factorial *= i;
}

System.out.println("Factorial of " + number + " is: " + factorial);


}
}

Q24 Explain the structure of java program.


Ans.
The structure of a Java program typically consists of several components organized in
a specific manner. Here's a breakdown of the structure of a basic Java program:
1. Package Declaration (Optional):
o The package statement, if present, declares the package to which the
current Java file belongs. Packages are used for organizing related classes
and providing namespace management.
o Syntax: package package_name;
2. Import Statements (Optional):
o Import statements are used to import classes or entire packages from
other packages into the current file's namespace. They allow you to
reference classes without specifying their full package names.
o Syntax: import package_name.ClassName; or import package_name.*;
3. Class Declaration:
o Every Java program must have at least one class. The class keyword is
used to declare a class.
o The class declaration includes the class name and can optionally specify a
superclass (using extends) and implemented interfaces (using
implements).
o Syntax: public class ClassName { ... }
4. Main Method:
o The main method is the entry point of a Java program. It is where the
program starts executing.
o The main method has a specific signature: public static void main(String[]
args).
o Syntax:
public class MainClass {
public static void main(String[] args) {
// Program logic goes here
}
}
5. Program Logic:
o This section contains the actual logic of the program, which may include
variable declarations, method definitions, control structures (such as if,
else, for, while, etc.), and other statements.
o Java programs are structured around classes and methods, so the
program logic is typically organized within methods defined in the class.
6. Comments:
o Comments are used to document the code and improve its readability.
Java supports single-line comments (//) and multi-line comments (/* ...
*/).
o Comments are ignored by the compiler and do not affect the execution of
the program. They are purely for human consumption.
Here's a basic example of a Java program with the above components:
package com.example; // Optional package declaration

import java.util.Scanner; // Optional import statement

public class Main {


public static void main(String[] args) {
// Main method, entry point of the program
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
scanner.close();
}
}
This program demonstrates the basic structure of a Java program, including package
declaration, import statements, class declaration, main method, and program logic.

Q25 Write java program to perform multiplication of two matrix.


Ans.
public class MatrixMultiplication {
public static void main(String[] args) {
// Define the dimensions of the matrices
int rows = 3;
int columns = 3;

// Initialize the first matrix


int[][] matrix1 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Initialize the second matrix


int[][] matrix2 = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

// Create a result matrix to store the sum


int[][] resultMatrix = new int[rows][columns];

// Perform matrix addition


for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
resultMatrix[i][j] = matrix1[i][j] * matrix2[i][j];
}
}

// Print the result matrix


System.out.println("The sum of the matrices is:");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
}
}

Q26 How to achieve abstraction using Interfaces in java.


Ans.
Abstraction is a feature of OOPs. The feature allows us to hide the implementation
detail from the user and shows only the functionality of the programming to the user.
Because the user is not interested to know the implementation. It is also safe from
the security point of view.
Using Interface:
In Java, an interface is similar to Java classes. The difference is only that an interface
contains empty methods (methods that do not have method implementation) and
variables. In other words, it is a collection of abstract methods (the method that does
not have a method body) and static constants. The important point about an interface
is that each method is public and abstract and does not contain any constructor.
Along with the abstraction, it also helps to achieve multiple inheritance. The
implementation of these methods provided by the clients when they implement the
interface.
Note: Using interface, we can achieve 100% abstraction.
Separating interface from implementation is one way to achieve abstraction.
The Collection framework is an excellent example of it.
Features of Interface:
o We can achieve total abstraction.
o We can use multiple interfaces in a class that leads to multiple inheritance.
o It also helps to achieve loose coupling.
Syntax:
public interface XYZ
{
public void method();
}
To use an interface in a class, Java provides a keyword called implements. We provide
the necessary implementation of the method that we have declared in the interface.

Q27 Explain method overriding with suitable example.


Ans.
Method overriding in Java allows a subclass to provide a specific implementation of a
method that is already provided by one of its superclasses. This allows for
polymorphic behavior, where a subclass can define its own behavior for a method
that it inherits from its superclass.
Here's an example to illustrate method overriding:
class Animal {
public void makeSound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


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

class Cat extends Animal {


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

public class Main {


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

animal1.makeSound(); // Output: Dog barks


animal2.makeSound(); // Output: Cat meows
}
}
In this example:
• We have a superclass Animal with a method makeSound() which prints a
generic message.
• The Dog and Cat classes extend the Animal class and override the makeSound()
method with their own specific implementations.
• In the Main class, we create instances of Dog and Cat, but we reference them
using the Animal type.
• When calling the makeSound() method on these instances, the overridden
method in the subclass is invoked based on the actual object type (Dog or Cat),
demonstrating polymorphic behavior.
Method overriding allows subclasses to provide their own implementation of
methods defined in their superclass, enabling customization and flexibility in object
behavior while adhering to the principle of inheritance.

Q28 Give the difference between method overloading & method overriding.
Ans.

Method Overloading Method Overriding

Method overloading is a compile-time


Method overriding is a run-time polymorphism.
polymorphism.
Method Overloading Method Overriding

Method overriding is used to grant the specific


Method overloading helps to increase
implementation of the method which is already
the readability of the program.
provided by its parent class or superclass.

It is performed in two classes with inheritance


It occurs within the class.
relationships.

Method overloading may or may not


Method overriding always needs inheritance.
require inheritance.

In method overloading, methods must


In method overriding, methods must have the
have the same name and different
same name and same signature.
signatures.

In method overloading, the return type


In method overriding, the return type must be
can or can not be the same, but we just
the same or co-variant.
have to change the parameter.

Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.

It gives better performance. The reason behind


Poor Performance due to compile time
this is that the binding of overridden methods
polymorphism.
is being done at runtime.

Private and final methods can be


Private and final methods can’t be overridden.
overloaded.

The argument list should be different The argument list should be the same in
while doing method overloading. method overriding.
Q29 Briefly explain the advantages about synchronization in thread.
Ans.
Synchronization in threads is super important because it helps in preventing conflicts
and issues when multiple threads are trying to access shared resources
simultaneously. Here are some advantages of synchronization:

1. Prevents Data Corruption: Synchronization ensures that only one thread can access
a shared resource at a time, preventing data corruption and maintaining data
integrity.

2. Avoids Race Conditions: Race conditions occur when the outcome of a program
depends on the execution order of threads. Synchronization helps in avoiding race
conditions by controlling the access to shared resources.

3. Maintains Consistency: By synchronizing critical sections of code, you can ensure


that the shared data remains consistent and accurate across all threads.

4. Ensures Thread Safety: Synchronization helps in achieving thread safety by making


sure that operations on shared data are performed atomically, without interference
from other threads.

5. Facilitates Communication: Synchronization mechanisms like wait(), notify(), and


notifyAll() enable threads to communicate and coordinate their activities effectively.

Overall, synchronization plays a crucial role in multi-threaded programming by


maintaining order, consistency, and preventing conflicts among threads.

Q30 Explain the creation of Thread with an example program.


Ans.
To create a thread in Java, you can extend the `Thread` class or implement the
`Runnable` interface. Here's an example using the `Runnable` interface:

// Define a class that implements the Runnable interface


class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread is running!");
}
}

public class Main {


public static void main(String[] args) {
// Create an instance of the class that implements Runnable
MyRunnable myrunnable = new MyRunnable();

// Create a new Thread and pass the instance of the class to it


Thread myThread = new Thread(myrunnable);

// Start the thread


myThread.start();
}
}

In this example:
1. We create a class `MyRunnable` that implements the `Runnable` interface. This
class contains the `run()` method, which defines the task the thread will execute.

2. In the `Main` class, we create an instance of `MyRunnable`.

3. We then create a new `Thread` object `myThread` and pass the `MyRunnable`
instance to it in the constructor.

4. Finally, we start the thread using `myThread.start()`, which will execute the `run()`
method of `MyRunnable`.

When you run this program, it will create a new thread that prints "Thread is
running!" to the console. This demonstrates the basic concept of creating and running
a thread in Java using the `Runnable` interface.

You might also like