[Go to site: main page, start]

0% found this document useful (0 votes)
15 views60 pages

Java Programming Basics Explained

The document provides an overview of Java programming, covering its definition, features, and applications. It discusses key concepts such as object-oriented programming, data types, and the differences between JDK, JRE, and JVM. Additionally, it explains Java's runtime environment, memory management, and control mechanisms for program flow.
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)
15 views60 pages

Java Programming Basics Explained

The document provides an overview of Java programming, covering its definition, features, and applications. It discusses key concepts such as object-oriented programming, data types, and the differences between JDK, JRE, and JVM. Additionally, it explains Java's runtime environment, memory management, and control mechanisms for program flow.
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

JAVA PROGRAMMING

BASIC

SIMPLIFIED COMPUTER

Simplified Computer, kalpana flat area, plot 2212, Kalpana Square,


Laxmisagar, Bhubaneswar, Odisha 751006

Written By: Shuvam Sahoo


Content
Serial No. Topic
1. What is java
2. Object-Oriented Programming System (OOPS)
3. Inheritance
4. Access Specifiers
5. Abstraction
6. Polymorphism
7. Thread
8. Datatypes
9. Wrapper Class
10. Final Keyword

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.

2. Web Applications such as Netflix , Amazon ,LinkedIn ,etc.

3. Enterprise Applications such as banking applications.

4. Mobile, Games, Software

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:

📘 Understanding the First Java Program

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

• The class keyword is used to declare a class in Java.

• A class is a blueprint for creating objects and encapsulates data and behavior.

4|Page
🔹 public

• public is an access modifier that defines visibility.

• 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

• void is the return type of the method.

• It indicates that the method does not return any value.

🔹 main

• main is the starting point of any standalone Java application.

• The JVM looks for this method signature to begin execution.

🔹 String[] args or String args[]

• This parameter allows the program to accept command-line arguments.

• It is an array of String objects passed to the main() method at runtime.

🔹 [Link]()

• Used to print output to the console.

• System is a predefined class.

• 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:

🧠 Java Runtime: A Conceptual Breakdown

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 dynamically loads .class files as needed.

• It verifies bytecode integrity and prepares classes for execution.

• This includes linking, initializing static blocks, and resolving dependencies.

⚙️ Bytecode Execution & JIT Compilation

• The JVM interprets bytecode or compiles it into native machine code using a Just-In-
Time (JIT) compiler.

• JIT improves performance by optimizing frequently executed code paths.

6|Page
🧮 Memory Management

• Heap: Stores dynamically created objects.

• Stack: Manages method calls, local variables, and primitive types.

• Garbage Collection: Automatically reclaims memory from objects no longer in use,


preventing leaks and fragmentation.

🔀 Thread Management

• Java supports multithreading natively.

• The JVM handles thread scheduling, synchronization, and lifecycle management.

• Threads can run concurrently, improving responsiveness and performance.

🖥️ OS Interaction

• The JVM abstracts the operating system, enabling platform-independent access to


system resources.

• This includes file I/O, networking, and hardware communication.

🚨 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

Aspect JDK JRE JVM

Purpose Used to develop Java Used to run Java Executes Java


applications applications bytecode

Platform Platform-dependent (OS Platform-dependent JVM is OS-specific, but


Dependency specific) (OS specific) bytecode is platform-
independent
JRE + Development tools JVM + Libraries (e.g., ClassLoader, JIT
(javac, debugger, etc.) [Link]) Compiler, Garbage
Includes
Collector

Writing and compiling Running a Java Convert bytecode into


Java code application on a native machine code
Use Case
system
📘 Java Variables: A Conceptual Overview

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.

Data Types in Java


In the Java programming language, data types define the nature of values that variables can
hold, as well as the amount of memory allocated for those values. Java is a strongly typed
and statically typed language, meaning every variable must be declared with a specific data
type, and type checking is enforced at compile time.

Java categorizes data types into two broad classes:

1. Primitive Data Types


Primitive data types are the most fundamental building blocks of data representation in Java.
They store simple values directly in memory and are not objects. Java defines eight primitive
types, each with a fixed size and range:

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

2. Non-Primitive Data Types (Reference Types)


Non-primitive data types, also known as reference types, refer to objects and store memory
addresses rather than raw values. These types are derived from classes and support
methods, inheritance, and polymorphism.

