0% found this document useful (0 votes)
11 views15 pages

Java Programming Language Features Explained

Java is a high-level, object-oriented, and platform-independent programming language known for its simplicity, robustness, and security features. Key components include JDK for development, JRE for execution, and JVM for running bytecode, allowing for the principle of 'Write Once, Run Anywhere'. The document also covers various Java concepts such as access modifiers, garbage collection, multithreading, and differences between data structures like ArrayList and LinkedList.

Uploaded by

anshdubey11303
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)
11 views15 pages

Java Programming Language Features Explained

Java is a high-level, object-oriented, and platform-independent programming language known for its simplicity, robustness, and security features. Key components include JDK for development, JRE for execution, and JVM for running bytecode, allowing for the principle of 'Write Once, Run Anywhere'. The document also covers various Java concepts such as access modifiers, garbage collection, multithreading, and differences between data structures like ArrayList and LinkedList.

Uploaded by

anshdubey11303
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

1. What is Java? Explain its features?

Ans: Java is a high-level, object-oriented, and platform-independent programming language developed


by Sun Microsystems (now owned by Oracle) in 1995. Java follows the principle of “Write Once, Run
Anywhere” (WORA) because programs written in Java can run on any machine that has the Java Virtual
Machine (JVM).

features:

 Simple – Easy to learn and use, with a syntax similar to C++ but without complex features like pointers.

 Object-Oriented – Promotes modularity, reusability, and maintainability by treating everything as an


object.

 Platform-Independent – Compiled into bytecode that runs on any system with a JVM (“Write Once,
Run Anywhere”).

 Robust – Strong memory management, automatic garbage collection, and exception handling reduce
errors and crashes.

 Secure – Eliminates unsafe constructs, supports bytecode verification, and provides a safe runtime
environment.

 Portable – Java programs can run on any operating system without modification.

 Multithreaded – Supports concurrent execution of multiple tasks for better performance.

 Distributed – Provides APIs for network-based applications and remote method invocation (RMI).

 Dynamic and Extensible – Classes and libraries can be loaded at runtime, allowing flexibility.

 High Performance – Just-In-Time (JIT) compiler converts bytecode into native code for faster
execution.

2. Difference between JDK, JRE, and JVM?

The JDK (Java Development Kit), JRE (Java Runtime Environment), and JVM (Java Virtual Machine) are
three fundamental components of Java with distinct purposes. The JDK is used by developers to write,
compile, and debug Java programs as it contains development tools like the compiler and debugger. The
JRE is used to run Java programs and provides the necessary libraries and JVM required to execute
bytecode. The JVM is the core part that interprets and executes Java bytecode, converting it into
machine code for the operating system, which ensures Java’s platform independence. So, in short, JDK is
for development, JRE is for execution, and JVM is the engine that runs Java programs.

[Link] the concept of platform independence in Java?


Java is platform-independent because it compiles code into bytecode, which can run on any
operating system using the Java Virtual Machine (JVM). Write once, run anywhere (WORA).
This means the same Java program can run on Windows, Linux, or Mac without any
modification.
The JVM acts as a bridge between bytecode and the underlying hardware, making Java truly
cross-platform.

4. Difference between compiler and interpreter.?

Feature Compiler Interpreter

Converts code Entire program at once Line by line

Output Bytecode / machine code Executes directly

Speed Faster (once compiled) Slower (interprets each time)

Error detection Detects all errors together Stops at first error

5. What is Bytecode?
Bytecode is an intermediate, platform-independent code generated by the Java compiler.
It is not machine-specific and is executed by the Java Virtual Machine (JVM).
This allows Java programs to run on any platform that has a JVM.

6. Difference between JIT Compiler and JVM:

JVM (Java Virtual


Feature JIT Compiler (Just-In-Time Compiler)
Machine)

Executes Java bytecode Converts bytecode to native machine


Purpose
on any platform code for faster execution

When it
At runtime During execution (just-in-time)
works

Interprets bytecode line Optimizes performance by compiling


Function
by line frequently used code blocks

Output Executes program directly Produces native code for the CPU

