Professional Documents
Culture Documents
Java Notes
Java Notes
Explanation:
public static void main(String[] args) : The main method where the program execution begins.
2. Compiling: Use the Java compiler ( javac ) to compile the code into bytecode, which is stored in
.class files.
3. Executing: The JVM interprets or just-in-time compiles the bytecode to machine code specific
to the operating system and hardware.
Variables in Java
Variables are used to store data. They must be declared before use.
Java Notes 1
int : 32-bit integer
Literals
Literals are fixed values assigned to variables.
Type Conversion
Type conversion can be implicit or explicit.
Implicit Conversion:
double d = 9.78;
int num = (int) d; // Casting double to int
Java Notes 2
Assignment Operators
Assignment operators are used to assign values to variables.
Relational Operators
Relational operators compare two values and return a boolean result.
Logical Operators
Logical operators are used to combine multiple boolean expressions.
If-Else
If-else statements are used for conditional execution.
Java Notes 3
}
If-Else If
If-else if statements handle multiple conditions.
Ternary Operator
The ternary operator is a shorthand for the if-else statement.
Switch Statement
Switch statements are used for multiple conditions based on a single variable.
int day = 2;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Other day");
break;
Java Notes 4
}
While Loop
Executes a block of code as long as a condition is true.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
Do-While Loop
Executes a block of code at least once, then repeatedly as long as a condition is true.
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
For Loop
Executes a block of code a specific number of times.
While Loop: When the number of iterations is not known and depends on a condition.
Do-While Loop: When the loop needs to run at least once regardless of the condition.
Java Notes 5
In Java, a class is a blueprint for creating objects (a particular data structure), providing initial
values for state (member fields or attributes), and implementations of behavior (member functions
or methods). An object is an instance of a class.
Class Example:
// Constructor
public Car(String color, String model, int year) {
this.color = color;
this.model = model;
this.year = year;
}
// Method
public void displayDetails() {
System.out.println("Color: " + color + ", Model: " + model + ", Yea
r: " + year);
}
}
Object Example:
Java Notes 6
Car car2 = new Car("Blue", "Ford Mustang", 1969);
JRE (Java Runtime Environment): Provides libraries, Java Virtual Machine (JVM), and other
components to run applications written in Java. It does not contain tools for Java development.
JVM (Java Virtual Machine): An abstract machine that enables your computer to run a Java
program. It converts Java bytecode into machine language.
Methods
Methods in Java are blocks of code that perform a specific task. They are used to define the
behavior of objects created from a class.
Method Overloading
Method overloading allows a class to have more than one method with the same name, as long as
their parameter lists are different.
Java Notes 7
}
Heap: Stores objects and class instances. It is a shared memory area used by all threads.
Need of an Array
Arrays store multiple values of the same type in a single variable, allowing efficient storage and
retrieval of data.
Creation of Array
Multi-Dimensional Array
3D Array:
Java Notes 8
Drawbacks of Array
Fixed size: Once declared, the size of the array cannot be changed.
Array of Objects
class Student {
String name;
int age;
What is String
A string is a sequence of characters. In Java, strings are objects of the String class.
Java Notes 9
String greeting = "Hello, World!";
Mutable String: StringBuffer and StringBuilder are used to create mutable strings.
StringBuffer Example:
StringBuilder Example:
Static Variable
A static variable is a class-level variable that is shared among all instances of the class. It is
declared using the static keyword.
Counter() {
Java Notes 10
count++;
}
Static Block
A static block is used to initialize static variables. It runs only once when the class is loaded into
memory.
static {
data = 50;
System.out.println("Static block executed.");
}
Static Method
A static method belongs to the class rather than any instance. It can be called without creating an
instance of the class.
Java Notes 11
Encapsulation
Encapsulation is the process of wrapping data (variables) and code (methods) together into a
single unit called a class. It restricts direct access to some of an object's components.
this Keyword
The this keyword refers to the current instance of the class. It can be used to refer to instance
variables, methods, and constructors.
public Example(int x) {
Java Notes 12
this.x = x; // Refers to the instance variable
}
Constructor
A constructor is a special method that is called when an object is instantiated. It initializes the
object.
Default Constructor:
Parameterized Constructor:
Java Notes 13
public ParameterizedConstructor(String name) {
this.name = name;
}
}
super Method: Refers to the parent class instance variable, method, or constructor.
class Parent {
String name = "Parent";
void display() {
System.out.println("Parent class method");
}
}
void display() {
System.out.println("Child class method");
}
void show() {
System.out.println(super.name); // Refers to Parent class variable
super.display(); // Calls Parent class method
System.out.println(this.name); // Refers to Child class variable
this.display(); // Calls Child class method
}
}
Naming Convention
Class Names: PascalCase (e.g., MyClass )
Anonymous Object
An anonymous object is an instance of a class without storing its reference in a variable. It is used
only once.
Java Notes 14
new Example().display();
Need of Inheritance
Inheritance promotes code reusability by allowing new classes to inherit properties and methods
from existing classes. It also helps in achieving runtime polymorphism.
What is Inheritance
Inheritance is a mechanism in which one class acquires the properties (fields) and behaviors
(methods) of another class. The class which inherits is called the subclass (child class) and the
class being inherited from is called the superclass (parent class).
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Animal {
void eat() {
System.out.println("Eating...");
}
}
Java Notes 15
Multilevel Inheritance: A class is derived from another class, which is also derived from
another class.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
Multiple Inheritance
Java does not support multiple inheritance (a class inheriting from more than one class) directly
due to ambiguity issues, but it can be achieved through interfaces.
interface Printable {
void print();
}
interface Showable {
void show();
}
Java Notes 16
Method Overriding
Method overriding occurs when a subclass provides a specific implementation of a method already
defined in its superclass. The method in the subclass should have the same name, return type, and
parameters as the method in the superclass.
class Animal {
void eat() {
System.out.println("Eating...");
}
}
Packages
Packages are used to group related classes and interfaces together. They help in organizing code
and avoiding name conflicts.
Creating a Package:
package com.example;
Using a Package:
import com.example.MyClass;
Java Notes 17
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Access Modifiers
Access modifiers determine the visibility of classes, methods, and variables. Java has four access
modifiers:
Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon, even
though the method name remains the same. It is achieved through method overloading and method
overriding.
Java Notes 18
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
Java Notes 19
}
Final Keyword
The final keyword can be used with variables, methods, and classes to indicate that they cannot
be changed, overridden, or inherited.
// Final variable
final int MAX_VALUE = 100;
// Final method
class A {
final void display() {
System.out.println("This is a final method.");
}
}
// Final class
final class B {
// Class definition
}
hashCode Method: Returns the hash code value for the object.
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Example example = (Example) obj;
return id == example.id && Objects.equals(name, example.name);
}
@Override
public int hashCode() {
return Objects.hash(id, name);
Java Notes 20
}
@Override
public String toString() {
return "Example{id=" + id + ", name='" + name + "'}";
}
}
class Animal {
void makeSound() {
System.out.println("Animal sound");
}
}
abstract Keyword
The abstract keyword is used to declare abstract classes and methods. Abstract classes cannot be
instantiated and abstract methods must be implemented by subclasses.
void sleep() {
Java Notes 21
System.out.println("Sleeping...");
}
}
Inner Class
An inner class is a class defined within another class. It can access all the members of the outer
class.
class InnerClass {
void display() {
System.out.println("Data: " + data);
}
}
}
Java Notes 22
}
What is Interface
An interface is a reference type in Java, similar to a class, that can contain only constants, method
signatures, default methods, static methods, and nested types. Methods in interfaces are abstract
by default.
interface Animal {
void eat();
void travel();
}
More on Interfaces
Implementing an Interface: A class uses the implements keyword to implement an interface.
Java Notes 23
public void travel() {
System.out.println("Dog travels");
}
}
interface Animal {
void eat();
default void travel() {
System.out.println("Animal travels");
}
}
interface Animal {
static void description() {
System.out.println("Animal interface");
}
}
Need of Interface
Interfaces provide a way to achieve abstraction and multiple inheritance in Java. They allow
different classes to implement the same set of methods, ensuring a contract for the classes.
What is Enum
An enum (short for "enumeration") is a special data type that enables a variable to be a set of
predefined constants.
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
Java Notes 24
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}
// Using if statement
if (today == Day.FRIDAY) {
System.out.println("It's Friday!");
}
Enum Class
The enum class in Java can have fields, constructors, and methods.
enum Day {
SUNDAY("Weekend"), MONDAY("Weekday"), TUESDAY("Weekday"),
WEDNESDAY("Weekday"), THURSDAY("Weekday"), FRIDAY("Weekday"),
SATURDAY("Weekend");
Day(String description) {
this.description = description;
}
Java Notes 25
public class Main {
public static void main(String[] args) {
for (Day day : Day.values()) {
System.out.println(day + ": " + day.getDescription());
}
}
}
What is Annotation
Annotations provide metadata about the program and are used to give information to the compiler,
to be used by the JVM, or for other tools. They do not directly affect the execution of the code.
Example:
Functional Interface
A functional interface is an interface with exactly one abstract method. They can contain multiple
default or static methods. Functional interfaces are used with lambda expressions.
Example:
@FunctionalInterface
interface MyFunctionalInterface {
void execute();
}
Lambda Expression
Lambda expressions provide a clear and concise way to implement a functional interface using an
expression.
Syntax:
Example:
Java Notes 26
MyFunctionalInterface myFunc = () -> System.out.println("Hello, Lambda!");
myFunc.execute();
@FunctionalInterface
interface Addable {
int add(int a, int b);
}
Types of Interface
Marker Interface: No methods, used to mark a class (e.g., Serializable ).
What is Exception
An exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
Java Notes 27
}
}
}
Exception Hierarchy
Java exceptions are hierarchical and are divided into two categories:
Unchecked Exceptions: Exceptions that are not checked at compile time (Runtime exceptions).
Hierarchy:
luaCopy code
Throwable
|-- Exception
| |-- IOException
| |-- SQLException
| `-- RuntimeException
| |-- ArithmeticException
| `-- NullPointerException
`-- Error
Example:
Java Notes 28
public class Example {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible for voting.");
} else {
System.out.println("Eligible for voting.");
}
}
Custom Exception
You can create your own exceptions by extending the Exception class.
Example:
Java Notes 29
static void checkAge(int age) throws MyException {
if (age < 18) {
throw new MyException("Not eligible for voting.");
} else {
System.out.println("Eligible for voting.");
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
Scanner:
import java.util.Scanner;
Java Notes 30
System.out.println("Hello, " + name);
scanner.close();
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
Threads
A thread is a lightweight sub-process, the smallest unit of processing. It is a separate path of
execution and can run concurrently with other threads. In Java, you can create a thread by
extending the Thread class or implementing the Runnable interface.
Java Notes 31
}
}
Multiple Threads
You can create and run multiple threads in Java to perform multiple tasks concurrently.
Example:
Example:
Java Notes 32
public class ThreadPrioritySleep extends Thread {
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
System.out.println(e);
}
System.out.println(Thread.currentThread().getName() + " - " +
i);
}
}
Runnable vs Thread
Runnable: Implements Runnable interface. Preferred way as it allows multiple inheritance.
Thread: Extends Thread class. Suitable when you want to override other Thread methods.
Race Condition
A race condition occurs when two or more threads can access shared data and try to change it at
the same time. This leads to inconsistent results.
Example:
class Counter {
private int count = 0;
Java Notes 33
public class RaceCondition {
public static void main(String[] args) throws InterruptedException {
Counter counter = new Counter();
Runnable task = () -> {
for (int i = 0; i < 1000; i++) {
counter.increment();
}
};
t1.start();
t2.start();
t1.join();
t2.join();
Thread States
A thread can be in one of the following states:
RUNNABLE: The thread is ready to run and is waiting for CPU time.
WAITING: The thread is waiting indefinitely for another thread to perform a particular action.
TIMED_WAITING: The thread is waiting for another thread to perform a specific action for up to
a specified waiting time.
Collection API
The Collection API is a framework that provides architecture to store and manipulate a group of
objects. It includes interfaces and classes like List , Set , Map , ArrayList , HashSet , and HashMap .
ArrayList
ArrayListis a resizable array implementation of the List interface. It allows duplicate elements and
maintains insertion order.
Example:
Java Notes 34
import java.util.ArrayList;
Set
Set is an unordered collection that does not allow duplicate elements. HashSet is a commonly used
implementation.
Example:
import java.util.HashSet;
import java.util.Set;
Map
Map is an object that maps keys to values. A Map cannot contain duplicate keys.
Example:
Java Notes 35
import java.util.HashMap;
import java.util.Map;
Comparator vs Comparable
Comparable: Used to define the natural order of objects (single sorting sequence).
Comparable Example:
import java.util.*;
Java Notes 36
Collections.sort(students);
Comparator Example:
import java.util.*;
class Student {
String name;
int age;
Java Notes 37
The Stream API was introduced in Java 8 to process collections of objects in a functional
programming style. It provides methods for filtering, mapping, and reducing, allowing for more
concise and readable code.
forEach Method
The forEach method is used to iterate over elements of a collection.
Example:
import java.util.Arrays;
import java.util.List;
Stream API
The Stream API is used to process collections of objects. A stream is a sequence of elements
supporting sequential and parallel aggregate operations.
Example:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
Java Notes 38
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Arrays;
import java.util.List;
Java Notes 39
System.out.println(sum); // Output: 15
}
}
import java.util.Arrays;
import java.util.List;
These notes provide an overview of threads, collections, and the Stream API in Java. Let me know
if you need more details or additional examples!
Java Notes 40