0% found this document useful (0 votes)
8 views12 pages

JavaUnit-1

The document contains important questions and answers related to Java programming, focusing on core concepts such as Object-Oriented Programming principles, the differences between JDK, JVM, and JRE, and various Java features. It also covers implementation concepts like static vs non-static methods, the use of 'this' and 'super' keywords, and dynamic binding. Additionally, it includes practical examples and programs demonstrating constructors, control statements, and recursion.

Uploaded by

Arnaymo 1
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)
8 views12 pages

JavaUnit-1

The document contains important questions and answers related to Java programming, focusing on core concepts such as Object-Oriented Programming principles, the differences between JDK, JVM, and JRE, and various Java features. It also covers implementation concepts like static vs non-static methods, the use of 'this' and 'super' keywords, and dynamic binding. Additionally, it includes practical examples and programs demonstrating constructors, control statements, and recursion.

Uploaded by

Arnaymo 1
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/ 12

JAVA IMPORTANT UNIT-1 QUESTIONS AND

ANSWERS
(By MrDnobody)
Join Community :
https://chat.whatsapp.com/DoeWwdns0fh3jZUtA
cMhaD

Core Fundamentals (High Priority)

1. Define the four pillars of Object-Oriented Programming.


The four pillars of Object-Oriented Programming (OOP) are Encapsulation,
Inheritance, Polymorphism, and Abstraction. Encapsulation means wrapping data
and methods together inside a class to protect it from outside interference. Inheritance
allows a new class to use properties and methods of an existing class, which improves
reusability. Polymorphism allows one task or method to be performed in di erent ways
depending on context. Abstraction hides unnecessary implementation details and
shows only important features. These pillars make Java reliable, secure, and e icient.

2. Di erentiate between JDK, JVM, and JRE.


The JDK (Java Development Kit) is used for developing Java programs and includes
compilers, libraries, and debugging tools. The JRE (Java Runtime Environment) is
required to run Java applications and contains libraries and JVM. The JVM (Java Virtual
Machine) executes the bytecode generated by the compiler and makes Java platform-
independent by allowing programs to run on any operating system. Together, JDK is for
development, JRE for running programs, and JVM for execution of Java code.

3. List any four characteristics of Java programming language.


Java is known for many unique features, but four major characteristics are:

1. Platform Independent – Programs can run on any system because of JVM.

2. Object-Oriented – Uses OOP concepts like classes and objects.

3. Robust – Strong memory management and exception handling.


4. Secure – Java has a strong security model with features like bytecode
verification.
These features make Java widely used in web, mobile, and enterprise
applications.

4. What is the di erence between class and object?


A class in Java is a blueprint or template that defines variables, methods, and behavior
for objects. It does not take up memory until an object is created. An object is an actual
instance of a class, created using the new keyword. For example, class Car may define
speed and color, while Car c1 = new Car(); creates an object representing a real car.
Thus, class defines the structure, while object is the usable entity.

5. Define Abstraction and Encapsulation with examples.


Abstraction means hiding implementation details and showing only essential
information. For example, in Java, using an interface hides how methods are
implemented. Encapsulation means wrapping variables and methods inside a class
and restricting direct access. This is usually done by using private variables and public
getter and setter methods. For example, a BankAccount class can hide the balance field
while allowing controlled access through methods. Together, they provide data
protection and simplify complexity in programming.

Implementation Concepts (Medium-High Priority)

6. Di erentiate between static and non-static methods.


A static method belongs to the class and can be called without creating an object. It is
mostly used for utility or common tasks, for example Math.sqrt(16). A non-static
method belongs to an instance (object) of the class and requires object creation to
access it. For example, if there is a class Student, the method displayDetails() must be
called with an object like s1.displayDetails(). Static saves memory, while non-static
works on object-specific data.

7. What is the purpose of 'this' keyword in Java?


The this keyword in Java refers to the current object of the class. It is mainly used to
di erentiate between instance variables and local variables when they have the same
name. It can also be used to call another constructor within the same class, making
code simpler. Additionally, it can pass the current object as an argument to other
methods. For example, in a class Student, using this.name = name; avoids confusion
between variables.

8. Distinguish between String and StringBu er classes.


A String in Java is immutable, meaning once created, its value cannot be changed. Any
modification creates a new object. For example, "Java" when changed produces a new
string. On the other hand, StringBu er is mutable, meaning its content can be changed
without creating new objects. For example, append("Program") modifies the same
bu er. String is useful for fixed text, while StringBu er is better for repeated changes like
in text editors or log files.

9. What is a constructor? Name its types.


A constructor is a special method in Java that initializes objects when they are created.
It has the same name as the class and no return type. Constructors are automatically
called during object creation. There are two types: Default Constructor, which takes no
arguments and assigns default values, and Parameterized Constructor, which accepts
arguments to initialize object values. For example, Student(String name, int age)
initializes values directly. Constructors make object initialization easier and more
consistent.

10. Explain the significance of 'super' keyword.