In short: JVM runs bytecode, and JIT compiler speeds it up by converting it to machine code.
7. Access Modifiers in Java:
Access modifiers control the visibility of classes, methods, and variables.
They define who can access a particular class or member (within the same class, package,
subclass, or anywhere).
8. Difference between public, private, protected, and default:

Modifier Access Level

public Accessible from anywhere

private Accessible only within the class

protected Accessible within same package and subclasses

default (no modifier) Accessible only within same package

9. What is static keyword? With example. Explain?


The static keyword is used to create class-level members (variables and methods) that are
common to all objects.
Key Points:
1. Shared Variable: If a variable is static, all objects share the same variable.
2. Class Method: Static methods can be called without creating an object.
3. Memory Efficient: Static members are stored in the method area instead of the heap, which
saves memory.

class Counter {
static int count = 0; // sabhi objects share karte hain

Counter() {
count++; // har object creation pe count badhta hai
}

static void showCount() {


[Link]("Total count: " + count);
}
}

public class Test {


public static void main(String[] args) {
Counter c1 = new Counter();
Counter c2 = new Counter();
[Link](); // Output: Total count: 2
}
}
Explanation:
 count static hai → sabhi objects share karte hain.
 showCount() static hai → bina object ke call kar sakte hain.

10. Difference between Instance Variable and Class Variable

Feature Instance Variable Class Variable (Static)

Defined Inside class, but outside methods Inside class with static keyword

Memory Each object has its own copy Shared among all objects

Access Accessed via object reference Accessed via class name (or object)

Lifetime Exists as long as the object exists Exists for the lifetime of the program

11. What is final keyword? Where can we use it?


2. Final Keyword
 Purpose: To make entities constant or immutable.
 Usage:
1. Final variable: Value cannot be changed after initialization.
2. …final int MAX = 100;
3. Final method: Cannot be overridden.
4. ..final void display() {}
5. Final class: Cannot be subclassed.
…. final class MyClass {}
12. . Difference between final, finally, and finalize

Keyword Purpose

Used with class, method, or variable to make it constant, non-overridable, or


final
immutable.

finally Block in try-catch that always executes, used for cleanup.

finalize() Method called by garbage collector before object is destroyed.

13. . Garbage Collection in Java


 Automatic process of reclaiming memory by deleting objects that are no longer referenced.
 Triggered by JVM using Garbage Collector (GC).
 Helps prevent memory leaks.
 Example:
[Link](); // Suggests JVM to run garbage collector
 Note: finalize() may be called before an object is removed.

14. Difference between Stack Memory and Heap Memory

Feature Stack Memory Heap Memory

Stores Local variables, method calls Objects and instance variables

Memory Allocation LIFO, automatic Dynamic, via new keyword

Lifetime Till method execution ends Till object is referenced

Access Fast, managed by JVM Slower, garbage collected

15. Difference between Method Overloading and Method Overriding

Feature Method Overloading Method Overriding

Same method name with Subclass provides new


Definition different parameters in the implementation for superclass
same class method

Must be different
Parameters Must be same as superclass
(number/type)

Return Type Can be same or different Must be same (or covariant)

Inheritance Not necessary Requires inheritance

Resolved at compile time Resolved at runtime (runtime


Compile/Runtime
(compile-time polymorphism) polymorphism)

Example:
// Overloading
class Example {
void show(int a) {}
void show(String s) {}
}

// Overriding
class Parent {
void display() {}
}
class Child extends Parent {
@Override
void display() {}
}
16. Constructor and Its Types
 Constructor: Special method to initialize objects.
 Rules:
o Same name as the class
o No return type
o Called automatically when object is created
Types of Constructors:
1. Default Constructor: No parameters, auto-provided if none is defined.
2. No-Arg Constructor: User-defined constructor without parameters.
3. Parameterized Constructor: Constructor with parameters to initialize objects.
17. Difference between Constructor and Method

Feature Constructor Method

Name Same as class Any name

Return Type None Must have a return type

Purpose Initialize object Perform tasks/operations

