Java Notes: Beginner to Advanced Guide
Java Notes: Beginner to Advanced Guide
Pa
Core Java Notes Beginner to
Advance
n
ta
he
C
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are
platform dependent because the configuration of each OS is different from each other.
However, Java is platform independent. There are three notions of the JVM:
specification, implementation, and instance.
til
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JRE
Pa
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
n
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
ta
JDK
he
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
C
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:
● Developers write Java code once, compile it into bytecode, and this bytecode can be
he
Java Variables
C
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.
Variable is a name of memory location. There are three types of variables in java: local,
instance and static.
There are two types of data types in Java: primitive and non-primitive.
1)Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2)Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
til
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3)Static variable
Pa
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and
Arrays.
he
Let's understand in detail about the two major data types of Java in the following paragraphs.
til
Pa
n
ta
he
location of the object in memory. This distinction is important because it affects how these
data types are stored, passed, and manipulated in Java programs.
Class
One common non-primitive data type in Java is the class. Classes are used to create objects,
which are instances of the class. A class defines the properties and behaviors of objects,
including variables (fields) and methods. For example, you might create
a Person class to represent a person, with variables for the person's name, age, and
address, and methods to set and get these values.
Interface
Interfaces are another important non-primitive data type in Java. An interface defines a contract
for what a class implementing the interface must provide, without specifying how it should be
implemented. Interfaces are used to achieve abstraction and multiple inheritance in Java,
allowing classes to be more flexible and reusable.
Arrays
Arrays are a fundamental non-primitive data type in Java that allow you to store multiple
values of the same type in a single variable. Arrays have a fixed size, which is specified when
til
the array is created, and can be accessed using an index. Arrays are commonly used to store
lists of values or to represent matrices and other multi-dimensional data structures.
Enum
Pa
Java also includes other non-primitive data types, such as enums and collections. Enums are
used to define a set of named constants, providing a way to represent a fixed set of values.
Collections are a framework of classes and interfaces that provide dynamic data structures
such as lists, sets, and maps, which can grow or shrink in size as needed.
Overall, non-primitive data types in Java are essential for creating complex and flexible
n
programs. They allow you to create and manipulate objects, define relationships between
objects, and represent complex data structures. By understanding how to use non-primitive
data types effectively, you can write more efficient and maintainable Java code.
ta
Type Casting
he
Type casting in Java is the process of explicitly converting a variable from one data type to
another. It is usually performed between compatible types (e.g., int to double).
Types of Casting:
C
Operators in Java
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
til
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o
o
o
Logical Operator,
Ternary Operator and
Assignment Operator.
til
Java AND Operator Example: Logical && and Bitwise &
Pa
The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
n
ta
The logical || operator doesn't check the second condition if the first condition is true. It checks
the second condition only if the first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
C
Java Ternary Operator
Java Ternary operator is used as one line replacement for if-then-else statement and used a
lot in Java programming. It is the only conditional operator which takes three operands.
til
Java Assignment Operator
Pa
Java assignment operator is one of the most common operators. It is used to assign the
value on its right to the operand on its left.
n
ta
o if statements
o switch statement
o for loop
o for-each loop
Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a
til
Boolean expression and enables the program to enter a block of code if the expression
evaluates to true.
Pa
2)if-else statement
n
The if-else statement is an extension to the if-statement, which uses another block of code,
ta
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.
he
C
3)if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
4) Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another
til
if or else-if statement.
Pa
n
ta
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable
he
which is being switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also
C
Pa
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences
in their syntax and condition checking time.
n
1. for loop
2. while loop
ta
til
The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take place
inside the loop statement in while loop.
Pa
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
til
Pa
n
ta
he
C
OOPs (Object-Oriented Programming)
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:
til
Pa
n
ta
he
Class
A class in Java is a blueprint or template for creating objects. It defines the structure
(fields/attributes) and behaviour (methods) that the objects of the class will have. Class
does not consume any space.
C
Object
An object in Java is an instance of a class. It is a real-world entity with state (attributes) and
behaviour (methods) as defined by the class.
til
Polymorphism in Java
Pa
Polymorphism is the ability of an object to take on many forms. It allows a single action to
behave differently based on the object performing it. In Java, polymorphism is primarily
achieved through method overloading and method overriding.
Types of Polymorphism
Compile-Time Polymorphism (Static Polymorphism):
n
o Achieved through method overloading.
o The method to be executed is determined at compile time.
ta
Method Overloading
Definition: Method overloading occurs when two or more methods in the same class
he
have the same name but different parameter lists (type, number, or order of
parameters).
Key Points:
til
Method Overriding
●
● Key Points:
Pa
Definition: Method overriding occurs when a subclass provides a specific
implementation of a method that is already defined in its superclass.
til
An array in Java is a data structure used to store multiple elements of the same data type in
a single variable. It provides a way to group and manage similar types of data efficiently.
Key Features
changed dynamically.
Pa
1. Fixed Size: The size of an array is defined at the time of creation and cannot be
2. Indexed Access: Array elements are accessed using an index, starting from 0.
3. Homogeneous Data: Arrays store elements of the same data type.
4. Continuous Memory: Array elements are stored in contiguous memory locations.
n
ta
he
C
til
Types of Arrays
Pa
n
ta
til
Pa
n
ta
he
o The size of an array is static and must be defined at the time of creation.
o It cannot grow or shrink dynamically, leading to potential memory wastage or
insufficient storage.
2. Homogeneous Data
o Arrays can only store elements of the same data type.
o For storing heterogeneous data, you need to use collections like ArrayList or
HashMap.
3. No Built-in Methods
o Arrays lack built-in methods for operations like adding, removing, or
searching elements efficiently.
o Collections like ArrayList provide these features.
4. Memory Usage
o Arrays use contiguous memory, which can cause issues when a large block of
memory is unavailable, even if there is enough fragmented memory.
5. Performance for Insertion/Deletion
o Inserting or deleting an element in an array requires shifting elements, which
is time-consuming, especially for large arrays.
6. Type-Specific
o Java arrays are type-specific, and you cannot store objects of different types
in a single array.
7. Lack of Flexibility
o Arrays are not resizable, unlike data structures like ArrayList, LinkedList, or
til
Vector.
8. No Direct Sorting/Searching Support
o Arrays require manual coding or external libraries to perform tasks like
An array of objects is a collection where each element is an object. This is useful for storing and
managing multiple objects of the same class.
n
ta
he
C
Mutable vs Immutable Strings in Java
In Java, strings can be mutable or immutable, depending on the type of class used to handle
the string.
Immutable Strings
1. Definition: Immutable strings cannot be modified after they are created. Any
operation that alters a string creates a new object rather than modifying the original
string.
2. Class Used: String class.
3. Characteristics:
til
o String objects are stored in the String Pool for memory efficiency.
o Modifying a string (e.g., concatenation) creates a new string object.
Pa
n
4. Advantages:
ta
6. Disadvantages:
Mutable Strings
C
1. Definition: Mutable strings can be modified directly without creating a new object.
2. Classes Used: StringBuilder and StringBuffer.
3. Characteristics:
o Modifications happen within the same object, reducing overhead.
o StringBuffer is synchronized (thread-safe), while StringBuilder is not
synchronized (faster in single-threaded operations).
4. Example:
5.Advantages:
til
concatenations).
● Reduces memory usage since no new objects are created.
6.Disadvantages:
●
threaded environments.
Pa
StringBuilder is not thread-safe, so it requires external synchronization in multi-
n
ta
he
C
● Use String for immutable operations, like string keys in maps or constant strings.
● Use StringBuilder for single-threaded programs requiring frequent modifications.
● Use StringBuffer in multi-threaded environments needing synchronized operations.
Static Variable
1. Definition: A static variable is shared across all objects of the class. It belongs to the
class, not the instances.
2. Key Points:
o One copy per class: All objects share the same value of the static variable.
o Memory allocation: Static variables are allocated memory once, in the
method area, at the time of class loading.
o Access: Can be accessed directly using the class name or through an object
reference (though not recommended).
Static Method
1. Definition: A static method belongs to the class rather than any specific object and
til
can be called without creating an instance of the class.
2. Key Points:
o No need for an object: Static methods can be called directly using the class
name.
o Access restrictions:
▪
Pa
Static methods cannot access non-static variables or methods
directly (since they belong to the object).
▪ They can only access other static variables and methods.
o Use case: Utility or helper methods (e.g., [Link]() or [Link]()).
n
ta
he
C
When to Use
til
● Use a static variable for class-level properties that should be shared among all
instances (e.g., a counter, configuration settings).
● Use a static method for utility-like functionality that doesn’t depend on instance
variables (e.g., mathematical calculations, helper methods).
Pa
n
Static Block in Java
A static block in Java is a block of code that is executed once when the class is loaded into
ta
memory. It is used to initialize static variables or perform any startup tasks for the class.
Key Points
he
Pa
In Java, a class is loaded into memory by the ClassLoader when it is required for execution.
There are multiple ways to load a class programmatically or automatically
2.Using [Link]()
Using [Link]()
3.Using [Link]()
4.Using [Link]()
If you have an instance of an object, you can get its class reference using the getClass()
method.
Encapsulation in Java
til
o Ensures data integrity and validation.
3. Improved Code Maintainability:
o Changes to the internal implementation do not affect external code interacting with
the class.
4. Enhanced Security:
Pa
o Protects data from unintended modifications.
Implementation of Encapsulation
Advantages of Encapsulation
he
1. Improves Security: Protects sensitive data from unintended access or modification.
2. Data Validation: Ensures that only valid data is stored in the fields (e.g., through
validation in setters).
3. Ease of Maintenance: Changes to internal implementation don’t affect external
code.
C
1. Encapsulation:
he
o They ensure that the internal representation of an object is hidden from the outside
world.
2. Data Validation:
o Setters allow you to add validation logic before changing a field's value.
3. Flexibility:
C
o You can modify the implementation of a getter or setter without changing the
external interface.
4. Consistency:
o Promotes a standard way to access and modify data across your code.
this Keyword in Java
The this keyword in Java is a reference variable that refers to the current object of the class.
It is commonly used to resolve naming conflicts and to access the instance variables,
methods, or constructors of the current object
til
o Pass the current object as an argument to another method or constructor.
4. Return the Current Object:
o Return the object itself from a method.
5. Call an Instance Method:
●
Pa
o Call a method of the current class explicitly.
this cannot be used in static methods because static methods belong to the class,
not any specific object.
n
● It is automatically passed as a reference to instance methods of a class.
● Improves code readability and resolves ambiguity when variable names conflict.
ta
1. Same Name as the Class: The constructor's name must exactly match the class name.
C
2. No Return Type: Constructors do not have a return type, not even void.
3. Automatically Invoked: The constructor is called automatically when an object is
instantiated.
4. Types of Constructors:
o Default Constructor: A no-argument constructor automatically provided by Java if
no constructor is defined in the class.
o Parameterized Constructor: A constructor with arguments to initialize fields with
specific values.
Types of Constructors
til
Pa
n
ta
he
C
Naming Conventions in Java
Naming conventions in Java are guidelines to improve the readability and maintainability of
code. These conventions make it easier for developers to understand the code and
collaborate on projects.
General Guidelines
til
o Use full, descriptive names (e.g., firstName instead of fName).
3. Follow Case Sensitivity:
o Java is case-sensitive, so follow specific conventions for different elements.
Conventions by Type
2.Methods
● Rules:
o First letter is lowercase, and subsequent words are capitalized.
o Use verbs to describe the action the method performs.
3.Variables
til
4.Constants
Pa
n
● Convention: Use UPPERCASE_WITH_UNDERSCORES.
● Rules:
o All letters should be uppercase.
ta
5.Packages
til
7.Enum Constants
Pa
● Convention: Use UPPERCASE_WITH_UNDERSCORES.
● Rules:
n
o Enum constants should be written in uppercase.
ta
he
8.Type Parameters
C
▪ E for Element
▪ K for Key
▪ V for Value
Anonymous Objects in Java
til
Characteristics of Anonymous Objects
Pa
3. Syntax: Created using the new keyword followed by the class constructor.
● Single-Use Objects: When the object is needed only once and does not need to be reused
later.
● Short Methods: When the object's purpose is fulfilled in a single method call.
n
ta
he
C
Inheritance in a JAVA
til
Pa
n
ta
he
C
C
he
ta
n
Pa
til
til
Method Overriding in Java
Pa
Method Overriding in Java occurs when a subclass provides a specific implementation of a
method that is already defined in its superclass. The method in the child class must have
the same name, return type, and parameters as the one in the parent class.
The final keyword in Java is used to restrict modification. It can be applied to variables,
methods, and classes, each serving a specific purpose.
til
Pa
n
ta
he
C
Dynamic Method Dispatch in java
til
Dynamic Method Dispatch is a mechanism in Java that resolves method calls at runtime
instead of compile-time. It is a key feature of runtime polymorphism.
Pa
n
ta
he
C
til
Pa
n
Upcasting and Downcasting in Java
In Java, casting refers to converting one type to another. When working with inheritance,
ta
we often deal with object type casting between a superclass and its subclass.
he
C
C
he
ta
n
Pa
til
Wrapper Classes in Java
Wrapper classes in Java are used to wrap primitive data types into objects. This is especially
useful when working with collections, generics, or when an object reference is required.
til
Pa
n
ta
he
C
Abstract Keyword in Java
The abstract keyword in Java is used to declare a class or a method that is incomplete and
must be implemented by a subclass.
til
Pa
n
ta
he
C
C
he
ta
n
Pa
til
Inner Classes in Java
An inner class in Java is a class defined inside another class. Java supports several types of
inner classes, which are useful for grouping logic, encapsulating behavior, and improving
readability and organization.
til
Pa
n
ta
he
C
C
he
ta
n
Pa
til
til
Interface in Java
Pa
n
ta
he
C
C
he
ta
n
Pa
til
til
Pa
n
ta
he
Enum in Java
C
In Java, an enum (short for enumeration) is a special data type that enables you to define a
fixed set of constants — like days of the week, directions, states, etc.
C
he
ta
n
Pa
til
Annotation in Java
Annotations in Java are metadata (data about data) that provide information to the
compiler, tools, or frameworks. They do not directly affect program logic, but can influence
how the code is compiled or executed.
til
Pa
n
ta
he
C
Different Type of Interface
til
Pa
n
ta
he
C
til
Pa
n
ta
he
method using an expression. They enable functional programming features in Java and are
mainly used to implement functional interfaces
C
he
ta
n
Pa
til
Exception in Java
In Java, an exception is an event that disrupts the normal flow of a program. It typically
occurs when something unexpected or erroneous happens during program execution.
til
Pa
n
ta
he
C
C
he
ta
n
Pa
til
til
Ducking Exception in Java
Pa
Ducking an exception in Java refers to the practice of passing the responsibility of handling
an exception to the caller method instead of handling it within the method itself. This is
done using the throws keyword in the method declaration
n
ta
he
C
til
Pa
n
ta
Both BufferedReader and Scanner are used to read input in Java, but they serve different
use-cases and have different performance and features.
C
he
ta
n
Pa
til
try-with-resources in Java
try-with-resources is a feature in Java that allows you to automatically close resources like
files, sockets, or database connections after use — without writing explicit finally blocks.
til
Pa
n
ta
he
C
Threads in Java
A thread in Java is a lightweight sub-process — the smallest unit of execution. Using threads,
Java supports multithreading, which means multiple parts of a program can run
concurrently.
C
he
ta
n
.
Pa
til
C
he
ta
n
Pa
til
til
Race Condition in Java
Pa
n
A race condition is a bug that occurs in multithreaded programs when two or more threads
access shared data at the same time, and the final result depends on the timing of their
execution.
ta
Because threads run concurrently, the order of execution is not guaranteed, leading to
unpredictable results.
he
C
C
he
ta
n
Pa
til
Collection API in Java
The Java Collection Framework (JCF) is a set of classes and interfaces in the [Link] package
til
that helps you store, manipulate, and retrieve groups of objects efficiently.
Pa
n
ta
he
C
C
he
ta
n
Pa
til
C
he
ta
n
Pa
til
til
Stream In Java
Pa
Stream was introduced in Java 8, the Stream API is used to process collections of objects. A
stream in Java is a sequence of objects that supports various methods that can be pipelined
to produce the desired result.
n
ta
he
C
til
Pa
n
ta
Optional<T> is a container object introduced in Java 8 that may or may not contain a non-
null value. It's a safer alternative to returning null and helps avoid NullPointerException.
C
C
he
ta
n
Pa
til
til
Pa
n
ta
Method reference and constructor reference are shortcuts in lambda expressions to directly
he