0% found this document useful (0 votes)
22 views75 pages

Java Notes: Beginner to Advanced Guide

The document provides an overview of core Java concepts, including the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), explaining their roles in executing Java applications. It also covers Java variables, data types, type casting, operators, control statements, and object-oriented programming principles like classes and polymorphism. The content is structured to guide beginners through advanced topics in Java programming.
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)
22 views75 pages

Java Notes: Beginner to Advanced Guide

The document provides an overview of core Java concepts, including the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), explaining their roles in executing Java applications. It also covers Java variables, data types, type casting, operators, control statements, and object-oriented programming principles like classes and polymorphism. The content is structured to guide beginners through advanced topics in Java programming.
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

til

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.

The JVM performs the following main tasks:

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:

o​ Standard Edition Java Platform


o​ Enterprise Edition Java Platform
o​ Micro Edition Java Platform
The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
til
Why Java platform independent
Pa
Java is platform-independent because it uses bytecode, an intermediate format generated
by the Java compiler. This bytecode can run on any platform with a Java Virtual Machine
(JVM), which translates the bytecode into platform-specific machine code. This ensures the
principle of "Write Once, Run Anywhere" (WORA).
n
Other language which is platform dependent , the compiler convert to Machin code that
makes platform dependent. In java compiler only create byte code and byte code can run
on JVM which create Machin code.
ta

Write Once, Run Anywhere (WORA)

●​ Developers write Java code once, compile it into bytecode, and this bytecode can be
he

run on any system without modification as long as it has a JVM.

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.

A local variable cannot be defined with "static" keyword.

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.

Data Types in Java


n
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
ta

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.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation. These are the
C

most basic data types available in Java language.

Java Primitive data types:

1.​ boolean data type


2.​ byte data type
3.​ char data type
4.​ short data type
5.​ int data type
6.​ long data type
7.​ float data type
8.​ double data type

til
Pa
n
ta
he

Non-Primitive Data Types in Java


In Java, non-primitive data types, also known as reference data types, are used to store
complex objects rather than simple values. Unlike primitive data types that store the actual
values, reference data types store references or memory addresses that point to the
C

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

1.​ Widening Casting (Implicit): Conversion


o​ Converts a smaller type to a larger type.
o​ Safe and done automatically by Java.
o​ Example:

int num = 10;


double result = num; // int to double

2.​ Narrowing Casting (Explicit):


o​ Converts a larger type to a smaller type.
o​ May lead to data loss and requires explicit casting.
o​ Example:

double num = 10.5;


int result = (int) num; // double to int (data loss: fractional part removed)

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.

Java Unary Operator


Pa
n
The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:
ta

o​ incrementing/decrementing a value by one


o​ negating an expression
o​ inverting the value of a Boolean
he

Java Arithmetic Operators


Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
C

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.