Called automatically during object Called explicitly using


Call
creation object

18. Default Constructor


 Provided by JVM automatically if no constructor is defined.
 No arguments and empty body.
Ex: class Example {
int x;
// JVM provides Example() automatically if no constructor is defined
}

19. Wrapper Classes in Java from note book.

20. 1. Difference between Primitive and Wrapper:


In Java, primitive types (like int, char, boolean) are basic data types that store simple values and
are not objects. Wrapper classes (like Integer, Character, Boolean) are object representations of
these primitives, providing methods and the ability to be used in collections. Primitives are
faster and memory-efficient, while wrappers are used when objects are required, such as in
Collections.

21. 2. Autoboxing and Unboxing:


Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper object
(e.g., int → Integer). Unboxing is the reverse process, converting a wrapper object back to its
primitive (e.g., Integer → int). This feature helps simplify code when using collections that only
accept objects.

22. 5. Why String is immutable in Java:


Strings are immutable in Java to ensure security, thread-safety, and performance. Since Strings
are widely used as keys in collections and in network/IO operations, immutability prevents
accidental or malicious changes, allows string pooling for memory efficiency, and ensures safe
sharing across multiple threads
23. . Difference between == and .equals() in Java:
 == compares reference equality, i.e., whether two references point to the same object in
memory.
 .equals() compares content equality, i.e., whether the values or content of two objects are the
same.

24. Difference between String, StringBuffer, and StringBuilder:


In Java, String, StringBuffer, and StringBuilder are used to store sequences of characters, but
they differ in mutability and thread-safety. A String is immutable, meaning once it is created, its
value cannot be changed; any modification creates a new String object. StringBuffer is mutable
and thread-safe, allowing multiple threads to safely modify it, but this makes it slightly slower.
StringBuilder is also mutable but not thread-safe, making it faster than StringBuffer in single-
threaded scenarios.
Ex: public class Main {
public static void main(String[] args) {
// String (immutable)
String str = "Hello";
[Link](" World"); // Does not change str
[Link]("String: " + str); // Output: Hello

// StringBuffer (mutable, thread-safe)


StringBuffer sb = new StringBuffer("Hello");
[Link](" World"); // Modifies the same object
[Link]("StringBuffer: " + sb); // Output: Hello World

// StringBuilder (mutable, not thread-safe)


StringBuilder sbd = new StringBuilder("Hello");
[Link](" World"); // Modifies the same object
[Link]("StringBuilder: " + sbd); // Output: Hello World
}
}Explanation:
 String: Original value doesn’t change because it’s immutable.
 StringBuffer: Changes are applied to the same object safely in multi-threaded programs.
 StringBuilder: Changes are applied to the same object faster in single-threaded programs.

25. 1. Packages in Java:


A package in Java is a namespace that organizes classes and interfaces into a folder-like
structure. It helps avoid name conflicts, makes code modular, and provides access protection.
Java provides built-in packages like [Link], [Link], and also allows creating user-defined
packages.

26. Import statement in Java:


The import statement is used to bring other classes or packages into the current Java file so
that their methods and variables can be used without fully qualifying their names. For example,
import [Link]; allows you to use ArrayList directly instead of writing [Link].

27. Difference between Array and ArrayList:


An Array has a fixed size, can store primitive types and objects, and has less flexibility. An
ArrayList is resizable, can only store objects, provides built-in methods like add(), remove(), and
offers better dynamic management of elements.

28. 5. Set, List, and Map in Java:


 List: An ordered collection that allows duplicate elements and maintains insertion order, e.g.,
ArrayList, LinkedList.
 Set: A collection that does not allow duplicates and does not maintain any specific order, e.g.,
HashSet, LinkedHashSet.
 Map: A collection of key-value pairs where each key is unique, and values can be duplicated,
e.g., HashMap, TreeMap.

29. diff b/w collection and framework?


