0% found this document useful (0 votes)
3 views16 pages

Java Impo Ques

Java is a high-level, object-oriented programming language known for its platform independence, allowing code to run on any device with the Java Virtual Machine (JVM). Key features include security, multithreading, and a Just-In-Time (JIT) compiler, while core OOP concepts encompass class, object, encapsulation, abstraction, inheritance, and polymorphism. The document also discusses constructors, the Java Development Kit (JDK), Java Runtime Environment (JRE), and memory management differences between stack and heap in Java.

Uploaded by

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

Java Impo Ques

Java is a high-level, object-oriented programming language known for its platform independence, allowing code to run on any device with the Java Virtual Machine (JVM). Key features include security, multithreading, and a Just-In-Time (JIT) compiler, while core OOP concepts encompass class, object, encapsulation, abstraction, inheritance, and polymorphism. The document also discusses constructors, the Java Development Kit (JDK), Java Runtime Environment (JRE), and memory management differences between stack and heap in Java.

Uploaded by

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

What is Java?

Answer: Java is a high-level, object-oriented programming language developed by Sun Microsystems in


1995. It is platform-independent, which means we can write code once and run it anywhere using the
Java Virtual Machine (JVM). Java is mostly used for building desktop applications, web applications,
Android apps, and enterprise systems.

What are the features of Java?


Key Features of Java
 Platform Independent
 Object-Oriented
 Security
 Multithreading
 Just-In-Time (JIT) Compiler

What are the OOP concepts?

The main Object-Oriented Programming (OOP) concepts are:

1. Class
A blueprint or template for creating objects. It defines properties (attributes) and behaviors
(methods).
2. Object
An instance of a class. It has state (data) and behavior (methods).
3. Encapsulation
Wrapping data and methods into a single unit (class) and restricting direct access to some of
the object's components. This is often done using access specifiers like private, public, and
protected.
4. Abstraction
Hiding complex implementation details and showing only the essential features. This helps
reduce complexity and increase efficiency.
5. Inheritance
The mechanism by which one class (child or subclass) inherits the properties and behaviors of
another class (parent or superclass), promoting code reusability.
6. Polymorphism
The ability of a function, object, or method to behave differently based on the context. It is of
two types:
o Compile-time Polymorphism (Method Overloading)
o Runtime Polymorphism (Method Overriding)

What is data encapsulation, and why is it useful?


Data encapsulation is a core concept in programming that involves bundling data (variables) and
the methods (functions) that operate on that data into a single unit, typically a class or object. It
restricts direct access to some of the object's components, which helps protect data integrity by
controlling how it's accessed or modified. This is useful for security, maintainability, and easier
understanding of code.
Why is Encapsulation Useful?

1. Data Hiding: Prevents external access to internal object details, improving security.
2. Control: Provides control over how data is accessed or modified.
3. Maintenance: Makes the code easier to maintain or modify without affecting other parts of the
program.
4. Reusability: Encapsulated code is easier to reuse and understand.
5. Increased Flexibility: You can change internal implementation without changing the interface
exposed to users.

What is polymorphism?

The word polymorphism means having many forms, and it comes from the Greek words poly
(many) and morph (forms), this means one entity can take many forms.

What are the types of polymorphism, and how do they differ?

Types of Polymorphism in Java


In Java Polymorphism is mainly divided into two types:
1. Compile-Time Polymorphism (Static)
2. Runtime Polymorphism (Dynamic)

1.Compile-time Polymorphism

Compile-time polymorphism is also known as static polymorphism or early binding. Compile-time


polymorphism is a polymorphism that is resolved during the compilation process. Overloading of
methods is called through the reference variable of a class. Compile-time polymorphism is achieved
by method overloading and operator overloading.

a. Method overloading
We can have one or more methods with the same name that are solely distinguishable by argument
numbers, type, or order.

Method Overloading occurs when a class has many methods with the same name but different
parameters. Two or more methods may have the same name if they have other numbers of
parameters, different data types, or different numbers of parameters and different data types.

b. Operator Overloading
An operator is said to be overloaded if it can be used to perform more than one function other than
the one its pre-defined for. Operator overloading is a mechanism through which we can change the
meaning of a pre-defined operator and make it work for user-defined objects. In this example, we'll
try to achieve the same by the use of method as Java does NOT support operator overloading.

2. Runtime Polymorphism
Runtime Polymorphism in Java known as Dynamic Method Dispatch. It is a process in which a
function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved
by Method Overriding. Method overriding, on the other hand, occurs when a derived class has a
definition for one of the member functions of the base class. That base function is said to be
overridden.