public class OperatorExample{


public static void main(String args[]){
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80​
Java Right Shift Operator
The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.

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

Java OR Operator Example: Logical || and Bitwise |


he

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

Java Control Statements | Control Flow in Java


Java provides three types of control flow statements.

1.​ Decision Making statements


he

o​ if statements
o​ switch statement

2.​ Loop statements


o​ do while loop
o​ while loop
C

o​ for loop
o​ for-each loop

3.​ Jump statements


o​ break statement
o​ continue statement
If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.

1.​ Simple if statement


2.​ if-else statement
3.​ if-else-if ladder
4.​ Nested if-statement

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.

Syntax of if statement is given below.

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.

Points to be noted about switch statement:

o​ The case variables can be int, short, byte, char, or enumeration. String type is also
C

supported since version 7 of Java


o​ Cases cannot be duplicate
o​ Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o​ Break statement terminates the switch block when the condition is satisfied. It is
optional, if not used, next case is executed.
o​ While using switch statements, we must notice that the case expression will be of
the same type as the variable. However, it will also be a constant value.
til
Loop Statements

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

3.​ do-while loop

Let's understand the loop statements one by one.


he

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when
we exactly know the number of times, we want to execute the block of code.
C
we want to execute the block of code.

Java while loop

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.

The syntax of the while loop is given below.


n
ta
he
C
Java do-while loop
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.

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:

o​ Happens within the same class.


C

o​ Determined at compile time (Compile-time Polymorphism).


o​ Does not depend on the return type.
Run-Time Polymorphism (Dynamic Polymorphism):
●​ Achieved through method overriding.
●​ The method to be executed is determined at runtime based on the object type.

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.

o​ Happens across classes in an inheritance hierarchy.


o​ Determined at runtime (Runtime Polymorphism).
o​ The method must have the same name, parameters, and return type.
o​ Requires the use of the @Override annotation (optional but recommended).
o​ The overridden method in the superclass must be public or protected (not
n
private).
ta
he
C
Array in Java

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

1.​ Single-Dimensional Array:

Pa
n
ta

2.​ Multi-Dimensional Array:


he
C

Jagged Arrays in Java


A jagged array (or irregular array) is a multi-dimensional array where the rows have
different lengths. Unlike regular 2D arrays, jagged arrays allow you to have variable column
sizes for each row.
Key Characteristics

1.​ Rows can have different numbers of columns.


2.​ Useful for representing irregular data structures like triangle matrices or sparse data.
3.​ Declared as an array of arrays.

til
Pa
n
ta
he

Disadvantages of Arrays in Java

1.​ Fixed Size


C

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

Array of Objects in Java


Pa
sorting or searching efficiently, whereas collections have built-in support.

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

●​ Thread-safe: No risk of data corruption when accessed by multiple threads.


●​ Efficient for scenarios like keys in a HashMap where immutability is desirable.
he

6.​ Disadvantages:

●​ Frequent modifications result in many intermediate objects and may cause


performance overhead.

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:

●​ Efficient for scenarios requiring frequent modifications (e.g., loops or

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

When to Use Which?

●​ 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

1.​ Execution Time:


o​ Executes when the class is loaded into the JVM.
o​ Executes before the main method or any instance creation.
2.​ One-Time Execution: Static blocks run only once, regardless of how many objects of
the class are created.
3.​ Purpose:
C

o​ Initialize static variables.


o​ Perform tasks that need to be done only once for the class.

When to Use Static Blocks

1.​ To initialize static variables or constants.


2.​ To load configuration settings or files.
3.​ To execute class-level startup logic (e.g., loading native libraries).
til
How to Load a Class in Java

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

1.​Automatically Loaded Classes

Java automatically loads classes when:


n
●​ You create an object of a class using new.
●​ You call a static method or access a static variable.
●​ The JVM encounters the main() method in a class.
ta

2.​Using [Link]()

The [Link]() method dynamically loads the class at runtime.


he

Using [Link]()

The ClassLoader class can be used to load a class programmatically.


C

3.​Using [Link]()

The ClassLoader class can be used to load a class programmatically.

4.​Using [Link]()

If you have an instance of an object, you can get its class reference using the getClass()
method.
Encapsulation in Java

Encapsulation is a fundamental principle of object-oriented programming (OOP) that


involves bundling data (fields) and methods (functions) that operate on the data into a
single unit (a class). It restricts direct access to certain components of an object and allows
controlled access through defined methods.

Key Features of Encapsulation

1.​ Data Hiding:


o​ Internal representation (fields) of an object is hidden from the outside world.
o​ Only selected information is accessible via public methods.
2.​ Controlled Access:
o​ Provides getter and setter methods to access or update private fields.

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

1.​ Declare Fields as private:


n
o​ This restricts direct access to the fields from outside the class.
2.​ Provide public Getter and Setter Methods:
o​ These methods control and validate access to the private fields.
ta

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

4.​ Reusability: Encapsulated classes are modular and easier to reuse.


til
Getters and Setters in Java
Pa
n
Getters and setters are methods used to access and update the private fields of a class.
They provide controlled access to the class's data by following the principles of
encapsulation.
ta

Why Use Getters and Setters?

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

Key Uses of this

1.​ Refer to Instance Variables:


o​ When a method or constructor has a local variable with the same name as an
instance variable, this is used to distinguish between them.
2.​ Call Another Constructor (Constructor Chaining):
o​ Used to call one constructor from another in the same class.
3.​ Pass 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:

Key Points About this

●​
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

What is a Constructor in Java?


A constructor in Java is a special method used to initialize objects. It is called automatically
when an object of a class is created. The constructor typically initializes the instance
he

variables of the class and allocates memory for the object.

Key Features of Constructors

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

1.​ Default Constructor:


o​ A no-argument constructor provided by the compiler if no constructor is
explicitly defined.
o​ Used to initialize fields to default values
2.​ No-Argument Constructor:

●​ Explicitly defined by the programmer.


●​ Similar to the default constructor but can include logic.

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

1.​ Names Should Be Meaningful:


o​ Use names that clearly describe the purpose of variables, methods,
classes, etc.
o​ Avoid single-character names except for loop variables or temporary use
(e.g., i, j).
2.​ Avoid Abbreviations:

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

1.​Classes and Interfaces


Pa
●​ Convention: Use PascalCase (also known as UpperCamelCase).
●​ Rules:
o​ First letter of each word should be capitalized.
n
o​ Should be nouns for classes (e.g., Student, Employee) and adjectives for interfaces
(e.g., Runnable, Serializable).
ta
he

2.​Methods

●​ Convention: Use camelCase.


C

●​ Rules:
o​ First letter is lowercase, and subsequent words are capitalized.
o​ Use verbs to describe the action the method performs.
3.​Variables

●​ Convention: Use camelCase.


●​ Rules:
o​ First letter is lowercase, and subsequent words are capitalized.
o​ Use meaningful names representing the purpose of the variable.

til
4.​Constants
Pa
n
●​ Convention: Use UPPERCASE_WITH_UNDERSCORES.
●​ Rules:
o​ All letters should be uppercase.
ta

o​ Words are separated by underscores.


he
C

5.​Packages

●​ Convention: Use lowercase and hierarchical structure.


●​ Rules:
o​ Typically follows the reversed domain name of the organization (e.g.,
[Link]).
o​ Avoid using underscores or special characters.
6.​Variables in Loops

●​ Convention: Use single-letter variables for loop counters.


●​ Rules:
o​ Use i, j, k for nested loops.

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

●​ Convention: Use a single uppercase letter.


●​ Rules:
o​ Commonly used letters:
▪​ T for Type

▪​ E for Element

▪​ K for Key

▪​ V for Value
Anonymous Objects in Java

An anonymous object in Java is an object that is created without assigning it to a reference


variable. It is often used when the object is required only once, making the code concise and
efficient.

til
Characteristics of Anonymous Objects

1.​ No Reference: The object is not stored in a reference variable.


2.​ Short-Lived: The object exists for a short duration and is used immediately after creation.

Pa
3.​ Syntax: Created using the new keyword followed by the class constructor.

When to Use Anonymous Objects

●​ 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

Inheritance in Java is a core concept of Object-Oriented Programming (OOP) that allows a


class (called a subclass or child class) to inherit properties and behaviors (fields and
methods) from another class (called a superclass or parent class).

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.

Purpose of Method Overriding

●​ To achieve runtime polymorphism (dynamic method dispatch).


n
●​ To customize behavior inherited from a parent class.
●​ To allow subclasses to provide specific functionality.
ta
he
C
til
Access Modifiers in Java
Pa
n
ta
he
C
Final Keyword in java

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

Lambda Expressions in Java

Lambda expressions were introduced in Java 8 to provide a concise way to represent a


C

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

Difference between throw and throws in Java


he
C
til
Pa
n
ta
he

BufferedReader vs Scanner in Java


C

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

What is Optional in Java?


he

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 & Constructor Reference in Java (Java 8+)

Method reference and constructor reference are shortcuts in lambda expressions to directly
he

refer to existing methods or constructors.

They make the code cleaner and more readable.


C
C
he
ta
n
Pa
til
C
he
ta
n
Pa
til

You might also like