The super keyword in Java refers to the parent (super) class. It is useful in three cases:
calling the parent constructor, accessing parent class variables, and accessing
overridden parent methods. For example, when a subclass has the same variable name
as the parent, super.variable can be used to access the parent variable. Similarly,
super() is used to call the parent class constructor. This ensures proper inheritance and
avoids confusion in multi-level class structures.

Technical Concepts (Medium Priority)

11. What is dynamic binding in Java?


Dynamic binding means that method calls are resolved at runtime instead of compile
time. It occurs when a parent class reference points to a child class object, and the
method being called is determined at execution. This enables runtime polymorphism.
For example, if Animal a = new Dog(); is created, calling a.speak() will execute the Dog
class version of speak(). Dynamic binding provides flexibility and supports the concept
of overriding in Java.

12. Di erentiate between primitive and reference data types.


Primitive data types are simple, built-in types provided by Java such as int, float, char,
and boolean. They directly store values and are faster. For example, int x = 10;.
Reference data types store the memory address of objects rather than values.
Examples include arrays, strings, and objects created from classes. For example, String
name = "Java"; stores a reference to the actual string. Primitive types are lightweight,
while reference types are more flexible.

13. What is the finalize() method?


The finalize() method in Java is a special method called by the Garbage Collector before
destroying an unused object. It is mainly used to release resources such as closing files,
database connections, or network sockets. Although rarely used, it helps ensure that
resources are properly cleaned up. For example, if a file is opened in an object, the
finalize() method can ensure it is closed before the object is removed from memory.

14. Define recursion with its advantage.


Recursion in Java is a process where a method calls itself repeatedly until a specific
base condition is satisfied. It breaks a large problem into smaller sub-problems of the
same type. For example, finding factorial n! = n*(n-1)!. One main advantage of recursion
is that it reduces the length of code and makes it easier to solve problems like tree
traversal, Fibonacci sequence, and mathematical operations. However, it should be
used carefully to avoid infinite loops.

15. What is operator precedence in Java?


Operator precedence is the rule that defines the order in which operators are evaluated
in a Java expression. For example, multiplication (*) and division (/) have higher
precedence than addition (+) and subtraction (-). This means in the expression 2 + 3 * 4,
multiplication is performed first, giving 2 + 12 = 14. Without precedence, results would
vary. Operator precedence ensures consistent evaluation of expressions and avoids
logical errors in programming.

5 Mark

1. Explain the Java execution model with JDK, JVM, and JRE architecture.

Java follows the principle of “Write Once, Run Anywhere.” Its execution model is based
on three main components: JDK, JRE, and JVM.

 JDK (Java Development Kit): Provides tools for development like compiler
(javac), debugger, and libraries. It is required when writing and compiling Java
programs.

 JRE (Java Runtime Environment): Contains JVM and essential libraries for
running Java applications but does not have development tools.

 JVM (Java Virtual Machine): Responsible for executing Java bytecode. It


provides platform independence by translating bytecode into machine-specific
instructions.

Execution Process:

1. Source code (.java) is written.

2. The compiler converts it into bytecode (.class).


3. JVM reads bytecode and executes it using an interpreter or Just-In-Time (JIT)
compiler.

4. The same bytecode runs on di erent platforms because JVM abstracts the
underlying OS