Common non-primitive types include:

• Classes: User-defined or built-in blueprints for creating objects.

• Interfaces: Abstract types that define method contracts without implementation.

• 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.

Java Control Mechanisms


Overview: Java provides three main categories to manage program flow: decision-making,
iteration, and jump constructs.

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

A class contains Data Members, which are attributes or properties of objects.


Examples of data members:

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.

1. Method Overloading: Also, known as compile-time polymorphism, is the


concept of Polymorphism where more than one method share the same
name with different signature(Parameters) in a class. The return type of these
methods can or cannot be same.
2. Method Overriding: Also, known as run-time polymorphism, is the concept
of Polymorphism where method in the child class has the same name,
return-type and parameters as in parent class. The child class provides the
implementation in the method already written.

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.

Cohesion: Cohesion refers to the level of a component which performs a single


welldefined task. A single well-defined task is done by a highly cohesive method.

Association: Association represents the relationship between the objects. Here, one
object can be associated with one object or many objects.

Aggregation: Aggregation is a way to achieve Association. Aggregation represents the


relationship where one object contains other objects as a part of its state.

Composition :The composition is also a way to achieve Association. The composition


represents the relationship where one object contains other objects as a part of its state.

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.

• 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.

20 | P a g e
Features Constructor Method

Constructors must have the same name as


Name the class name Methods can have any valid name

Return Methods have the return type or void if does not


Type Constructors do not return any type return any value.

Constructors are called automatically with


Invocation new keyword Methods are called explicitly

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.

Java static keyword


The static keyword in Java is used for memory management mainly. We can apply static
keyword with variables, methods, blocks and nested classes. The static keyword belongs
to the class than an instance of the class.

1)Java static variable


• If you declare any variable as static, it is known as a static variable. 。
• The static variable can be used to refer to the common property of all objects
(which is not unique for each object), for example, the company name of
employees, college name of students, etc.

23 | P a g e
• The static variable gets memory only once in the class area at the time of
class loading.

2) Java static method


If you apply static keyword with any method, it is known as static method.

• 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.

3) Java static block


• Is used to initialize the static data member.
• It is executed before the main method at the time of classloading.

Java this Keyword


In Java, "this" is a reference variable that refers to the current object, or can be said "this" in
Java is a keyword that refers to the current object instance. It is mainly used to,

• Call current class methods and fields

• To pass an instance of the current class as a parameter

• To differentiate between the local and instance variables.

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.

[Link] of super with Variables

[Link] of super with Constructors

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.

Static Binding Dynamic Binding

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.

• Abstract classes may have methods without implementation and must be


implemented by subclasses.

• By abstracting functionality, changes in the implementation do not affect the code


that depends on the abstraction.

➢ Java provides two ways to implement abstraction, which are listed below:

• Abstract Classes (Partial Abstraction)

• Interface (100% Abstraction)

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.

Introduction to Java Packages


What is a Package?

In the world of Java, a

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

Java packages can be broadly categorized into two forms:

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

[Link] package, you could create sub-packages like


[Link] and [Link] to separate
different product categories.

Access Modifiers in Java


What are Modifiers?

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.

The Four Types of Java Access Modifiers

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.

Analogy: A default member is like an internal memo within a department of a company.


Everyone in that department (package) can see it, but other departments cannot.

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.

Column1 Column2 Column3 Column4 Column5

Within Within Outside Package by Outside


Modifier Class Package Subclass Only Package

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.

Typically, encapsulation is implemented by making the data members (instance variables)


of a class private and providing public methods (known as "getters" and "setters") to access
and modify that data. This practice is the primary method for achieving

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

Implementing encapsulation in your code provides several significant benefits:

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

read-only. Conversely, by providing only a setter method, you can make it

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.

Class vs. Object:

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

Feature Class Object

A class is a blueprint or template


from which objects are created. It
Core can also be described as a group of
Definition similar objects. An object is an instance of a class.

An object is a real-world entity with a


Real- specific state and behavior, such as a
World A class is a general concept, like the particular pen, laptop, mobile phone,
Analogy idea of a "Car". or your own car.

A class is a logical entity. It's a design


or a plan that exists in code but
doesn't have a physical presence in An object is a physical entity. When it is
memory until an object is created created, it occupies a specific block of
Entity Type from it. memory.

An object is primarily created through


