JAVA PROGRAMMING FULL NOTES
JAVA PROGRAMMING FULL NOTES
JAVA PROGRAMMING
NOTES
PREPARED BY click to know
Neither here
Nor here
2|Page
UNIT I:
3|Page
Java Features
Java boasts several key features:
Java Evolution
Java was developed by James Gosling and his team at Sun
Microsystems in 1991 as part of the "Green Project." Initially named
Oak, it was designed for interactive consumer electronics like
televisions. However, the team realized its potential for web
development, leading to its rebranding as Java in 1995. The name
"Java" was inspired by coffee, reflecting its creators’ love for coffee
from Java Island.
Over the years, Java has undergone significant updates to improve its
performance, security, and developer experience:
1. Java 1.0 (1996): Introduced core features like applets, AWT, and
platform independence.
1. Platform Dependency
2. Memory Management
3. Performance
4. Pointers
5. Multiple Inheritance
7. Applications
In essence, the JVM executes the program, while the JRE provides the
essential resources for its execution.
9|Page
Primitive types are predefined and hold simple values, while non-
primitive types are created by the programmer and can hold multiple
values or methods.
Variables
Variables are containers for storing data values. In Java, you must
declare a variable with a specific type before using it:
int number = 5;
Operators
Java operators are special symbols that perform operations on
variables or values. They can be classified into several categories based
on their functionality. These operators play a crucial role in performing
arithmetic, logical, relational, and bitwise operations etc.
float x;
byte y;
...
...
y=(byte)x;
int x=30;
float y;
y=x; // y==30.000000.
12 | P a g e
Strings
String is the type of objects that can store the sequence of characters
enclosed by double quotes, defined by the String class. Strings are
immutable, once created their value cannot change.
Common methods:
Example:
System.out.println(name.toUpperCase());
Equality Test
• Primitive types: Use == to compare values.
String a = "hello";
String b = "hello";
System.out.println(a.equals(b)); // true
13 | P a g e
System.in
System.out
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
15 | P a g e
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
ARRAYS
Arrays are fundamental structures in Java that allow us to store
multiple values of the same type in a single variable. They are useful for
storing and managing collections of data.
int[] arr = { 1, 2, 3, 4, 5 };
1. Array Declaration
type[] arrayName;
2. Create an Array
To create an array, you need to allocate memory for it using the “new”
keyword
16 | P a g e
We can access array elements using their index, which starts from 0:
5. Array Length
System.out.println(numbers[i]);}
17 | P a g e
Example:
//output
Number of arguments: 3
Argument 1: Hello
Argument 2: World
Argument 3: 123
18 | P a g e
1. Declaration:
int[][] raggedArray;
2. Initialization:
int[][] raggedArray = {
};
3. Accessing Elements:
System.out.println(raggedArray[1][2]); // Outputs: 5
19 | P a g e
Vectors
A Vector is a growable array-like data structure provided by Java's
java.util package. Unlike arrays, Vectors can dynamically resize as
elements are added. Vectors are synchronized, making them thread-
safe.
1. Declaration
2. Adding Elements
vector.add(10);
vector.add(20);
3. Accessing Elements
System.out.println(vector.get(0)); // Outputs: 10
20 | P a g e
UNIT II:
21 | P a g e
Classes in Java
A class is a blueprint for creating objects. It defines fields (variables)
and methods (functions) that describe the behavior of an object.
Example:
class Car {
String model;
int speed;
void accelerate() {
speed += 10;
Objects in Java
An object is an instance of a class. It has state (values of instance
variables) and behavior (methods).
Creating an Object:
myCar.model = "Tesla";
myCar.accelerate();
Relationships in Java
Java supports different types of class relationships:
class Engine { }
class Car {
Engine engine;
}
23 | P a g e
class Vehicle { }
class Person {
return name;
}
24 | P a g e
class Person {
name = newName;
Advantages:
class Student {
String name;
int age;
// Constructor
Student(String n, int a) {
name = n;
age = a;
// Method
void display() {
}
26 | P a g e
s1.display();
Key Points:
class Student {
String name;
Student(String name) {
this.name = name;
void display() {
s.display();
var Keyword
The var keyword was introduced in Java 10 as part of local variable
type inference. It allows the compiler to determine the data type of a
variable at compile-time, reducing redundancy in variable declarations.
However, Java remains a statically-typed language, meaning that once
a variable's type is inferred, it cannot change.
Syntax of var
Instead of explicitly specifying the type, you can use var, and the
compiler will automatically infer the correct type.
System.out.println(message);
System.out.println(number);
System.out.println(decimal);
}}
30 | P a g e
The compiler analyzes the assigned value and infers its data type.
Advantages of var
Implicit Parameters
class Car {
String model;
void display() {
}
32 | P a g e
car1.model = "Tesla";
Explicit Parameters
class MathOperations {
return a + b;
}}
33 | P a g e
Explanation:
Example:
class Example {
Private Methods
Private methods are only accessible within the same class.
class Demo {
System.out.println("Private Method");
Final Fields
A final field cannot be changed after initialization.
class Constants {
}
36 | P a g e
Example:
class Counter {
Counter() {
count++;
new Counter();
new Counter();
37 | P a g e
System.out.println(Counter.count); // Output: 2
Static Methods
Static methods can only access static fields and methods and cannot
use ‘this’ or ‘super’. They are called using the class name (e.g.,
ClassName.methodName()).
Example:
class MathUtils {
return x * x;
System.out.println(MathUtils.square(5)); // Output: 25
}
38 | P a g e
Syntax:
System.out.println("Hello, Java!");
Here,
Method Parameters
Method parameters are inputs passed to a method to perform
operations. They allow methods to work with different values
dynamically.
Syntax:
Example:
class Demo {
}}
40 | P a g e
Packages
A package in Java is a way to group related classes and interfaces to
organize code and avoid name conflicts.
Types of Packages:
Creating a Package:
}}
Using a Package:
obj.show();
}}
41 | P a g e
Object Construction
Object construction refers to the process of creating objects from a
class using a constructor. A constructor is a special method that
initializes an object when it is instantiated using the new keyword.
1. Default Constructor
Example:
class Car {
void display() {
2. Parameterized Constructor
Example:
class Car {
String model;
int year;
// Parameterized Constructor
Car(String m, int y) {
model = m;
year = y;
void display() {
3. Constructor Overloading
Example:
class Car {
String model;
int year;
// Default Constructor
Car() {
44 | P a g e
model = "Unknown";
year = 2000;
// Parameterized Constructor
Car(String m, int y) {
model = m;
year = y;
void display() {
A constructor can call another constructor in the same class using this().
Example:
class Car {
String model;
int year;
// Default Constructor
Car() {
}
46 | P a g e
// Parameterized Constructor
this.model = model;
this.year = year;
void display() {
}
47 | P a g e
Example:
class Demo {
}
48 | P a g e
UNIT III:
49 | P a g e
Defining Subclasses
Defining a subclass involves creating a new class that extends an
existing class (the superclass) using the extends keyword. This
mechanism allows the subclass to inherit fields and methods from the
superclass, promoting code reuse and logical organization. In a
subclass, you can add new methods and variables, or override inherited
methods to tailor behavior for the subclass. Overriding is achieved by
providing a new implementation for an inherited method. For example:
class Animal {
void makeSound() {
System.out.println("Some sound");
void makeSound() {
System.out.println("Bark");
Overriding Methods
Method overriding allows a subclass to provide a specific
implementation of a method already defined in its superclass. This
enables runtime polymorphism, meaning that the method call is
resolved at runtime based on the object's actual type. To override a
method, the subclass must define a method with the same name,
return type, and parameter list as the superclass method. Overriding is
applicable only to instance methods and does not work with static or
final methods.
Example:
class Animal {
void makeSound() {
void makeSound() {
System.out.println("Bark");
}
52 | P a g e
Subclass Constructors
When a subclass is instantiated, its constructor is responsible for
initializing the subclass's fields and may also need to initialize fields
inherited from its superclass. To facilitate this, the subclass constructor
can invoke the superclass's constructor using the super() keyword. This
call must be the first statement in the subclass constructor. If the
subclass constructor does not explicitly call a superclass constructor,
Java automatically inserts a call to the superclass's no-argument
constructor. However, if the superclass does not have a no-argument
constructor, the subclass must explicitly call one of the superclass's
constructors using super() with appropriate arguments; otherwise, a
compilation error will occur.
Example:
class Animal {
String name;
// Superclass constructor
Animal(String name) {
this.name = name;
}
53 | P a g e
String breed;
// Subclass constructor
this.breed = breed;
In this example, the Dog class extends the Animal class. The Dog
constructor calls the Animal constructor using super(name) to initialize
the name field inherited from Animal. This ensures that both the
inherited and subclass-specific fields are properly initialized.
54 | P a g e
Inheritance Hierarchies
Inheritance hierarchies represent the structured arrangement of classes
in a parent-child relationship where a general superclass is extended by
more specialized subclasses. This design pattern promotes code reuse,
organization, and clarity by centralizing common attributes and
methods in a superclass. Subclasses inherit these members while
adding their unique behaviors and properties, thus forming a hierarchy.
In hierarchical inheritance, multiple subclasses can extend the same
superclass, allowing them to share common functionality while
diverging in specialized implementations. Such hierarchies support
polymorphism, enabling objects of different subclasses to be treated
uniformly based on their shared superclass, which simplifies method
invocation and enhances maintainability.
Example:
// Superclass
class Vehicle {
void startEngine() {
System.out.println("Engine started.");
}}
// Subclass 1
void openTrunk() {
System.out.println("Trunk opened.");
55 | P a g e
}}
// Subclass 2
void popWheelie() {
System.out.println("Popping a wheelie!");
}}
}}
56 | P a g e
Polymorphism
Polymorphism, derived from the Greek for "many forms," is a
fundamental concept in Java and object-oriented programming that
allows objects to be treated as instances of their parent class rather
than their actual class. This capability enables a single interface to
represent different underlying data types, promoting flexibility and
integration in code design.
o Example:
class MathOperations {
return a + b;
return a + b + c;
return a + b;
o Example:
class Animal {
void makeSound() {
void makeSound() {
System.out.println("Bark");
void makeSound() {
System.out.println("Meow");
}
59 | P a g e
Animal myAnimal;
// Class implementation
}
61 | P a g e
System.out.println("Trying to override.");
Casting
Casting refers to converting a variable from one data type to another.
This is essential when working with different data types and classes,
especially in the context of inheritance and polymorphism. Java
supports two primary types of casting:
Abstract Classes
An abstract class serves as a blueprint for other classes, allowing
developers to define methods that must be implemented by
subclasses. Abstract classes cannot be instantiated directly; instead,
they provide a common structure for related classes.
Key Features:
Example:
void stop() {
void start() {
System.out.println("Car started.");
• public int hashCode(): Returns a hash code value for the object.
• public final void wait(): Causes the current thread to wait until
another thread invokes the notify() method or the notifyAll()
method for this object.
67 | P a g e
equals() Method:
class EqualsMethod
boolean result;
result = str1.equals(str2);
System.out.println(result);
68 | P a g e
result = str1.equals(str3);
System.out.println(result);
result = str3.equals(str1);
System.out.println(result);
Output
true
false
false
69 | P a g e
hashCode() Method:
Syntax:
toString() Method:
Syntax:
return
getClass().getName()+"@"+Integer.toHexString(hashCode());
}
70 | P a g e
stringList.add("Hello");
stringList.add("World");
Example:
import java.util.ArrayList;
numbers.add(10);
numbers.add(20);
numbers.add(30);
// Access elements
System.out.println(number);
}
73 | P a g e
These conversions are handled by the Java compiler, allowing for more
concise and readable code.
Example:
Syntax:
// method body
Example:
class VarargsExample {
for (String i : n) {
System.out.println();
Names("name1", "name2");
Output
name1 name2
UNIT IV:
78 | P a g e
Interfaces: Defining
An interface is a blueprint of a class. It has static constants and abstract
methods.
In other words, we can say that interfaces can have abstract methods
and variables. It cannot have a method body.
Syntax:
interface <interface_name>{
// by default.
Example:
interface Animal {
void eat();
void sleep();
}
79 | P a g e
Cannot be instantiated;
Specifies a set of
contains both abstract
methods a class must
(without implementation)
80 | P a g e
Static Methods:
• They are useful for providing utility methods that are related to
the interface.
Example:
interface Calculator {
static int add(int a, int b) {
return a + b;
}
}
Private Methods:
• They can only be accessed from within the interface, not from
implementing classes.
• They are useful for breaking down complex default methods into
smaller, more manageable methods.
Example:
interface MyInterface {
default void doSomething() {
stepOne();
stepTwo();
}
Default methods
Before Java 8, interfaces could only have abstract methods. The
implementation of these methods has to be provided in a separate
class. So, if a new method is to be added in an interface, then its
implementation code has to be provided in the class implementing the
same interface. To overcome this issue, Java 8 has introduced the
concept of default methods which allow the interfaces to have
methods with implementation without affecting the classes that
implement the interface.
Example:
interface TestInterface
// abstract method
// default method
}
84 | P a g e
System.out.println(a*a);
d.square(4);
d.show();
Output:
16
Causes:
• Multiple inheritance
Solutions:
Example:
import java.util.*;
numbers.sort(descendingComparator);
}}
87 | P a g e
Example:
String name;
int age;
this.name = name;
this.age = age;
@Override
return super.clone();
}
89 | P a g e
Lambda expressions
Lambda expressions, introduced in Java 8, provide a concise way to
represent anonymous functions (methods without a name). They are
used to implement functional interfaces —interfaces with a single
abstract method (SAM). Lambda expressions improve code readability
and reduce boilerplate code by eliminating the need for anonymous
inner classes.
Key Features:
1. Syntax :
(parameters) -> expression or
(parameters) -> { statements; }
Example:
interface MathOperation {
}
90 | P a g e
Explanation
Exception Handling:
Exception handling is a mechanism to handle runtime errors, ensuring
normal program flow. Exceptions are classified into Checked Exceptions
(compile-time), Unchecked Exceptions (runtime, e.g.,
`NullPointerException`), and Errors (serious issues like
`OutOfMemoryError`). It uses `try-catch`, `throw`, and `finally` for
effective error management.
Classification of Exceptions
a. Checked Exceptions
b. Unchecked Exceptions
• These are exceptions that occur at runtime and are not checked at
compile-time.
• Examples: NullPointerException,
ArrayIndexOutOfBoundsException.
92 | P a g e
c. Errors
If the caller doesn’t handle the exception, the compiler will throw an
error. Declaring checked exceptions ensures that potential issues are
acknowledged and managed. It forces developers to think about error
scenarios and handle them appropriately, improving code reliability.
94 | P a g e
Throwing an Exception
Throwing an exception means explicitly raising an exception in the
program using the throw keyword. This is useful when you detect an
error condition and want to signal it to the caller. For example:
super(message);
}}
try {
validateAge(15);
} catch (InvalidAgeException e) {
System.out.println(e.getMessage());
}}
}}}
96 | P a g e
Catching Exceptions
Catching exceptions involves using a try-catch block to handle runtime
errors gracefully. The try block contains code that may throw an
exception, and the catch block handles the exception if it occurs. For
example:
try {
} catch (ArithmeticException e) {
try {
} catch (ArrayIndexOutOfBoundsException e) {
} catch (Exception e) {
}
97 | P a g e
Rethrowing Exceptions
Rethrowing an exception means catching an exception and then
throwing it again to propagate it further up the call stack. This is useful
when you want to log or process an exception but still allow higher-
level methods to handle it. Example:
try {
} catch (IOException e) {
}
98 | P a g e
Finally Block
The finally block is used to execute important cleanup code, such as
closing files or releasing resources, regardless of whether an exception
occurs or not. It is always executed after the try block and any
associated catch blocks. Example:
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught");
} finally {
}
99 | P a g e
Try-With-Resources
Introduced in Java 7, try-with-resources ensures that resources (like
files, sockets, etc.) are closed automatically after use. Resources must
implement the AutoCloseable interface. Example:
int i;
System.out.print((char) i);
} catch (IOException e) {
}
100 | P a g e
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
e.printStackTrace();
Output:
java.lang.ArithmeticException: / by zero
at Example.main(Example.java:5)
101 | P a g e
Introduction to Multithreading
Multithreading is a programming concept that allows a single process
to execute multiple threads concurrently. It allows concurrent
execution of tasks within a single process, improving performance and
responsiveness. In Java, threads can be created by extending the
Thread class or implementing the Runnable interface. Proper
synchronization is essential to avoid race conditions and ensure thread
safety. While multithreading offers significant benefits, it also
introduces challenges like deadlocks and debugging complexity.
System.out.println("Thread is running");
}
102 | P a g e
System.out.println("Thread is running");
}}
}
103 | P a g e
Advantages of Multithreading
Key Concepts:
1. Streams:
2. Types of Streams :
3. Common Classes :
4. File Operations :
5. Try-With-Resources :
6. Error Handling :
String line;
System.out.println(line);
} catch (IOException e) {
}
107 | P a g e
Writing to a file
import java.io.*;
bw.write("This is a test.");
} catch (IOException e) {
}
108 | P a g e
Neither here
Nor here