Java Programming Basics Explained
Java Programming Basics Explained
BASIC
SIMPLIFIED COMPUTER
1|Page
What is Java?
• Java is a programming language and a platform. Java is a high level, robust, object-
oriented and secure programming language.
• Java was developed by Sun Microsystems (now a subsidiary of Oracle) in 1995.
James Gosling is known as the father of Java. Before Java was named Java, it was
called Oak. Since Oak was already a registered company, James Gosling and his
team changed the name to Java.
• Platform: Any hardware or software environment in which a program runs, is known
as a platform. Since Java has a runtime environment (JRE) and API, it is called a
platform.
• Java is platform independent → which means it can run in any platform that support
java.
Application
1. Desktop Applications such as Eclipse Idle, media player, NetBeans Idle, etc.
5. Smart Card
6. Robotics
Features of Java
Simple Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language because:
➢ Java syntax is based on C++ (so easier for programmers to learn it after C++).
➢ Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
➢ There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.
2|Page
Java embraces object-oriented principles :
It structures programs as a collection of interacting objects. In Java, almost everything is treated
as an object—each encapsulating both data and behavior. This approach allows developers to
model real-world entities more naturally, promoting modularity, reusability, and clarity in
software design.
Platform Independent :
➢ Java programs can run on any system that has a Java Virtual Machine (JVM),
regardless of the underlying hardware or operating system. Java achieves this by
compiling source code into bytecode, which is an intermediate, machine-
independent format. This bytecode is then interpreted or executed by the JVM on
any platform, ensuring consistent behavior across Windows, macOS, Linux, and
others. This “write once, run anywhere” capability is a key feature that distinguishes
Java from many other programming languages.
3|Page
Secure :
Java is widely recognized for its strong security architecture. It enables developers to build
robust, virus-resistant applications. Java’s security model is built into the language and
runtime environment, offering multiple layers of protection.
Key features contributing to Java’s security include:
• No explicit pointers – This eliminates direct memory access, reducing the risk of
unauthorized data manipulation.
• Bytecode verification – Ensures code integrity before execution.
• Sandboxing via the JVM – Java programs run inside a controlled virtual machine
environment, isolating them from the host system and preventing harmful
operations.
• Security Manager and API – Allows fine-grained access control over system
resources.
Robust :
The term “robust” refers to strength and reliability. Java is considered robust because it
emphasizes early error detection, strong memory management, and runtime checking.
Java’s robustness is supported by several key features:
• Strong type checking – Errors are caught at compile time, reducing runtime
failures.
• Automatic garbage collection – Frees unused memory, preventing memory leaks.
• Exception handling – Allows graceful recovery from unexpected errors.
• No explicit pointers – Eliminates direct memory access, reducing the risk of system
crashes.
Here’s a refined, textbook-style explanation of the First Java Program, structured clearly
and aligned with how academic sources typically present it:
A basic Java program begins with the main() method, which serves as the entry point for
execution. Here's a breakdown of its key components:
🔹 class
• A class is a blueprint for creating objects and encapsulates data and behavior.
4|Page
🔹 public
• When applied to the main() method, it ensures that the method is accessible to the
Java Virtual Machine (JVM) from outside the class.
🔹 static
• Declaring a method as static means it belongs to the class rather than an instance.
• The JVM calls the main() method without creating an object, which saves memory
and simplifies execution.
🔹 void
🔹 main
🔹 [Link]()
• out is a static member of System, representing the standard output stream (an
instance of PrintStream).
• println() is a method of PrintStream that prints the argument and moves the cursor
to a new line.
5|Page
What happens at runtime?
Absolutely, Anshuman! Here's the refined version of your Java runtime explanation, now
without chapter references but still grounded in the concepts found in Java: The Complete
Reference by Herbert Schildt:
In Java, runtime refers to the phase when a compiled program is actively executing inside
the Java Virtual Machine (JVM). This is distinct from compile time, when source code is
translated into bytecode.
📦 Class Loading
• The JVM interprets bytecode or compiles it into native machine code using a Just-In-
Time (JIT) compiler.
6|Page
🧮 Memory Management
🔀 Thread Management
🖥️ OS Interaction
🚨 Exception Handling
• Java uses structured exception handling (try, catch, finally) to manage runtime
errors.
• The JVM throws exceptions when unexpected conditions arise, allowing programs to
recover or terminate gracefully.
🧹 Shutdown Hooks
• Before the JVM exits, it can run shutdown hooks—custom threads registered to
perform cleanup tasks.
• These are useful for saving state, closing resources, or logging final messages.
7|Page
Difference between JDK, JRE, and JVM
In the Java programming language, a variable serves as a symbolic name for a memory
location that stores data during the execution of a program. Each variable is associated
with a specific data type, which determines the kind of values it can hold. Variables are
fundamental to the structure and behavior of Java programs, enabling dynamic data
manipulation and state management.
Java categorizes variables into three primary types based on their scope and lifecycle:
local variables, instance variables, and static variables.
8|Page
• Local Variables
A local variable is declared within the body of a method, constructor, or block. Its
scope is confined strictly to the enclosing structure, meaning it is accessible only
during the execution of that specific method or block. Other methods within the
class have no visibility of the local variable.
• Instance Variables
An instance variable is declared within a class but outside the body of any method
or constructor. These variables are associated with individual objects created from
the class. Each object maintains its own copy of the instance variable, allowing for
unique state representation across instances.
9|Page
• Static Variables
A static variable is declared using the static keyword within a class but outside any
method or constructor. Unlike instance variables, static variables belong to the
class itself rather than any specific object. As such, only one copy of a static
variable exists, and it is shared among all instances of the class.
10 | P a g e
Type Description Default Value Size
1 bit (JVM-
boolean Represents logical values false dependent)
char Represents a single Unicode character '\u0000' 2 bytes
byte 8-bit signed integer 0 1 byte
short 16-bit signed integer 0 2 bytes
int 32-bit signed integer 0 4 bytes
long 64-bit signed integer 0L 8 bytes
float 32-bit IEEE 754 floating-point 0.0f 4 bytes
double 64-bit IEEE 754 floating-point 0.0d 8 bytes
• Arrays: Fixed-size containers that hold multiple values of the same type.
Summary
Unicode System
• Unicode in Java refers to Java's built-in support for the Unicode character encoding
standard. This means Java can represent and manipulate text from virtually all written
languages and scripts worldwide.
11 | P a g e
• The reason to uses the Unicode system to overcome the limitations of older character
encodings like ASCII, ensuring that the language can be used globally. By adopting a
single, standardized system, Java applications can handle and display text from
virtually any language or script in a consistent manner across different computers
and operating systems.
• ASCII→ American Standard Code for Information Interchange
Operators in Java:
Operators in Java are special symbols that perform operations on variables and
values. They are categorized into several types based on the operations they perform
• Unary Operator - need only one operand. They are used to increment, decrement, or
negate a value which includes “+”, “-”, “++”, “- -”, and “!”.
• Arithmetic Operators- are used to perform simple arithmetic operations on primitive
and non-primitive data types which includes “+”, “++”, “-”, “- - ”, “*”, “/”, “%”.
12 | P a g e
• Assignment Operator- '=' The 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. Which includes “+=”, “-=”, “*=”,
“/=”, “%=”, “=”.
• 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. Which
includes “==”, “!=”, “>”, “<”, “>=”, “<=”.
• 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. Operators
are “&&”, “||”, “!”.
• Ternary Operator- is a shorthand version of the if-else statement. It has three
operands and hence the name Ternary. The format to write Ternary is
condition ? if true : if false .
• 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 and the operators are “&”, “|”, “^”,
“~”.
• 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 “<<”, “>>”, “>>>”.
• Instance of operator is used for type checking. It can be used to test if an object is
an instance of a class, a subclass, or an interface. The general format
object instance of class/subclass/interface
13 | P a g e
14 | P a g e
Java Keywords and Program Flow Essentials
Java Keywords
• Definition: Java keywords, also known as reserved terms, are pre-assigned words
that act as critical triggers in code, prohibiting their use as variable, object, or class
identifiers.
• Role: Serve as foundational elements for Java programming, defining specific
operations and behaviors.
Decision-Making Constructs:
• if Constructs: Evaluate conditions to direct flow, yielding a Boolean (true or false)
result.
• if-else Constructs: Extend if with an alternative block for false conditions.
• if-else-if Ladder: Chains multiple conditions for varied execution paths.
• Nested if Constructs: Embed if or if-else within others for complex decision trees.
• switch Construct: Executes a specific case based on a variable's value, similar to
if-else-if chains.
Iteration Constructs:
• do-while Construct: Runs the loop body at least once before checking the
condition, known as an exit-controlled loop.
• while Construct: Repeats statements when iteration count is unknown upfront.
• for Construct: Combines initialization, condition, and update in one line, ideal for
known iteration counts (like C and C++).
• for-each Construct: Simplifies traversal of arrays or collections without manual
indexing.
Jump Constructs:
• break Construct: Exits the current loop or switch, moving to the next statement.
• continue Construct: Skips the current iteration and proceeds to the next loop
cycle.
15 | P a g e
Question For Practice
1. Explain why Java is called *platform independent*. What role does the JVM play in
this?
2. Write a simple Java program to print `"Hello, Java!"`. Break down each keyword
(`class`, `public`, `static`, `void`, `main`, `String[] args`).
3. Differentiate between **JDK**, **JRE**, and **JVM** with one example use-case
each.
4. Explain the difference between **heap** and **stack** memory in Java with an
example scenario.
5. Define local, instance, and static variables. Write a Java code snippet that
demonstrates all three in a single program.
6. Why is Java called *strongly typed*? List all 8 primitive data types with size and
default values.
7. Write a Java program to show the difference between `==` and `.equals()` when
comparing strings.
8. Write a Java program that uses a **switch statement** to print the day of the week
given a number (1 = Monday, … 7 = Sunday).
9. Write a Java program to calculate the factorial of a number using both a `for` loop
and a `while` loop.
10. Explain how Java handles runtime errors. Write a short program using `try-catch-
finally` to handle division by zero.
Test-1
[Link]/14819106
16 | P a g e
OOPs (Object-Oriented Programming System)
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology to design a program using classes and objects.
Means solving real world problems focusing on objects related to it. It simplifies software
development and maintenance by providing some concepts:
➢ Class
➢ Object
➢ Inheritance
➢ Polymorphism
➢ Abstraction
➢ Encapsulation
What is Class?:
Class is a Blueprint or a Logical structure for Objects.
If you see the above picture where class is Fruit, which is a Logical structure or Blueprint
for all the Objects such as:
• Banana
• Apple
• Grapes
• Watermelon
17 | P a g e
What is Object?
Object is an instance of a class and it instantiates the class.
It contains attributes in the form of Data Members and behavior in the form of Methods
or Member Functions.
Polymorphism:
➢ One interface for many forms or methods.
18 | P a g e
Inheritance: Acquiring properties or traits from a parent class.
Encapsulation: Wrapping up of data and code together.
Abstraction: Specifies essential features and hides all other details.
Interface: A connection or contract between classes or other interfaces.
Coupling :Coupling refers to the knowledge or information or dependency of another
class. It arises when classes are aware of each other.
Association: Association represents the relationship between the objects. Here, one
object can be associated with one object or many objects.
Constructors
➢ a constructor is a special type of method used to initialize objects when they are
created. It is invoked automatically when a new instance of a class is created using
the new keyword.
➢ A constructor must have the same name as the class it belongs to.
➢ Unlike regular methods, a constructor does not have any return type, not
even void. Its purpose is to initialize the object, not to return a value
➢ When an object of a class is created, the constructor is called automatically to
initialize the object’s [Link] are primarily used to set the initial
state or values of an object’s attributes when it is created.
19 | P a g e
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
Default Constructor:
➢ a default constructor is a special type of constructor that is automatically provided
by the Java compiler if no explicit constructors are defined within a class.
20 | P a g e
Features Constructor Method
Purpose Constructors are used to initialize objects Methods are used to perform operations
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.
21 | P a g e
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.
Constructor Overloading
➢ Constructor overloading in Java is a feature that allows a class to have multiple
constructors with the same name (which is the class name) but different parameter
22 | P a g e
lists. This enables objects of the class to be initialized in various ways, providing
flexibility in object creation.
➢ A class can define multiple constructors.
➢ All overloaded constructors must share the same name as the class, but their
parameter lists must differ. This difference can be in the number of parameters, the
data types of the parameters, or the order of the parameter types.
➢ Constructors including overloaded ones, do not have a return type not even void.
➢ Constructor overloading provides different ways to initialize an object based on the
specific needs at the time of object creation.
23 | P a g e
• The static variable gets memory only once in the class area at the time of
class loading.
• A static method belongs to the class rather than the object of a class.
• A static method can be invoked without the need for creating an instance of a class.
• A static method can access static data member and can change the value of it.
Inheritance In Java
24 | P a g e
Super Keyword:
The super keyword in Java is a reference variable that is used to refer to the parent class
when we are working with objects.
25 | P a g e
[Link] of super with class
Polymorphism in Java
➢ Polymorphism in Java is a concept by which we can perform a single action in
different ways. There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism. We can perform polymorphism in java
by method overloading and method overriding.
Runtime Polymorphism
➢ in Java Runtime polymorphism or Dynamic Method Dispatch is a process in which a
call to an overridden method is resolved at runtime rather than compile-time.
It takes place at compile time for which is referred It takes place at runtime so do it is referred to
to as early binding as late binding.
It uses overloading more precisely operator
overloading method It uses overriding methods.
It takes place using normal functions It takes place using virtual functions
Static or const or private functions use real objects
in static binding Real objects use dynamic binding.
26 | P a g e
Instanceof Keyword in Java
In Java, instanceof is a keyword used for checking if a reference variable contains a given
type of object reference or not. Following is a Java program to show different behaviors of
instanceof. Henceforth it is known as a comparison operator where the instance is getting
compared to type returning boolean true or false as in Java we do not have 0 and 1 boolean
return types.
Java Abstraction
➢ Abstraction in Java is the process of hiding internal implementation details and
showing only essential functionality to the user. It focuses on what an object does
rather than how it does it.
• Abstraction hides the complex details and shows only essential features.
➢ Java provides two ways to implement abstraction, which are listed below:
27 | P a g e
Abstract class Interface
Abstract class can have abstract and non-abstract Interface can have only abstract methods. Since Java 8,
methods. it can have default and static methods also.
Abstract class doesn't support multiple
inheritance. Interface supports multiple inheritance.
Abstract class can have final, non-final, static and
non-static variables. Interface has only static and final variables.
Abstract class can provide the implementation of Interface can't provide the implementation of abstract
interface. class.
The abstract keyword is used to declare abstract
class. The interface keyword is used to declare interface.
An abstract class can extend another Java class
and implement multiple Java interfaces. An interface can extend another Java interface only.
An abstract class can be extended using keyword An interface can be implemented using keyword
'extends'. 'implements'.
A Java abstract class can have class members like
private, protected, etc. Members of a Java interface are public by default.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
28 | P a g e
Java Fundamentals & OOP Principles
This foundational section will guide you through the core principles that govern how Java
applications are structured. We'll explore the concepts of organization, visibility, data
protection, and the object-oriented paradigms that make Java a powerful and robust
language.
package is a fundamental mechanism for organizing your code. Think of it like a folder on
your computer's file system. Just as you use folders to group related documents,
spreadsheets, and images, a Java package is used to group similar types of classes,
interfaces, and even sub-packages. This grouping is not just for neatness; it's a critical
strategy for managing complexity in large applications and preventing naming conflicts. For
instance, you could have a class named
List in your own project, and without packages, it would clash with Java's built-in List class
from the [Link] package.
Types of Packages
Built-in Packages: These are the extensive libraries that come with the Java Development
Kit (JDK). They provide a vast arsenal of pre-written, pre-tested code that developers can
use to perform common tasks without having to reinvent the wheel. There are many such
packages, including well-known ones like
[Link] (which contains fundamental classes like String and Object), [Link] (for input
and output operations), [Link] (for the Collections Framework and other utilities), and
[Link] (for database connectivity).
User-defined Packages: These are the packages that you, the developer, create to
organize your application's source code. For example, in a large e-commerce application,
you might create packages like [Link], [Link], and
[Link].
Sub-packages
To achieve an even finer level of organization, Java allows for the creation of
29 | P a g e
sub-packages, which are essentially packages inside other packages. This hierarchical
structure helps to categorize the main package further. For instance, within the
In Java,
modifiers are keywords that you add to definitions to change their meanings. There are two
primary types of modifiers:
access modifiers and non-access modifiers. This chapter focuses on the four crucial
access modifiers that control the visibility and accessibility of classes, methods, and
variables. They are the gatekeepers of your code, determining what parts of your
application can interact with other parts.
private: This is the most restrictive access level. When a member (a variable or method) is
declared
private, it can only be accessed from within the class in which it is declared. It cannot
be seen or used from outside that class, not even by other classes in the same package or
by its own subclasses.
Analogy: Think of a private variable as the thoughts in your own mind. Only you have direct
access to them.
default: If you do not explicitly write an access modifier for a member, it is given default
access by the Java compiler. The access level for a
default member is only within its own package. It cannot be accessed from any class
outside of its current package.
protected: The protected modifier is a step up in accessibility from default. Its access level
extends to everything
30 | P a g e
within the same package, and it also allows access outside the package, but only
through a child class (subclass) via inheritance. If you try to access a
protected member from a different package without it being a subclass, access will be
denied.
Analogy: A protected member is like a family recipe. It's known by everyone in the
immediate family (package), and it can be passed down to children who may move away
(subclasses in other packages), but it's not shared with the general public.
public: This is the most permissive access level. When a member is declared
public, it can be accessed from everywhere. This includes from within its own class, from
other classes within the same package, and from any class in any other package.
Analogy: A public member is like a public website or a billboard. Anyone, anywhere, can
access it.
private Y N N N
default Y Y N N
protected Y Y Y N
public Y Y Y Y
Defining Encapsulation
Encapsulation is one of the four fundamental principles of Object-Oriented Programming
(OOP). In Java, it is the process of
wrapping code and data together into a single unit. The document provides a helpful
analogy: think of a medical capsule which contains a mixture of several different
medicines, all bundled together in one package. In Java, this "capsule" is the class.
data hiding in Java, because it prevents other classes from being able to directly access
the private data members.
31 | P a g e
Advantages of Encapsulation
Complete Control Over Data: Encapsulation gives you fine-grained control over your data.
For example, if you have a variable
id, you might want to ensure it's never set to a negative number. Inside the setter method
for
id, you can write logic to validate the input value before assigning it to the variable. This
prevents the object's state from becoming corrupt.
Creating Read-Only or Write-Only Classes: You can easily control the accessibility of
your class's data. By providing only a getter method for a variable, you make that variable
effectively
write-only. You can even skip providing either method if the variable is meant for internal
use only.
Increased Flexibility and Maintainability: Because the internal representation of the data
is hidden from the outside world, you are free to change it without breaking the code that
uses your class. For example, you could change the data type of a variable, and as long as
the public getter and setter methods continue to work as expected, no other part of the
application needs to be modified.
Understanding the distinction between a class and an object is perhaps the most
fundamental concept in object-oriented programming. They are related, but they are not
the same thing.
32 | P a g e
Column1 Column2 Column3
33 | P a g e
Polymorphism, which means "many forms," is another core OOP principle. It allows a
single action to be performed in different ways. In Java, polymorphism is primarily achieved
through method overloading and method overriding. While they sound similar, they are
fundamentally different concepts.
🔢 Arrays in Java
An array is a collection of elements of the same type stored in a contiguous memory
location. In Java, arrays are objects, meaning they are created dynamically using the new
keyword.
34 | P a g e
1D Array Example
2D Array Example
35 | P a g e
✨ Strings in Java
Strings in Java are objects of the String class, stored in the String Pool (inside heap
memory). They are immutable, meaning once created, their values cannot be changed.
Creating Strings
36 | P a g e
Mutable Strings in Java
1. StringBuffer
• Thread-safe: All methods are synchronized, meaning multiple threads cannot modify it
at the same time → safe for multi-threaded environments.
Example:
37 | P a g e
2. StringBuilder
• Not thread-safe: Methods are not synchronized, so not safe in multi-threaded code.
Example:
When to use:
38 | P a g e
• Checked at compile-time → The compiler forces you to handle them using try-catch or
throws.
• Examples:
o IOException
o SQLException
o FileNotFoundException
[Link] Exceptions
• Not checked at compile-time → Occur at runtime.
• Examples:
o NullPointerException
o ArithmeticException
o ArrayIndexOutOfBoundsException
39 | P a g e
Errors
• Serious problems beyond the control of the programmer.
• Examples:
o OutOfMemoryError
o StackOverflowError
o VirtualMachineError
40 | P a g e
📦 Collections Framework
The Java Collections Framework provides classes and interfaces to store and manipulate
groups of objects. It includes List, Set, Map, and Queue interfaces with various
implementations.
ArrayList :
ArrayList is a resizable array implementation that is part of the [Link] package. Unlike
regular arrays, you don’t need to specify its size in advance; it can grow or shrink
dynamically as elements are added or removed.
• Indexed Access: ArrayList elements can be accessed using indices like arrays.
• Allows Null and Duplicates: ArrayList allows both null values and duplicate
elements.
41 | P a g e
• Maintains Insertion Order: Elements are stored in the order they are added.
HashSet
HashSet in Java implements the Set interface of Collections Framework. It is used to store
the unique elements and it doesn't maintain any specific order of elements.
42 | P a g e
1. Adding Elements in HashSet
• To add an element to the HashSet, we can use the add() method. However, the insertion
order is not retained in the HashSet. We need to keep a note that duplicate elements are
not allowed and all duplicate elements are ignored.
43 | P a g e
HashMap
A HashMap is a part of Java’s Collection Framework and implements the Map interface. It
stores elements in key-value pairs, where:
• Keys are unique. If we try to insert a duplicate, it replaces the existing value of the
corresponding key.
• Internally uses Hashing, hence allows efficient key-based retrieval, insertion, and
removal with an average of O(1) time.
• Not synchronized (unlike Hashtable in Java) and hence faster for most cases.
44 | P a g e
• Allows to store the null keys as well, but there should be only one null key object.
Multiple values can be null.
• Declaration: public class HashMap<K,V> extends AbstractMap<K,V> implements
Map<K,V>, Cloneable, Serializable
To add an element to the map, we can use the put() method. However, the insertion
order is not retained in the Hashmap. Internally, for every element, a separate hash is
generated and the elements are indexed based on this hash to make it more efficient.
After adding the elements if we wish to change the element, it can be done by again
adding the element with the put() method. Since the elements in the map are indexed
using the keys, the value of the key can be changed by simply inserting the updated
value for the key for which we wish to change.
Removing Element from Java HashMap: To remove an element from the Map, we can
use the remove() method. This method takes the key value and removes the mapping
for a key from this map if it is present in the map.
45 | P a g e
Traversal of Java HashMap: We can use the Iterator interface to traverse over any
structure of the Collection Framework. Since Iterators work with one type of data we use
Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the
next() method we print the entries of HashMap.
46 | P a g e
File Handling in Java
In Java, file handling means working with files like creating them, reading data, writing data
or deleting them. It helps a program save and use information permanently on the computer.
Byte Streams: In Java, Byte Streams are used to handle raw binary data such as
images, audio files, videos or any non-text file. They work with data in the form of 8-
bit bytes.
Character Streams: In Java, Character Streams are used to handle text data. They
work with 16-bit Unicode characters, making them suitable for international text and
language support.
47 | P a g e
Create a File
File created
Write to a File
48 | P a g e
Read from a File
Delete a File
Deleted File
49 | P a g e
Multithreading in Java
Multithreading in Java is a feature that enables a program to run multiple threads
simultaneously, allowing tasks to execute in parallel and utilize the CPU more efficiently. A
thread is a lightweight, independent unit of execution inside a program (process).
We create a class that extends Thread and override its run() method to define the task.
Then, we make an object of this class and call start(), which automatically calls run() and
begins the thread’s execution.
We create a new class which implements [Link] interface and define the run()
method there. Then we instantiate a Thread object and call start() method on this object.
Advantages
1. Improved Performance: Multiple tasks can run simultaneously, reducing execution
time.
2. Efficient CPU Utilization: Threads keep the CPU busy by running tasks in parallel.
50 | P a g e
3. Responsiveness: Applications (like GUIs) remain responsive while performing
background tasks.
4. Resource Sharing: Threads within the same process share memory and resources,
avoiding duplication.
51 | P a g e
Using Runnable keyword
52 | P a g e
Heap Area
• Heap is a shared runtime data area where objects and arrays are stored. It is
created when the JVM starts.
• JVM allows user to adjust the heap size. When the new keyword is used the
object is allocated in the heap and its reference is stored in the stack.
• There exists one and only one heap for a running JVM process.
Method Area
• Method area is a logical part of the heap and it is created when the JVM starts.
• Garbage collection of the method area is not guaranteed and depends on JVM
implementation.
JVM Stacks
• A stack is created when a thread is created and the JVM stack is used to store
method execution data, including local variables, method arguments and return
addresses.
• Stacks size can be either fixed or dynamic and it can be set when the stack is
created.
53 | P a g e
Native Method Stacks
• Native method stack is also known as C stacks.
• This memory is allocated for each thread when it is created and can have either a
fixed or dynamic size.
• Native method stacks handle the execution of native methods that interact with
the Java code.
• For non-native methods, it stores the address of the current JVM instruction.
• On some platforms, the PC can also store a return address or native pointer.
• Garbage collector finds objects that are no longer needed by the program.
• It removes those unused objects to free up the memory and making space for
new objects.
• Java uses generational garbage collection so that new objects are collected more
frequently in the young generation than older objects which survive longer in the
old generation, this helps improve efficiency.
• You can request garbage collection using [Link](), but the JVM ultimately
decides when it should run.
54 | P a g e
Java 8 Features
There are a few major Java 8 features mentioned below:
Lambda Expressions
Functional Interfaces
55 | P a g e
Method Reference
• Constructor Reference.
Streams
Stream API is introduced in Java 8 and is used to process collections of objects with
the functional style of coding using the lambda expression. So to understand what
stream API is, you must have knowledge of both lambda and functional interfaces.
Methods related to one of the most powerful features of Java Stream are mentioned
below.
Comparable and Comparator are interfaces used to order objects. They are
particularly useful in sorting operations and collections that require natural ordering.
Here we will learn about Comparable and Comparator in depth.
56 | P a g e
Date/Time API
This section gives you to handle the ever-changing world of dates and times within
your Java programs. Explore working with calendars, timestamps, and time
manipulation – essential skills for building applications that deal with deadlines,
scheduling, or even historical data analysis.
1. Why is Java considered more secure than C++? Explain with at least two features.
2. Differentiate between final, finally, and finalize() in Java.
3. What is typecasting in Java? Give an example of both widening and narrowing
conversions.
4. Write a Java snippet to demonstrate constructor overloading.
5. Explain the difference between shallow copy and deep copy in Java.
6. Define dynamic binding with a short code example.
7. Explain how Java achieves memory safety without using explicit pointers.
8. What is the role of the classloader in JVM?
9. Give one real-life example for aggregation and composition.
10. What is the difference between StringBuilder and StringBuffer in terms of
synchronization?
11. Write a short code snippet showing the use of this() constructor call in Java.
12. Differentiate between throw and throws with syntax.
13. Why are Java interfaces considered to support multiple inheritance?
14. Give one use case of the volatile keyword in multithreading.
15. What is autoboxing and unboxing in Java? Give one example each.
16. Differentiate between instance variables and static variables with examples.
17. What is the purpose of the instanceof operator in Java? Write a short code snippet.
18. Explain the use of the default keyword in interfaces (Java 8 feature).
19. What is the difference between compile-time error and runtime error in Java? Give
one example each.
20. Write a short Java code to demonstrate the ternary operator.
57 | P a g e
Question (5marks each)
1. Compare abstract classes and interfaces in Java with suitable code examples.
2. Explain method overriding and show with a code snippet how runtime
polymorphism works.
3. Discuss how JVM manages heap and stack memory during program execution
with a diagram.
4. Write a Java program to demonstrate the difference between == and .equals()
when comparing wrapper objects.
5. Explain how access modifiers affect inheritance across packages with an
example.
6. What is the difference between checked, unchecked exceptions, and errors in
Java? Give one example for each.
7. Compare ArrayList, HashSet, and HashMap in terms of order, duplication, and
null values.
8. Write a Java program to create two threads using Runnable interface and Thread
class, showing the difference.
9. Discuss the life cycle of a thread in Java with a neat labeled diagram.
10. Explain the working of the garbage collector in Java with the concept of
generational GC.
11. Write a Java program to demonstrate synchronized methods for preventing race
conditions.
12. Explain the role of lambda expressions and method references in Java 8 with
examples.
13. Write a program that sorts a list of custom Student objects using both
Comparable and Comparator.
14. How does the Stream API improve performance in data processing? Illustrate
with a code example using filter() and map().
15. Explain JDK vs JRE vs JVM in detail with a diagram showing their relationship.
16. Explain the difference between static binding and dynamic binding in Java with
suitable examples.
17. Write a Java program to demonstrate the use of the super keyword with variables,
methods, and constructors.
18. Compare HashMap vs Hashtable in Java in terms of synchronization, null handling,
and performance.
19. Describe the Java Memory Model (JMM). Explain how it ensures visibility and
ordering of variables in a multithreaded environment.
20. Write a program to demonstrate file handling in Java: create a file, write content
into it, and then read it back.
58 | P a g e
Gmail: shuvamsahoo1234@[Link]
Website: [Link]
Instagram 1 : [Link]
Instagram 2 : [Link]
59 | P a g e