A class is declared using the class the new keyword, for example: Student
Creation keyword, for example: class s1 = new Student();.Student class a
Syntax Student{}. single time.

An object is created many times, as per


the requirements of the program. You
Frequency A class is declared only once. You can create thousands of Student
of Creation write the code for the objects from a single Student class.

Memory A class doesn't allocate memory An object allocates memory in the


Allocation when it is created or declared. heap the moment it is created.

There are many ways to create an


object in Java, such as using the new
There is only one way to define a keyword, the newInstance() method,
Methods class in Java: using the class the clone() method, a factory method,
of Creation keyword. or through deserialization.

Polymorphism: Method Overloading vs. Overriding

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.

Column1 Column2 Column3


Feature Method Overloading Method Overriding
Method overloading is used to increase the Method overriding is used to provide a
readability of the program. It allows you to specific implementation of a method that is
have multiple methods with the same name already provided by its superclass. It allows a
that perform similar actions but on different subclass to customize or completely change
Purpose types or numbers of parameters. the behavior of an inherited method.
Method overloading is performed within a Method overriding occurs in two classes that
Location single class. have an IS-A (inheritance) relationship.
In the case of method overloading, the
parameters must be different (either in
number, type, or order). This is how the In the case of method overriding, the
compiler knows which version of the parameter list must be exactly the same as in
Parameters method to call. the superclass method.
Method overloading is an example Method overriding is an example of run-time
ofcompile-time polymorphism (also known polymorphism (also known as dynamic
as static binding). The decision of which binding). The decision of which method to call
Type of method to call is made at the time of is deferred until runtime, based on the type of
Polymorphism compilation. the object.
The return type can be the same or
different in method overloading. However,
you cannot overload a method only by
changing its return type; the parameter list
must also change. return type must be the A covariant return type means the overriding
same or a covariant type in method method can return a subtype of the type
Return Type overriding. returned by the superclass method.

🔢 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

String s1 = "Hello"; // String literal


String s2 = new String("World"); // Using new keyword

Common String Methods


length() Returns length of string "Java".length() → 4
charAt(int i) Returns character at index "Java".charAt(1) → 'a'
equals(String) Compares content "hi".equals("hi") → true
== Compares memory address Different from .equals()
substring(start,
Returns substring "program".substring(0,4) → "prog"
end)
toLowerCase() Converts to lowercase "JAVA".toLowerCase() → "java"
toUpperCase() Converts to uppercase "java".toUpperCase() → "JAVA"
trim() Removes spaces " hi ".trim() → "hi"

36 | P a g e
Mutable Strings in Java

In Java, String objects are immutable (cannot be changed after creation).


To work with mutable strings, Java provides two main classes:

1. StringBuffer

• Mutable: Contents can be modified after creation.

• Thread-safe: All methods are synchronized, meaning multiple threads cannot modify it
at the same time → safe for multi-threaded environments.

• Slower than StringBuilder because synchronization adds overhead.

Example:

37 | P a g e
2. StringBuilder

• Mutable: Like StringBuffer, contents can be changed.

• Not thread-safe: Methods are not synchronized, so not safe in multi-threaded code.

• Faster than StringBuffer because it avoids synchronization overhead.

Example:

When to use:

• Single-threaded programs → StringBuilder (better performance).

• Multi-threaded programs → StringBuffer (safety).

⚠️ Exception Handling in Java


Exceptions are unwanted or unexpected events that disrupt the normal flow of a program.
Java provides a robust mechanism to handle exceptions using try, catch, finally, throw, and
throws.

Types of Exceptions in Java


1. Checked Exceptions

38 | P a g e
• Checked at compile-time → The compiler forces you to handle them using try-catch or
throws.

• These are usually recoverable.

• Examples:
o IOException

o SQLException

o FileNotFoundException

[Link] Exceptions
• Not checked at compile-time → Occur at runtime.

• Usually caused by programming mistakes (logic errors).

• Not compulsory to handle.

• Examples:

o NullPointerException

o ArithmeticException

o ArrayIndexOutOfBoundsException

39 | P a g e
Errors
• Serious problems beyond the control of the programmer.

• Cannot be handled with normal exception handling.

• Indicate problems with the JVM environment.

• 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.

• Resizable Array: ArrayList can automatically grow dynamically in size.

• Indexed Access: ArrayList elements can be accessed using indices like arrays.