Method Overriding
Method overriding in Java means when a subclass provides a specific implementation of a method
that is already defined in its superclass. The method in the subclass must have the same name,
return type, and parameters as the method in the superclass. Method overriding allows a subclass to
modify or extend the behavior of an existing method in the parent class. This enables dynamic
method dispatch, where the method that gets executed is determined at runtime based on the
object's actual type.

What are constructors in Java?


constructors play an important role in object creation. A constructor is a special block of
code that is called when an object is created. Its main job is to initialize the object, to set up
its internal state, or to assign default values to its attributes. This process happens
automatically when we use the "new" keyword to create an object.

Characteristics of Constructors:
 Same Name as the Class: A constructor has the same name as the class in
which it is defined.
 No Return Type: Constructors do not have any return type, not even void.
The main purpose of a constructor is to initialize the object, not to return a
value.
 Automatically Called on Object Creation: When an object of a class is
created, the constructor is called automatically to initialize the object’s
attributes.
 Used to Set Initial Values for Object Attributes: Constructors are primarily
used to set the initial state or values of an object’s attributes when it is
created.

Name and explain the types of constructors in Java.

Types of Constructors in Java


Now is the correct time to discuss the types of the constructor, so primarily there
are three types of constructors in Java are mentioned below:
 Default Constructor
 Parameterized Constructor
 Copy Constructor
1. Default Constructor in Java
A constructor that has no parameters is known as default constructor. A
default constructor is invisible. And if we write a constructor with no arguments,
the compiler does not create a default constructor. Once you define a
constructor (with or without parameters), the compiler no longer provides the
default constructor. Defining a parameterized constructor does not automatically
create a no-argument constructor, we must explicitly define if needed. The
default constructor can be implicit or explicit.
 Implicit Default Constructor: If no constructor is defined in a class, the
Java compiler automatically provides a default constructor. This constructor
doesn’t take any parameters and initializes the object with default values,
such as 0 for numbers, null for objects.
 Explicit Default Constructor: If we define a constructor that takes no
parameters, it's called an explicit default constructor. This constructor
replaces the one the compiler would normally create automatically. Once you
define any constructor (with or without parameters), the compiler no longer
provides the default constructor for you.

2. Parameterized Constructor in Java


A constructor that has parameters is known as parameterized
constructor. If we want to initialize fields of the class with our own values, then
use a parameterized constructor.

3. Copy Constructor in Java


Unlike other constructors copy constructor is passed with another object which
copies the data available from the passed object to the newly created object.

What is JDK?
The Java Development Kit (JDK) is a cross-platformed software development environment that offers a
collection of tools and libraries necessary for developing Java-based software applications and applets. It is a
core package used in Java, along with the JVM (Java Virtual Machine) and the JRE (Java Runtime
Environment).

Contents of JDK
The JDK has a private Java Virtual Machine (JVM) and a few other resources
necessary for the development of a Java Application.
JDK contains:
 Java Runtime Environment (JRE),
 An interpreter/loader (Java),
 A compiler (javac),
 An archiver (jar) and many more.
The Java Runtime Environment in JDK is usually called Private Runtime
because it is separated from the regular JRE and has extra content.

What is JVM?
A Java Virtual Machine (JVM) is a virtual machine that allows Java programs to
run on different platforms and operating systems. It acts as an interpreter,
translating Java bytecode into machine code that the computer can understand.
The JVM is a crucial part of the Java Runtime Environment (JRE).

What is JRE?
A Java Virtual Machine (JVM) is a virtual machine that allows Java programs to
run on different platforms and operating systems. It acts as an interpreter,
translating Java bytecode into machine code that the computer can understand.
The JVM is a crucial part of the Java Runtime Environment (JRE).

In Java, what are the differences between heap and stack memory?

Difference between Stack and Heap Memory in Java


S.No. Stack Memory in Java Heap Memory in Java

1. Stack follows the LIFO order. Heap does not follow any order because here, the
pattern of memory allocation is not fixed.

2. It stores the entities that have a short life, like Heap stores entities like objects.
variables and methods.

3. It is not flexible as we cannot make any changes It is flexible as we can make changes here even
once the memory allocation is done. after the allocation of memory.

4. It is faster than heap in terms of allocation and It is slower than stack in terms of allocation and
deallocation. deallocation.

5. The size of stack memory is small. The size of heap memory is large.
6. Through the JVM option -Xss, we can improve Through the JVM options -Xmx and -Xms, we can
the size of a stack. change the size of a stack.

7. It is affordable. It is affordable as compared to the stack.

8. The implementation part is easy here. The implementation part is tough here.

9. In stack, the memory allotment is continuous. In heap, the memory allotment is random.

10. The allocation and deallocation are automatically Here the allocation and deallocation are done
performed by the compiler. manually.