In Java, a Collection is an interface that represents a group of objects, providing methods to
store, retrieve, and manipulate them. It is part of the Java Collections Framework (JCF). A
Framework, on the other hand, is a broader concept—it is a predefined architecture or set of
classes and interfaces that provides ready-to-use functionality and standard ways to build
applications.
30. Multithreading in Java:
Multithreading is a core feature of Java that allows a program to execute multiple threads
simultaneously. A thread is the smallest unit of execution in a program, and multithreading
helps in parallel execution, improving performance and responsiveness. Java provides two ways
to create threads:
1. Extending the Thread class
2. Implementing the Runnable interface
Multithreading is commonly used in real-time applications, such as games, web servers, or GUI
applications, where multiple tasks need to run concurrently.
class MyThread implements Runnable {
public void run() {
for (int i = 1; i <= 5; i++) {
[Link]([Link]().getName() + " : " + i);
}
}
}

public class Main {


public static void main(String[] args) {
Thread t1 = new Thread(new MyThread(), "Thread-1");
Thread t2 = new Thread(new MyThread(), "Thread-2");

[Link](); // starts Thread-1


[Link](); // starts Thread-2
}
}
Explanation:
 We create a class MyThread implementing Runnable and override the run() method.
 Two threads t1 and t2 are created and started using start().
 Both threads execute concurrently, printing numbers 1 to 5.

31. Difference between HashMap and Hashtable:


Both HashMap and Hashtable store data as key-value pairs, but HashMap is non-synchronized
and allows one null key and multiple null values, making it faster. Hashtable is synchronized,
thread-safe, and does not allow null keys or values. HashMap is generally preferred in single-
threaded applications, while Hashtable is legacy and rarely used today.

32. . Difference between ArrayList and LinkedList:


ArrayList is backed by an array, provides fast random access (O(1)), but slow insertions and
deletions in the middle (O(n)). LinkedList is doubly-linked, so insertions and deletions are faster
(O(1) at ends or when node reference is known), but random access is slower (O(n)). ArrayList is
better for read-heavy operations, LinkedList for write-heavy operations.

33. Difference between HashSet and TreeSet:


HashSet stores elements in no particular order, allows one null element, and is faster (O(1) for
add, remove, contains). TreeSet stores elements in sorted order according to natural ordering or
a comparator, does not allow null elements, and is slower (O(log n) for operations) because it
uses a Red-Black tree internally.

34. HashMap vs ConcurrentHashMap:


 HashMap is not thread-safe and should not be used in multithreaded environments.
 ConcurrentHashMap is thread-safe, allows concurrent read/write operations, and is faster than
Hashtable in multi-threaded use.
 Nulls: HashMap allows one null key, ConcurrentHashMap allows no null keys or values.

35. 1. Difference between throw and throws:


 throw is used inside a method to explicitly throw an exception (e.g., throw new IOException();).
 throws is used in a method declaration to indicate which exceptions the method might throw,
allowing the caller to handle them (e.g., public void readFile() throws IOException).

36. . Explain try-catch-finally in Java:


The try block contains code that might throw exceptions. The catch block handles specific
exceptions thrown by the try block. The finally block contains code that always executes,
regardless of whether an exception occurred, typically used for cleanup tasks like closing files or
releasing resources.

37. Difference between Checked and Unchecked Exceptions:


 Checked exceptions are checked at compile-time and must be either handled using try-catch or
declared with throws (e.g., IOException).
 Unchecked exceptions occur at runtime, do not need to be declared or caught (e.g.,
NullPointerException, ArithmeticException).

38. What are Threads in Java:


A thread is the smallest unit of execution in a Java program. Multithreading allows multiple
threads to run concurrently, improving performance and responsiveness. Threads can be
created by extending Thread or implementing Runnable.

39. Difference between Process and Thread:


 Process: Independent program execution with its own memory and resources. Communication
between processes is costly.
 Thread: Lightweight subunit of a process sharing the same memory. Multiple threads in a
process run concurrently and are cheaper to create and manage.

40. 2. What are OOP principles in Java?


Answer:
Four pillars of OOP in Java:
1. Encapsulation – Binding data and methods together.
2. Inheritance – Reusing code from a parent class.
3. Polymorphism – One task, different implementations.
4. Abstraction – Hiding implementation, showing only functionality.