class Hello {

public static void main(String[] args) {

System.out.println("Hello Java");

Diagram:
Java Source Code → javac Compiler → Bytecode → JVM (Interpreter/JIT) → OS → Output

This model makes Java secure, portable, and platform-independent.

2. Describe the four fundamental principles of OOP with examples.

Object-Oriented Programming (OOP) in Java is based on Abstraction, Encapsulation,


Inheritance, and Polymorphism.

1. Abstraction: Hiding internal details and showing only essential features.


Example: abstract class Vehicle { abstract void run(); }

2. Encapsulation: Wrapping data and methods into a single unit (class). Protects
data using private variables and getters/setters.
Example:

class Student {

private int marks;

public void setMarks(int m){ marks = m; }

public int getMarks(){ return marks; }

Inheritance: Allows one class to acquire properties of another using extends.


Example: class Dog extends Animal {}

Polymorphism: Ability of an object to take many forms. Implemented through method


overloading (compile-time) and overriding (runtime).

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

class Dog extends Animal { void sound(){ System.out.println("Bark"); } }


Real-world examples:

 Abstraction: ATM hides internal cash dispenser logic.

 Encapsulation: Bank account details hidden from users.

 Inheritance: Car is a type of Vehicle.

 Polymorphism: “+” operator works for both numbers and strings.

3. Program: Constructors and Constructor Chaining

In Java, constructors are special methods used to initialize objects. Types are:

1. Default Constructor – Provided by Java or user-defined without parameters.

2. Parameterized Constructor – Accepts arguments to initialize fields.

3. Copy Constructor – Initializes object using another object.

class Student {

int id; String name;

Student(){ id=0; name="NA"; } // default

Student(int i, String n){ id=i; name=n; } // parameterized

Student(Student s){ id=s.id; name=s.name; } // copy

Constructor Chaining:
It is calling one constructor from another using this() or super().

class A {

A(){ this(5); }

A(int x){ System.out.println("Value: " + x); }

Importance: Constructor chaining reduces code repetition and ensures all


constructors initialize object fields consistently.

This helps in reusability and clarity.

4. Explain the concept of static keyword in Java with program.

The static keyword is used for class-level members, meaning they belong to the class
rather than objects.
1. Static Variables: Shared among all objects.

2. Static Methods: Can be called without creating objects.

3. Static Blocks: Used for initialization, executed once when the class is loaded.

class Counter {

static int count = 0; // static variable

Counter(){ count++; }

static void show(){ System.out.println("Count: " + count); }

static { System.out.println("Class Loaded"); }

class Test {

public static void main(String[] args){

new Counter(); new Counter();

Counter.show();

Execution Order:

1. Static block executes first when class loads.

2. Then constructors run as objects are created.

3. Static methods can be called directly using class name.

Advantages: Saves memory, useful for utility functions (like Math.sqrt()).

5. Compare String and StringBu er with program.

String: Immutable class (once created, cannot be changed). Operations like


concatenation create new objects. E icient when values do not change often.

StringBu er: Mutable class. Can modify content without creating new objects. Better
for heavy modifications like appending inside loops.

class Demo {

public static void main(String[] args){

String s1 = "Java";
s1.concat(" World"); // new object created

System.out.println(s1); // prints "Java"

StringBu er sb = new StringBu er("Java");

sb.append(" World"); // modifies same object

System.out.println(sb); // prints "Java World"

When to use:

 Use String when values are constant.

 Use StringBu er/StringBuilder when frequent modifications are needed.

Performance-wise, StringBu er is faster in loops, while String is simple for read-only


text.

6. Demonstrate usage of this and super keywords.

 this keyword: Refers to the current object. Used to di erentiate between


instance and local variables, call current class methods/constructors.

 super keyword: Refers to parent class object. Used to call parent class
constructors and overridden methods.

class Animal {

String name="Animal";

void display(){ System.out.println("I am Animal"); }

class Dog extends Animal {

String name="Dog";

void display(){

System.out.println(this.name); // Dog

System.out.println(super.name); // Animal

super.display(); // calls parent method

}
}

class Test {

public static void main(String[] args){ new Dog().display(); }

Both this and super resolve ambiguity in inheritance. this() can also call another
constructor in the same class, while super() must be the first call in a subclass
constructor.

7. Program: Control Statements in Java

Control statements guide the flow of execution.

1. If-else: Conditional branching.

2. Switch-case: Multi-way branching.

3. Loops: For, While, Do-While.

class ControlDemo {

public static void main(String[] args){

int n=3;

if(n%2==0) System.out.println("Even");

else System.out.println("Odd");

switch(n){

case 1: System.out.println("One"); break;

case 2: System.out.println("Two"); break;

default: System.out.println("Other");

for(int i=1;i<=3;i++) System.out.println(i);

int j=1; while(j<=3){ System.out.println(j); j++; }

}
Flow of Execution:

 If-else checks condition first.

 Switch jumps directly to the matching case.

 Loops repeat instructions until condition fails.

These statements make programs dynamic and logical.

8. Explain dynamic binding and method overriding.

 Dynamic Binding: Also called late binding, it decides which method to call at
runtime.

 Method Overriding: A subclass provides its own version of a method already


defined in parent class. Dynamic binding is achieved through overriding.

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

class Dog extends Animal { void sound(){ System.out.println("Bark"); } }

class Test {

public static void main(String[] args){

Animal a = new Dog(); // upcasting

a.sound(); // Bark (runtime decision)

Here, JVM decides at runtime that Dog’s version of sound() should be executed.

Advantages:

 Supports runtime polymorphism.

 Makes code flexible and reusable.

9. Implement array operations and recursion.

Array Sorting Example:

import java.util.*;

class ArraySort {

public static void main(String[] args){


int[] arr={5,2,8,1};

Arrays.sort(arr);

for(int i:arr) System.out.print(i+" ");

Arrays.sort uses e icient algorithms like QuickSort/TimSort.

Factorial using Recursion:

class RecursionDemo {

static int fact(int n){

if(n==0) return 1;

return n*fact(n-1);

public static void main(String[] args){

System.out.println(fact(5)); // 120

Analysis:

 Arrays allow storage of multiple elements in one variable. Sorting organizes data
for fast access.

 Recursion solves problems by calling the function itself until base condition.

 Example uses divide-and-conquer style logic.

10. Java Data Types, Operators, and Precedence

Java supports primitive types (int, float, char, boolean) and reference types (objects,
arrays).

Operators:

1. Arithmetic: +, -, *, /, %

2. Relational: <, >, ==, !=


3. Logical: &&, ||, !

4. Assignment: =, +=, -=

5. Unary: ++, --

Operator Precedence:

 Multiplication/division have higher precedence than addition.

 Parentheses override precedence.

Example:

class TypeCasting {

public static void main(String[] args){

int a=5, b=2;

double c=(double)a/b; // type casting

System.out.println(c); // 2.5

Associativity: When operators have the same precedence, evaluation order is


decided (e.g., left to right for +).

Data types define variable size and type, operators perform actions, and precedence
rules ensure correct order of execution.

You might also like