Is Java Platform Independent if then how?


The meaning of Java platform-independent is that the Java compiled code(byte code) can
run on all operating systems. A program is written in a language that is human-readable. It
may contain words, phrases, etc. which the machine does not understand. For the source
code to be understood by the machine, it needs to be in a language understood by
machines, typically a machine-level language. So, here comes the role of a compiler. The
compiler converts the high-level language (human language) into a format understood by
the machines.

Step-by-Step Execution of Java Program


 Whenever a program is written in JAVA, the java compiles it.
 The result of the JAVA compiler is the .class file or the bytecode and not
the machine's native code (unlike the C compiler).
 The bytecode generated is a non-executable code and needs an interpreter
to execute on a machine. This interpreter is the JVM and thus the Bytecode
is executed by the JVM.
 And finally, the program runs to give the desired output.
What is a classloader?

Explain public static void main(String args[]) in Java.

Syntax of the main() method is always written as:

1. Public
It is an Access modifier, which specifies from where and who can access the
method. Making the main() method public makes it globally available. It is made
public so that JVM can invoke it from outside the class as it is not present in the
current class.
2. Static
It is a keyword that is when associated with a method, making it a class-
related method. The main() method is static so that JVM can invoke it
without instantiating the class. This also saves the unnecessary wastage of
memory which would have been used by the object declared only for calling
the main() method by the JVM.

3. Void
It is a keyword and is used to specify that a method does not return
anything. As the main() method does not return anything, its return type is void.
As soon as the main() method terminates, the Java program terminates too.
Hence, it doesn't make any sense to return from the main() method as JVM
can't do anything with its return value of it.

4. main
It is the name of the Java main method. It is the identifier that the JVM looks
for as the starting point of the Java program. It's not a keyword.

5. String[] args
It stores Java command-line arguments and is an array of
type java.lang.String class. Here, the name of the String array is args but it is
not fixed and the user can use any name in place of it.

What is Java String Pool?

The Java String Pool (also known as the String Intern Pool) is a special memory region in the Java heap
where String literals are stored to optimize memory usage and improve performance.

What will happen if we don't declare the main as static?


If the main method in Java is not declared as static, the program will not run because the JVM (Java Virtual
Machine) cannot find the entry point for execution. The JVM expects the main method to be static so it can
be called directly without needing to create an instance of the class.

Explain different data types in Java.

. Primitive Data Types (built-in)


There are 8 primitive data types:

Type Size Description Example


byte 1 byte Smallest integer type (-128 to 127) byte a = 100;
short 2 bytes Small integer (-32,768 to 32,767) short s = 2000;
int 4 bytes Default integer type int x = 12345;
Type Size Description Example
long 8 bytes Large integer long l = 1234567890L;
float 4 bytes Single-precision decimal float f = 12.5f;
double 8 bytes Double-precision decimal (default for decimals) double d = 19.99;
char 2 bytes A single Unicode character char c = 'A';
boolean 1 bit True or false values boolean b = true;

📝 Note: Numeric types (int, float, etc.) are signed and store both positive and negative values.

2. Non-Primitive (Reference) Data Types


These refer to objects and include:

Type Description Example


String Sequence of characters String s = "Hello";
Arrays Collection of elements of the same type int[] arr = {1, 2, 3};
Classes Blueprint for creating objects MyClass obj = new MyClass();
Interfaces Reference type used for abstraction Runnable r = new MyRunnable();
Enums Special class representing a group of constants enum Day { MON, TUE }

What are the default values assigned to variables and instances in Java?

Default Values for Instance Variables:


Data Type Default Value

byte 0

short 0

int 0

long 0L

float 0.0f

double 0.0d

char '\u0000' (null character)

boolean false

Object types null

What is a static variable?

A static variable in Java is a variable that belongs to the class, not to any specific object. It is shared across
all instances of the class and is initialized only once when the class is first loaded into memory.
What is Inheritance? Explain types of inheritance.

Inheritance is one of the four fundamental OOP concepts (along with encapsulation, polymorphism, and
abstraction). It allows a class to acquire the properties and behaviors (fields and methods) of another class.

✅ Why Use Inheritance?

 Code Reusability: Avoid duplication by reusing parent class code.


 Extensibility: Add or enhance functionality by extending base classes.
 Hierarchy Representation: Helps model relationships like is-a (e.g., Dog is an Animal).

Types of Inheritance in Java


Below are the different types of inheritance which are supported by Java.
 Single Inheritance
 Multilevel Inheritance
 Hierarchical Inheritance
 Multiple Inheritance
 Hybrid Inheritance