• Supports Generics: It ensures type safety at compile-time.

• Not Synchronized: ArrayList uses [Link]() for thread safety.

• 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.

• Can store the Null values.

• Uses HashMap (implementation of hash table data structure) internally.

• Also implements Serializable and Cloneable interfaces.

• HashSet is not thread-safe. To make it thread-safe, synchronization is needed


externally.

• Use: public class HashSet<E> extends AbstractSet<E> implements Set<E>,


Cloneable, Serializable

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.

[Link] Elements in HashSet


The values can be removed from the HashSet using the remove() method.

3. Iterating through the HashSet


Iterate through the elements of HashSet using the iterator() method. Also, the most
famous one is to use the enhanced for loop.

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.

• Values can be duplicated.

• 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

Adding Elements in HashMap in Java

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.

Changing Elements in HashMap in Java

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).

• A process can have multiple threads.


• Each thread runs independently but shares the same memory.

Extending the Thread class

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.

Implementing the Runnable Interface

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.

5. Better User Experience: Smooth execution of tasks like file downloads,


animations, and real-time updates.

Using extends keyword

51 | P a g e
Using Runnable keyword

Java Memory Model


Java memory management is the process by which the Java Virtual Machine (JVM)
automatically handles the allocation and deallocation of memory. It uses a garbage
collector to reclaim memory by removing unused objects, eliminating the need for manual
memory management

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.

• Scanner sc = new Scanner([Link])

Method Area
• Method area is a logical part of the heap and it is created when the JVM starts.

• Method area is used to store class-level information such as class structures,


Method bytecode, Static variables, Constant pool, Interfaces.

• Method area can be of fixed or dynamic size depending on the system's


configuration.

• Static variables in Java are stored in the Method Area.

• 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.

• Each Thread has its own stack, ensuring thread safety.

• Stacks size can be either fixed or dynamic and it can be set when the stack is
created.

• The memory for stack needs not to be contiguous.

• Once a method completes execution, its associated stack frame is removed


automatically.

53 | P a g e
Native Method Stacks
• Native method stack is also known as C stacks.

• Native method stacks are not written in Java language.

• 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.

Program Counter (PC) Registers


• Each JVM thread has a Program Counter (PC) register.

• For non-native methods, it stores the address of the current JVM instruction.

• For native methods, the PC value is undefined.

• On some platforms, the PC can also store a return address or native pointer.

Garbage Collector in java


The Garbage collector automatically removes the unused objects that are no longer
needed. It runs in the background to free up memory.

• 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: Concise functional code using ->.

• Functional Interfaces: Single-method interfaces.

• Introduced and Improved APIs:

1. Stream API: Efficient Data Manipulation.

2. Date/Time API: Robust Date and Time Handling.

3. Collection API Improvements: Enhanced Methods for Collections


(e.g., removeIf, replaceAll).

4. Concurrency API Improvements: New classes for parallel processing


(e.g., CompletableFuture).

• Optional Class: Handle null values safely.

• forEach() Method in Iterable Interface: Executes an action for each element in a


Collection.

• Default Methods: Evolve interfaces without breaking compatibility.

• Static Methods: Allows adding methods with default implementations to


interfaces.

• Method References: Refer to methods easily.

Lambda Expressions

Lambda Expression basically expresses an instance of the functional interface, in


other words, you can say it provides a clear and concise way to represent a method
of the functional interface using an expression. Lambda Expressions are added in
Java 8.

Functional Interfaces

An interface that contains only one abstract method is known as a functional


interface, but there is no restriction, you can have n number of default and static
methods inside a functional interface.

55 | P a g e
Method Reference

Method reference is a shorthand notation of a lambda expression to call a


method. There are four types of method references that are as follows:

• Static Method Reference

• Instance Method Reference of a particular object

• Instance Method Reference of an arbitrary object of a particular type

• 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.

Java Stream Programs

Java Streams provide a powerful and expressive way to process sequences of


elements in Java, enabling functional-style operations on collections of data. The
Stream API, introduced in Java 8, facilitates efficient data manipulation and
transformation using a sequence of operations that can be performed in parallel or
sequentially

Java Stream Methods

Methods related to one of the most powerful features of Java Stream are mentioned
below.

Comparable and Comparator

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.

Question (3marks each)

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]

YouTube: Shuvam Sahoo - YouTube

59 | P a g e

You might also like