JAVA (1)
JAVA (1)
Justify
ANS:-Java achieves platform independence through its compilation process. When you compile a Java program, the
source code is translated into bytecode, which is a platform-neutral intermediate representation of the program. This
bytecode is not specific to any particular operating system or hardware architecture.
Furthermore, Java utilizes the concept of the Java Virtual Machine (JVM). The bytecode generated during compilation
is executed by the JVM, which is platform-specific. However, the JVM is available for different platforms, including
Windows, macOS, Linux, and others. This allows the same bytecode to run on any device or operating system that
has a compatible JVM installed, without the need for recompilation or modification of the original source code.
2) List out Java development tools and explain any one from it.
3. Eclipse
4. IntelliJ IDEA
5. NetBeans
6. Maven
7. Gradle
8. Ant
9. JUnit
The Java Development Kit (JDK) is a core component for developing Java applications. It includes:
- JVM (Java Virtual Machine): Runs the compiled bytecode on any platform.
- Java Runtime Environment (JRE): Provides libraries and other resources to run Java applications.
- Additional Tools: Utilities like `javap` (class file disassembler), `javadoc` (documentation generator), and others for
development and testing.
The JDK is essential for writing, compiling, and running Java programs.
ANS:-Automatic type conversion means that the programming language automatically changes one data type into
another. For example, in Java, an int can be automatically converted to a double without needing extra code from
the programmer. This helps in making sure that operations between different types work smoothly.
Example in Java
ANS:-The break and continue statements are the jump statements that are used to skip some statements inside the
loop or terminate the loop immediately without checking the test expression. These statements can be used inside
any loops such as for, while, do-while loop.
Break:-The break statement in java is used to terminate from the loop immediately. When a break statement is
encountered inside a loop, the loop iteration stops there, and control returns from the loop immediately to the first
statement after the loop. Basically, break statements are used in situations when we are not sure about the actual
number of iteration for the loop, or we want to terminate the loop based on some condition.
Syntax :
break;
Continue:-The continue statement in Java is used to skip the current iteration of a loop. We can use continue
statement inside any types of loops such as for, while, and do-while loop. Basically continue statements are used in
the situations when we want to continue the loop but do not want the remaining statement after the continue
statement.
Syntax:
continue;
ANS:-Data types in Java are of different sizes and values that can be stored in the variable that is made as per
convenience and circumstances to cover up all test cases. Java has two categories in which data types are segregated
Primitive Data Type: Primitive data are only single values and have no special capabilities. There are 8 primitive data
types.such as boolean, char, int, short, byte, long, float, and double
-long: 64-bit integer, used for large values, range from -2^63 to 2^63-1.
-Interfaces: Abstract types used to specify a behavior that classes must implement.
ANS:-
Method overloading helps to increase the readability of the Method overriding is used to grant the specific implementation of the
program. method which is already provided by its parent class or superclass.
It occurs within the class. It is performed in two classes with inheritance relationships.
Method overloading may or may not require inheritance. Method overriding always needs inheritance.
In method overloading, methods must have the same name In method overriding, methods must have the same name and same
and different signatures. signature.
Static binding is being used for overloaded methods. Dynamic binding is being used for overriding methods.
It gives better performance. The reason behind this is that the binding of
Poor Performance due to compile time polymorphism.
overridden methods is being done at runtime.
Private and final methods can be overloaded. Private and final methods can’t be overridden.
ANS:-In Java, a Constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling the constructor, memory for the object is allocated in the memory. It is a special type
of method that is used to initialize the object. Every time an object is created using the new() keyword, at least one
constructor is called.
EXAMPLE:-
// Constructor
import java.io.*;
// Driver Class
class Geeks {
// Constructor
Geeks()
{
super();
System.out.println("Constructor Called");
// main function
Object Creation: When an object is created using the new keyword, the constructor is called.
Initialization: The constructor initializes the object's fields with the provided values or default values.
- Implement the `run()` method with the code you want to execute in a thread.
Example
```java
@Override
System.out.println("Thread is running");
```
Explanation
1. MyRunnable Class:
2. Main Class:
- Starts the thread with `thread.start()`, which calls the `run()` method.
- Contains: Just the Java runtime environment for running Java applications.
- What It Is: A package that provides the libraries, JVM, and other components to run Java applications.
- Contains: JVM + standard libraries and other files required to run Java applications.
- Contains: JRE + development tools like the compiler (`javac`), debugger, and other tools.
10) What is the difference between create a string using double quotes and using new operator?
ANS:-Strings are the type of objects that can store the character of values and in Java, every character is stored in 16
bits i,e using UTF 16-bit encoding. A string acts the same as an array of characters in Java. String is an immutable class
which means a constant and cannot be changed once created and if wish to change , we need to create an new
object and even the functionality it provides like toupper, tolower, etc all these return a new object , its not modify
the original object. It is automatically thread safe.
Ways of Creating a String
1)String Literal
Syntax:
1. String literal
To make Java more memory efficient (because no new objects are created if it exists already in the string constant
pool).
Example:
In such a case, JVM will create a new string object in normal (non-pool) heap memory and the literal “Welcome” will
be placed in the string constant pool. The variable s will refer to the object in the heap (non-pool)
Example:
2. Relational Operators
3. Logical Operators
4. Bitwise Operators
Bitwise operators are used to perform operations on individual bits of integer types.
5. Assignment Operators
The ternary operator is a shorthand for an if-else statement that assigns a value based on a
condition.
ANS:-A class in Java is a set of objects which shares common characteristics/ behavior and common properties/
attributes. It is a user-defined blueprint or prototype from which objects are created. For example, Student is a class
while a particular student named Ravi is an object.To define a class in Java, you use the class keyword followed by the
class name. Within the class definition, you can include fields (variables), methods, constructors, and inner classes.
Each class typically encapsulates related data and behavior.
Class is not a real-world entity. It is just a template or blueprint or prototype from which objects are created.
Data member
Method
Constructor
Nested Class
Interface
SYNTAX:-
Within the curly braces {}, you can define fields (variables), methods, constructors, and other inner classes.
13)List out the looping statements available in Java. Explain any one with example.
ANS:-Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions
repeatedly while some condition evaluates to true. Java provides three ways for executing the loops. While all the
ways provide similar basic functionality, they differ in their syntax and condition checking time.
1.while loop: A while loop is a control flow statement that allows code to be executed repeatedly based on a given
Boolean condition. The while loop can be thought of as a repeating if statement.
Syntax :
loop statements...
2.for loop: for loop provides a concise way of writing the loop structure. Unlike a while loop, a for statement
consumes the initialization, condition and increment/decrement in one line thereby providing a shorter, easy to
debug structure of looping.
Syntax:
statement(s)
3.do while: do while loop is similar to while loop with only difference that it checks for condition after executing the
statements, and therefore is an example of Exit Control Loop.
Syntax:
do
statements..
while (condition);
ANS:-Scope of a variable is the part of the program where the variable is accessible. Like C/C++, in Java, all identifiers
are lexically (or statically) scoped, i.e.scope of a variable can be determined at compile time and independent of
function call stack.
Java programs are organized in the form of classes. Every class is part of some package. Java scope rules can be
covered under following categories.
Member Variables (Class Level Scope):-These variables must be declared inside class (outside any function). They
can be directly accessed anywhere in class.
Local Variables (Method Level Scope):-Variables declared inside a method have method level scope and can’t be
accessed outside the method.
Block scope:-Block scope refers to the scope of variables declared within a block of code enclosed within curly braces
{}. In Java, blocks can be found within methods, constructors, loops, if statements, and other control structures.
-Variables declared within a block are accessible only within that block and any nested blocks. Once the block
execution completes, the variables -declared within it go out of scope, and their memory is reclaimed.
-In Java we can usually access a variable as long as it was defined within the same set of brackets as the code we are
writing or within any curly brackets inside of the curly brackets where the variable was defined.
-Any variable defined in a class outside of any method can be used by all member methods.
-When a method has the same local variable as a member, “this” keyword can be used to reference the current class
variable.
-For a variable to be read after the termination of a loop, It must be declared before the body of the loop.
ANS:-
ArrayList LinkedList
This class uses a dynamic array to store the elements in This class uses a doubly linked list to store the elements in
it. With the introduction of generics, this class supports it. Similar to the ArrayList, this class also supports the
1. the storage of all types of objects. storage of all types of objects.
Manipulating ArrayList takes more time due to the Manipulating LinkedList takes less time compared to
internal implementation. Whenever we remove an ArrayList because, in a doubly-linked list, there is no
element, internally, the array is traversed and the concept of shifting the memory bits. The list is traversed
2. memory bits are shifted. and the reference link is changed.
4. It can be one, two or multi-dimensional. It can either be single, double or circular LinkedList.
This class works better when the application demands This class works better when the application demands
7. storing the data and accessing it. manipulation of the stored data.
ArrayList LinkedList
10. It is used to store only similar types of data. It is used to store any types of data.
12. This is known as static memory allocation. This is known as dynamic memory allocation.
ANS:-Multiple Inheritance is a feature provided by OOPS, it helps us to create a class that can inherit the properties
from more than one parent. Some of the programming languages like C++ can support multiple inheritance but Java
can’t support multiple inheritance.The major reason behind Java’s lack of support for multiple inheritance lies in its
design philosophy of simplicity and clarity over complexity. By disallowing Multiple Inheritance, Java aims to prevent
the ambiguity and complexities that can arise from having multiple parent classes.
Java class can be inherited from only one superclass using the extends keyword. The single inheritance model
ensures a clear hierarchical structure where each class has a single direct superclass and it can facilitate easier code
maintenance and reduce the potential for conflicts.
ANS:-Serialization is a mechanism of converting the state of an object into a byte stream.Serialization in Java is the
process of converting an object into a format that can be easily stored, transmitted, or reconstructed later. This is
done by converting the object into a sequence of bytes. It's commonly used for saving object states to files, sending
objects over networks, or storing them in databases. Java provides built-in support for serialization through the
java.io.Serializable interface, making it easy to serialize and deserialize objects using streams.
EXAMPLE:-
import java.io.*;
this.name = name;
this.age = age;
return "Person{" +
"name='" + name + '\'' +
'}';
// Serialization
try {
out.writeObject(person);
out.close();
fileOut.close();
} catch (IOException e) {
e.printStackTrace();
18)Write a Program in java to check whether the given number is Armstrong number
ANS:-
import java.util.Scanner;
if (isArmstrong(number)) {
} else {
int sum = 0;
while (number != 0) {
number /= 10;
Below are the different types of inheritance which are supported by Java.
1. Single Inheritance
In single inheritance, subclasses inherit the features of one superclass. In the image below, class A serves as a base
class for the derived class B.
2. Multilevel Inheritance
In Multilevel Inheritance, a derived class will be inheriting a base class, and as well as the derived class also acts as
the base class for other classes. In the below image, class A serves as a base class for the derived class B, which in
turn serves as a base class for the derived class C. In Java, a class cannot directly access the grandparent’s members.
3. Hierarchical Inheritance
In Hierarchical Inheritance, one class serves as a superclass (base class) for more than one subclass. In the below
image, class A serves as a base class for the derived classes B, C, and D.
In Multiple inheritances, one class can have more than one superclass and inherit features from all parent classes.
Please note that Java does not support multiple inheritances with classes. In Java, we can achieve multiple
inheritances only through Interfaces. In the image below, Class C is derived from interfaces A and B.
5. Hybrid Inheritance
It is a mix of two or more of the above types of inheritance. Since Java doesn’t support multiple inheritances with
classes, hybrid inheritance involving multiple inheritance is also not possible with classes. In Java, we can achieve
hybrid inheritance only through Interfaces if we want to involve multiple inheritance to implement Hybrid
inheritance.
ANS:-Method overloading is a feature in Java that allows a class to have multiple methods with the same name but
with different parameters or argument lists within the same class. The methods must have different parameter types,
different numbers of parameters, or both.
When a method is overloaded, Java determines which version of the method to execute based on the arguments
provided during the method call. This is known as compile-time polymorphism or static polymorphism because the
decision on which method to call is made at compile time.
Method overloading enables developers to define several methods with the same name that perform similar tasks
but operate on different types of data or accept different numbers of parameters, making the code more readable
and flexible.
METHOD OVERRIDING:-
Method overriding in Java refers to the process of providing a new implementation for a method in a subclass that is
already defined in its superclass. When a subclass overrides a method of its superclass, it provides a specific
implementation of that method tailored to the subclass's context.In Java, Overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is already provided by one of its super-
classes or parent classes. When a method in a subclass has the same name, the same parameters or signature, and
the same return type(or sub-type) as a method in its super-class, then the method in the subclass is said to override
the method in the super-class.
ANS:-The static keyword in Java is mainly used for memory management. The static keyword in Java is used to share
the same variable or method of a given class. The users can apply static keywords with variables, methods, blocks,
and nested classes. The static keyword belongs to the class than an instance of the class.
ANS:-
Class Interface
The keyword used to create a class is “class” The keyword used to create an interface is “interface”
Classes do not support multiple inheritance. The interface supports multiple inheritance.
Variables in a class can be static, final, or neither. All variables are static and final.
ANS:-The super() method in Java is used to call the constructor of the superclass from the subclass. It is typically used
in the constructor of the subclass to invoke the constructor of the superclass. Here are the conditions for using the
super() method:
1.Call to superclass constructor: The super() method must be the first statement in the constructor of the subclass.
2.Implicit super constructor call: If the constructor of the subclass does not explicitly call super(), the compiler
inserts a call to the no-argument constructor of the superclass.
3.Explicit super constructor call: If the superclass does not have a no-argument constructor (default constructor), the
subclass constructor must explicitly call one of the superclass constructors using super().
4.Arguments matching: When calling super(), the arguments passed (if any) must match one of the constructors in
the superclass.
5.Superclass constructor chaining: If the superclass constructor calls another constructor within the same class using
this(), the subclass constructor can still use super() to call one of the superclass constructors.
ANS:-
Java C++
oracle.com/java isocpp.org
Java was influenced to develop BeanShell, C#, Clojure, Groovy, C++ was influenced to develop C99, Java, JS++, Lua,
Hack, J#, Kotlin, PHP, Python, Scala, etc. languages. Perl, PHP, Python, Rust, Seed7, etc. languages.
Platform-independent, Java bytecode works on any operating Platform dependent should be compiled for different
system. platforms.
It can run on any OS hence it is portable. C++ is platform-dependent. Hence it is not portable.
It doesn’t support direct native library calls but only Java Native It supports direct system library calls, making it
Interfaces. suitable for system-level programming.
Libraries have a wide range of classes for various high-level C++ libraries have comparatively low-level
services. functionalities.
Java doesn’t support the goto Keyword C++ supports the goto keyword.
Java C++
Java doesn’t support Structures and Unions. C++ supports Structures and Unions.
It supports no global scope. It supports both global scope and namespace scope.
Java supports only calls by value. C++ both supports call by value and call by reference.
ANS:-In Java, the super keyword is used to refer to the superclass (parent class) of the current object. It can be used
to access superclass methods, constructors, and fields from within the subclass (child class). One common use case
for the super keyword is to invoke the superclass constructor from the subclass constructor, especially when the
superclass has parameterized constructors.
In this example:
•We have a superclass Animal with a parameterized constructor that initializes the color field.
•The subclass Dog extends the Animal class and adds a new field breed.
•In the constructor of Dog, we use super(color) to explicitly call the superclass constructor with the color parameter.
•Inside the display() method of Dog, we use super.display() to call the superclass display() method to print the color
of the dog.
Without the use of the super keyword, the superclass constructor would not be invoked automatically, and the
superclass fields would remain uninitialized. Similarly, without super.display(), only the subclass method would be
called, and the superclass method would be overridden.
Using the super keyword ensures that both superclass and subclass constructors and methods are properly invoked,
allowing for correct initialization and behavior in class hierarchies.
26)List out few important classes and interfaces in collection framework. What is vector class?
ANS:-The Java Collections Framework provides a set of classes and interfaces to represent and manipulate collections
of objects. Some important classes and interfaces in the Java Collections Framework are:
Classes:
1.ArrayList: Implements the List interface using a dynamic array. It allows fast random access and dynamic resizing of
the underlying array.
2.LinkedList: Implements the List interface using a doubly linked list. It provides efficient insertion and deletion
operations at both ends of the list.
3.HashSet: Implements the Set interface using a hash table. It does not allow duplicate elements and provides
constant-time performance for basic operations like add, remove, and contains.
4.TreeSet: Implements the Set interface using a red-black tree. It stores elements in sorted order and provides
efficient operations for range queries.
5.HashMap: Implements the Map interface using a hash table. It stores key-value pairs and provides constant-time
performance for basic operations like put, get, and remove.
6.TreeMap: Implements the Map interface using a red-black tree. It stores key-value pairs in sorted order and
provides efficient operations for range queries.
Interfaces:
1.List: Represents an ordered collection of elements that allows duplicate elements. It defines operations for
accessing, adding, removing, and modifying elements in the list.
2.Set: Represents a collection of unique elements. It does not allow duplicate elements and provides operations for
adding, removing, and testing for the presence of elements.
3.Map: Represents a collection of key-value pairs. It maps keys to values and does not allow duplicate keys. It
provides operations for adding, removing, and retrieving values based on keys.
4.Queue: Represents a collection that supports insertion and removal of elements according to a specific order. It
typically follows the FIFO (First-In-First-Out) or LIFO (Last-In-First-Out) order.
5.Deque: Represents a double-ended queue that supports insertion and removal of elements at both ends. It
extends the Queue interface and provides additional operations for stack-like behavior.
VECTOR:-The Vector class implements a growable array of objects. Vector implements a dynamic array which means
it can grow or shrink as required. Like an array, it contains components that can be accessed using an integer index.
They are very similar to ArrayList, but Vector is synchronized and has some legacy methods that the collection
framework does not contain.
It also maintains an insertion order like an ArrayList. Still, it is rarely used in a non-thread environment as it is
synchronized, and due to this, it gives a poor performance in adding, searching, deleting, and updating its elements.
The Iterators returned by the Vector class are fail-fast. In the case of concurrent modification, it fails and throws the
ConcurrentModificationException.
Syntax:
public class Vector<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, Serializable
27)What is wrapper class? Explain Auto boxing and unboxing with example.
ANS:-WRAPPER CLASS:-A Wrapper class in Java is a class whose object wraps or contains primitive data types. When
we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other
words, we can wrap a primitive value into a wrapper class object.They convert primitive data types into objects.
Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by
value).The classes in java.util package handles only objects and hence wrapper classes help in this case also.
Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and
not primitive types.
-On object data we can call multiple methods compareTo(), equals(), toString()
1. Autoboxing
The automatic conversion of primitive types to the object of their corresponding wrapper classes is known as
autoboxing. For example – conversion of int to Integer, long to Long, double to Double, etc.
2. Unboxing
It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding
primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc.
ANS:-
String StringBuffer
String is slow and consumes more memory when we concatenate too StringBuffer is fast and consumes less
many strings because every time it creates new instance. memory when we concatenate t strings.
String class overrides the equals() method of Object class. So you can StringBuffer class doesn't override the
compare the contents of two strings by equals() method. equals() method of Object class.
String class is slower while performing concatenation operation. StringBuffer class is faster while performing
concatenation operation.
String class uses String constant pool. StringBuffer uses Heap memory
ANS:-
ANS:-In Java, a constructor is a block of codes similar to the method. It is called when an instance of the class is
created. At the time of calling constructor, memory for the object is allocated in the memory.It is a special type of
method which is used to initialize the object.Every time an object is created using the new() keyword, at least one
constructor is called.
1.Same Name as Class: Constructors have the same name as the class in which they are defined. This allows the
compiler to recognize them as constructors and automatically invoke them when objects of the class are created.
2.No Return Type: Constructors do not have a return type, not even void. This is because they are not intended to
return any value; their purpose is to initialize objects.
3.Cannot be Inherited or Overridden: Constructors are not inherited by subclasses and cannot be overridden like
regular methods. Each class in the inheritance hierarchy must define its own constructors.
4.Can Overload: Like other methods, constructors can be overloaded, meaning a class can have multiple constructors
with different parameter lists. This allows for object initialization with different sets of parameters.
5.Implicit Superclass Constructor Call: If a constructor does not explicitly call a superclass constructor using super(),
the compiler inserts a call to the no-argument constructor of the superclass as the first statement in the constructor.
6.Implicit Superclass Constructor Invocation: If a constructor does not explicitly call super() or this(), the compiler
inserts a call to the no-argument constructor of the superclass as the first statement in the constructor.
7.Initialization Block: Constructors can contain initialization blocks (initializer blocks) that are executed before the
constructor body. These blocks are useful for performing common initialization tasks across multiple constructors.
8.Can Access Modifiers: Constructors can have access modifiers like public, private, protected, or default (package-
private), controlling their visibility and accessibility.
9.Initialization of Final Variables: Constructors can initialize final variables. Once initialized, the value of a final
variable cannot be changed.
Multilevel inheritance in Java refers to a type of inheritance where a class is derived from another class, which is also
derived from another class, creating a chain of inheritance. In other words, it involves more than two levels of
inheritance. This allows the properties and methods of a class to be passed on to multiple levels of subclasses.
Example:-
// Base class
class Animal {
void eat() {
System.out.println("Eating...");
void bark() {
System.out.println("Barking...");
System.out.println("Weeping...");
ANS:- 1.Object oriented:Java is an Object Oriented Programming Language, which supports the construction of
programs that consist of collections of collaborating objects. These objects have a unique identity and have oop
features such as encapsulation, abstraction, Class, inheritance and polymorphism.
2. Simple:Java was designed with a small number of language constructs so that programmers could learn it quickly
which make it simple. It eliminates several language features that were in C/C++ that was associated with poor
programming practices or rarely used such as multiple inheritance, goto statements, header files, structures,
operator overloading, and pointers, security reason was also there for removing or not adding pointer in java.
3. Secure:Java is designed to be more secure in a networked environment. A byte code verification processis used by
the Java run-time environment to ensure that code loaded over the network does not violate Java security
constraints. Absence of pointer also adds on values for java security features.
4. Platform Independent: As we have seen on Introduction page Byte code and JVM which plays the major role for
making the java platform independent and which make it a distinct.
5. Robust:Java is designed to eliminate certain types of programming errors. Java is strongly typed, which allows
extensive compile-time error checking. Its automatic memory management (garbage collection) eliminates memory
leaks and other problems associated with dynamic memory allocation and deallocation. Java does not support
memory pointers, which eliminates the possibility of overwriting memory and corrupting data.
6. Portable:Has usually meant some work when moving an application program to another machine. Recently, the
Java programming language and runtime environment has made it possible to have programs that run on any
operating system and machine that supports the Java standard (from Sun Microsystems) without any porting work.
7. Architecture Neutral:Any system that implements the Java Virtual Machine interprete the Java applications that
are compiled to bytecodes. The Java Virtual Machine is supported by most ofoperating systems, this means that Java
applications are able to run on most platforms.
8. Dynamic:Java supports dynamic loading of classes class loader is responsible for loading the class dynamically in to
JVM.
9. Interpreted:Java source code is compiled to bytecodes, which are interpreted by a Java run-time environment.
10. High Performance:Java is an interpreted language, it was designed to support “just-in-time” compilers, which
dynamically compile bytecodes to machine code.
11. Multithreaded:Java supports multiple threads of execution including a set of synchronization primitives. This
makes programming with threads much easier.
12. Distributed:Java supports various levels of network connectivity. Java applications are network conscious: TCP/IP
support is built into Java class libraries. They have ability to open and access remote objects on the Internet.
Custom exceptions in Java are user-defined exceptions that extend the Exception class (for checked exceptions) or
the RuntimeException class (for unchecked exceptions). They allow you to create specific error conditions that are
relevant to your application, making your code more readable and maintainable by providing meaningful error
messages.
Inheritance:Custom exceptions should extend Exception for checked exceptions or RuntimeException for unchecked
exceptions.
Constructors:Define constructors in your custom exception class to pass error messages and other relevant data to
the superclass.
Meaningful Names:Use meaningful class names for custom exceptions to clearly indicate the type of error.
Exception Handling:Handle custom exceptions using try-catch blocks or by declaring them with the throws keyword
in method signatures.
ANS:-in Java, Access modifiers help to restrict the scope of a class, constructor, variable, method, or data member. It
provides security, accessibility, etc to the user depending upon the access modifier used with the element.Access
specifiers (also known as access modifiers) in Java determine the visibility and accessibility of classes, methods, and
variables. They help in implementing encapsulation by controlling how different parts of the code can access a
particular member or class. Java provides four main access specifiers:
1.Public (public)
Usage: For methods and variables that need to be accessed from any other class.
2.Private (private)
Usage: For methods and variables that should not be accessed outside the class.
3.Protected (protected)
Visibility: Accessible within the same package and subclasses (even if they are in different packages).
Usage: For methods and variables that should not be accessed outside the package.
35) What is inheritance? Explain different types of inheritance supported by java with an example.
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class (subclass or
derived class) to inherit properties and behaviors (fields and methods) from an existing class (superclass or base
class). This promotes code reuse and establishes a natural hierarchical relationship between classes.
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
1. Single Inheritance
class Animal {
void eat() {
void bark() {
2. Multilevel Inheritance
A class inherits from a superclass, and another class inherits from that subclass, forming a chain.
class Animal {
void eat() {
void walk() {
void bark() {
3. Hierarchical Inheritance
class Animal {
void eat() {
}
class Dog extends Animal {
void bark() {
void meow() {
ANS:-A thread is a process or task in execution. The Java Virtual Machine allows an application to execute multiple
threads concurrently. Such as paint, calculator, Microsoft word or any process running on computer is a thread. Every
thread has a priority. Threads with higher priority are executed in preference to threads with lower priority. Each
thread which is currently executing may or may not be marked as a daemon. When a new Thread object is created,
the priority of new thread is initially set equal to the priority of the creating thread.A newly created thread is a
daemon thread if and only if the creating thread is a daemon.
-NEW:
Definition: A thread that has been created but not yet started.
Transition: The start() method must be called to move the thread to the RUNNABLE state.
-RUNNABLE:
-BLOCKED:
Definition: A thread that is waiting for a monitor lock to enter a synchronized block/method.
Cause: Occurs when one thread tries to access a synchronized block/method held by another thread.
-WAITING:
Definition: A thread that is waiting indefinitely for another thread to perform a specific action.
Cause: Occurs when calling methods like Object.wait(), Thread.join(), or LockSupport.park() without a timeout.
-TIMED_WAITING:
Definition: A thread that is waiting for another thread to perform a specific action for a specified period.
Cause: Occurs when calling methods like Thread.sleep(), Object.wait(long timeout), or Thread.join(long millis).
-TERMINATED:
Cause: Occurs when the run() method completes normally or the thread is explicitly stopped.