1. Single Inheritance
In single inheritance, a sub-class is derived from only one super class. It inherits the
properties and behavior of a single-parent class. Sometimes, it is also known as simple
inheritance. In the below figure, 'A' is a parent class and 'B' is a child class. The class 'B'
inherits all the properties of the class 'A'.

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 if they
are private.

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.

Multiple Inheritance (Through Interfaces)


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.
It is important to note that Hybrid inheritance does not necessarily require the
use of Multiple Inheritance exclusively. It can be achieved through a
combination of Multilevel Inheritance and Hierarchical Inheritance with classes,
Hierarchical and Single Inheritance with classes. Therefore, it is indeed possible
to implement Hybrid inheritance using classes alone, without relying on multiple
inheritance type.
Justify why Java doesn’t support multiple inheritance?

Explain Java tokens in detail.

In Java, Tokens are the smallest elements of a program that is meaningful to


the compiler. They are also known as the fundamental building blocks of the
program. Tokens can be classified as follows:
1. Keywords
2. Identifiers
3. Constants/Literals
4. Operators
5. Separators

What are the different operators used in Java?

Types of Operators in Java


1. Arithmetic Operators
2. Unary Operators
3. Assignment Operator
4. Relational Operators
5. Logical Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instance of operator
Let's see all these operators one by one with their proper examples.
1. Arithmetic Operators
Arithmetic Operators are used to perform simple arithmetic operations on
primitive and non-primitive data types.

 * : Multiplication
 / : Division
 % : Modulo
 + : Addition
 - : Subtraction

2. Unary Operators
Unary Operators need only one operand. They are used to increment,
decrement, or negate a value.
 - , Negates the value.
 + , Indicates a positive value (automatically converts byte, char,
or short to int).
 ++ , Increments by 1.
o Post-Increment: Uses value first, then increments.
o Pre-Increment: Increments first, then uses value.
 -- , Decrements by 1.
o Post-Decrement: Uses value first, then decrements.
o Pre-Decrement: Decrements first, then uses value.
 ! , Inverts a boolean value.

3. Assignment Operator
'=' Assignment operator is used to assign a value to any variable. It has right-
to-left associativity, i.e. value given on the right-hand side of the operator is
assigned to the variable on the left, and therefore right-hand side value must be
declared before using it or should be a constant.
The general format of the assignment operator is:
variable = value;
In many cases, the assignment operator can be combined with others to create
shorthand compound statements. For example, a += 5 replaces a = a + 5.
Common compound operators include:
 += , Add and assign.
 -= , Subtract and assign.
 *= , Multiply and assign.
 /= , Divide and assign.
 %= , Modulo and assign.
4. Relational Operators
Relational Operators are used to check for relations like equality, greater than,
and less than. They return boolean results after the comparison and are
extensively used in looping statements as well as conditional if-else statements.
The general format is ,
variable relation_operator value
Relational operators compare values and return Boolean results:
 == , Equal to.
 != , Not equal to.
 < , Less than.
 <= , Less than or equal to.
 > , Greater than.
 >= , Greater than or equal to.

5. Logical Operators
Logical Operators are used to perform "logical AND" and "logical OR"
operations, similar to AND gate and OR gate in digital electronics. They have a
short-circuiting effect, meaning the second condition is not evaluated if the first
is false.
Conditional operators are:
 &&, Logical AND: returns true when both conditions are true.
 ||, Logical OR: returns true if at least one condition is true.
 !, Logical NOT: returns true when a condition is false and vice-versa

6. Ternary operator
The Ternary Operator is a shorthand version of the if-else statement. It has
three operands and hence the name Ternary. The general format is,
condition ? if true : if false
The above statement means that if the condition evaluates to true, then execute
the statements after the '?' else execute the statements after the ':'.

7. Bitwise Operators
Bitwise Operators are used to perform the manipulation of individual bits of a
number and with any of the integer types. They are used when performing
update and query operations of the Binary indexed trees.
 & (Bitwise AND): returns bit-by-bit AND of input values.
 | (Bitwise OR): returns bit-by-bit OR of input values.
 ^ (Bitwise XOR): returns bit-by-bit XOR of input values.
 ~ (Bitwise Complement): inverts all bits (one's complement).

8. Shift Operators
Shift Operators are used to shift the bits of a number left or right, thereby
multiplying or dividing the number by two, respectively. They can be used when
we have to multiply or divide a number by two. The general format ,
number shift_op number_of_places_to_shift;
 << (Left shift): Shifts bits left, filling 0s (multiplies by a power of two).
 >> (Signed right shift): Shifts bits right, filling 0s (divides by a power of
two), with the leftmost bit depending on the sign.
 >>> (Unsigned right shift): Shifts bits right, filling 0s, with the leftmost bit
always 0.

What is scanner class? How it works? Also explain its working with one example.

You might also like