41. Difference between Abstract Class and Interface in Java

Feature Abstract Class Interface

Can have abstract and Java 7: Only abstract methods;


Methods concrete (with body) Java 8+: can have default & static
methods methods

Can have instance variables,


Fields/Variables Only public static final (constants)
static, final, non-final

Constructor Can have constructors Cannot have constructors

Supports single inheritance Supports multiple inheritance


Inheritance
(extends only one class) (implements multiple interfaces)

Access Methods can be private, Methods are public by default


Modifiers protected, public (except private/default in Java 9+)

Use when classes share Use to define a contract that


Use Case
common behavior/state multiple classes can implement

Ex:
// Interface
interface Vehicle {
void run(); // abstract method
default void fuel() {
[Link]("Vehicle needs fuel"); // default method
}
}

// Abstract Class
abstract class Car {
void start() {
[Link]("Car started");
}
abstract void drive(); // abstract method
}

// Concrete Class implementing Interface & extending Abstract Class


class Honda extends Car implements Vehicle {
@Override
void drive() {
[Link]("Honda is driving");
}
@Override
public void run() {
[Link]("Honda is running");
}
}

public class Test {


public static void main(String[] args) {
Honda h = new Honda();
[Link](); // from abstract class
[Link](); // abstract method implemented
[Link](); // interface method implemented
[Link](); // default method from interface
}
}
Output:
Car started
Honda is driving
Honda is running
Vehicle needs fuel
Key Point:
 Abstract Class → “partially implemented class”
 Interface → “contract to implement”

42. Q13. Difference between Abstract Class and Concrete Class?


 Abstract: Cannot be instantiated.
 Concrete: Can be instantiated.

43. Q15. Can we overload main() method?


✅ Yes, but JVM calls only public static void main(String[] args).

Q44. Can we override static methods?


❌ No. Static methods belong to class, not object.
Q45. Can we make a constructor final?
❌ No, because constructors are never inherited.

Q46. What is Marker Interface in Java?


 Interface with no methods (e.g., Serializable, Cloneable).

Q47. Difference between Abstract Method and Virtual Method?


 Abstract: No body, must be implemented.
Virtual (default in Java): Can be overridden.

48. What is String Pool in Java?


Answer:
 String Pool (or String Constant Pool) is a special area in the heap memory where Java stores
string literals to save memory.
 Purpose: Avoid creating duplicate string objects; multiple variables can point to the same string
in the pool.
public class Test {
public static void main(String[] args) {
String s1 = "Java"; // String literal, goes to pool
String s2 = "Java"; // Points to same object in pool
String s3 = new String("Java"); // New object in heap
String s4 = [Link](); // Returns reference from pool

[Link](s1 == s2); // true


[Link](s1 == s3); // false
[Link](s1 == s4); // true
}
}
Output:
true
false
true

49. Q24. Difference between super keyword and this keyword

Feature super this

Use Refers to parent class object Refers to current class object

Access parent class Access current class


Access
methods/constructors/variables variables/methods/constructors
Feature super this

Constructor this() calls current class


super() calls parent constructor
Call constructor

Inheritance Only used in subclass Used in same class

Ex: class Parent {


int x = 10;
void show() { [Link]("Parent show"); }
}

class Child extends Parent {


int x = 20;
void show() {
[Link]("Child show");
[Link]("Parent x = " + super.x); // access parent variable
[Link](); // access parent method
}
}

public class Test {


public static void main(String[] args) {
Child c = new Child();
[Link]();
}
}

50 Explain Lambda Expression in Java


Answer:
 Lambda expressions are anonymous functions that provide concise way to implement
functional interfaces (interfaces with a single abstract method).
 Introduced in Java 8.

51. Explain Generic Classes in Java


Answer:
 Generics allow type-safe classes, interfaces, and methods.
 They help avoid casting and runtime errors by enforcing type checking at compile time.
Key Points:
 <T> → Type parameter (can be any type).
 Ensures compile-time type safety.
 Works with classes, methods, and interfaces.

You might also like