JAVA Unit-1
JAVA Unit-1
1. Introduction to Java
What is Java?
Why Java?
Java was created to allow programmers to write code that can run anywhere. The concept is known
as “Write Once, Run Anywhere.” This is possible because Java code is compiled into bytecode
which runs on the Java Virtual Machine (JVM), making it independent of the operating system.
Java Architecture
When a Java program is compiled, the source code is converted into bytecode by the Java compiler.
The bytecode is platform-independent and can be executed on any machine that has the JVM
installed.
• Simple: Easy to understand, similar to C and C++ but without complex features like pointers and
operator overloading
• Secure: Java does not allow explicit use of pointers, and has a security manager
C++ and Java are both programming languages, but they have some key differences.
Page 2
C++ is a more complex language than Java. It’s a general-purpose language that can be used
for a variety of tasks, including game development, system programming, and web
development.
Java is a more simpli ed language than C++. It’s a general-purpose language that’s often used
for mobile app development and web development.
Java is more platform-independent than C++. Java code can run on any platform that has the
Java Virtual Machine (JVM) installed.
C++ is more secure than Java. C++ code is more dif cult to exploit than Java code.
In summary, C++ is a more complex language than Java, and Java is more platform-
independent than C++.
- Keywords: These are special words in Java that have a speci c meaning. You can’t use them as
variable names. Examples include ‘class’, ‘public’, ‘static’, ‘void’, ‘int’, ‘return’, ‘if’, ‘else’,
‘while’, ‘try’, ‘catch’, ‘extends’, ‘implements’, ‘ nal’, ‘private’, ‘protected’, and ‘this’. Some
keywords are reserved but not used, like ‘goto’ and ‘const’.
fi
fi
fi
fi
Page 3
- Identi ers: These are names for variables, methods, and classes.
- Operators: These are symbols used to perform operations, like addition or comparison.
- Separators: These are used to separate code elements, like semicolons, commas, braces, and
brackets.
4. Keywords in Java
Java has a set of reserved words that have a speci c meaning. You can’t use them as variable
names. Here are some examples:
Java has two main types of data types: primitive and non-primitive.
fi
fi
fi
fi
fi
fi
fi
Page 4
- Primitive Data Types: These are the basic data types provided by Java.
Access speci ers determine how accessible classes, variables, and methods are
- Public: This access modi er allows variables, methods, and classes to be accessed from
anywhere in the program.
fl
fi
fi
fi
fl
fi
fi
fi
fl
fi
Page 5
- Private: This access modi er restricts variables, methods, and classes to be accessed only within
the same class.
- Protected: This access modi er allows variables, methods, and classes to be accessed within the
same package and by subclasses in other packages.
- Default (no keyword): This access modi er allows variables, methods, and classes to be
accessed only within the same package.
- int id
• Variables
• Methods
• Classes
• Packages
• Interfaces
Examples:
A package in Java is a collection of related classes and interfaces. It helps organize code into
namespaces and avoids class name con icts.
Types of Packages:
◦ java.net – networking
class Test {
public static void main(String args[]) {
MyClass obj = new MyClass(); // Using the class from
the package
obj.display();
}
}
fi
fl
Page 7
3. Sub-Packages
What is a Sub-Package?
Example:
If you have:
• package university.students;
package university.students;
import university.students.Student;
class Test {
public static void main(String args[]) {
Student s = new Student();
s.info();
}
}
Behavior:
• The member is accessible within the same package but not from outside the package.
Example:
2. Inheritance
3. Abstraction
4. Polymorphism
A class is a blueprint or template that de nes the structure (attributes) and behavior (methods) of
objects.
Components of a Class:
Syntax of a Class:
class ClassName {
// Fields
dataType fieldName;
// Constructor
ClassName(parameters) {
// Initialization
}
// Methods
returnType methodName(parameters) {
// Method body
}
}
Example:
class Car {
String color;
int speed;
void accelerate() {
speed += 10;
}
}
Object
Creating an Object:
2. Inheritance in Java
Inheritance allows a subclass (child class) to inherit properties and methods from a superclass
(parent class).
Bene ts:
• Code Reusability
• Method Overriding
• Polymorphism
Types of Inheritance:
1. Single Inheritance:
class A { }
class B extends A { }
2. Multilevel Inheritance:
class A { }
class B extends A { }
class C extends B { }
3. Hierarchical Inheritance:
class A { }
class B extends A { }
class C extends A { }
4. Multiple Inheritance (via Interfaces only):
interface A { }
interface B { }
class C implements A, B { }
Example:
class Animal {
void eat() {
fi
Page 11
System.out.println("Eating...");
}
}
3. Abstraction in Java
Abstraction hides implementation details and shows only the essential features.
1. Abstract Classes
2. Interfaces
Abstract Class:
• Cannot be instantiated
Syntax:
Syntax:
interface InterfaceName {
void method1();
default void method2() { }
static void method3() { }
}
Example:
interface Drawable {
void draw();
}
4. Polymorphism in Java
fi
fi
Page 13
Polymorphism means "many forms" and allows methods to behave differently based on the object
type.
Types:
Method Overloading:
Example:
class Calculator {
int add(int a, int b) {
return a + b;
}
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
How to Achieve:
Example:
class Student {
private String name;
• Data Hiding
• Controlled Access
• Flexibility
• Reusability
• Maintainability
Pack Up
OOP
De nition Example
Concept
Class Blueprint for objects class Car { }
Object Instance of a class Car myCar = new Car();
Inheritance Child inherits from parent class Dog extends Animal
Abstraction Hiding complex details abstract class Shape
Polymorphis Same method, different add(int, int) vs
m behavior add(double)
Encapsulation Binding data and methods private + getters/setters
class Outer {
private int x = 10;
class Inner {
void display() {
System.out.println(x);
}
}
}
fi
Page 16
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.display(); // Output: 10
}
}
2. Static Inner Class
class Outer {
static int y = 20;
class Outer {
void outerMethod() {
class LocalInner {
void display() {
System.out.println("Local Inner Class");
}
}
LocalInner inner = new LocalInner();
inner.display();
}
}
4. Anonymous Inner Class
interface Greeting {
void greet();
}
class Parent {
static void show() { System.out.println("Parent"); }
}
class Child extends Parent {
static void show() { System.out.println("Child"); }
}
public class Main {
public static void main(String[] args) {
Parent obj = new Child();
obj.show(); // Output: Parent
}
}
2. Final Methods: Cannot Be Overridden
class Parent {
final void display() { System.out.println("Parent"); }
}
class Child extends Parent {
// Error if overriding final method
}
3. Fields Are Not Polymorphic
3. Method Overloading
(A) Resolution Rules:
class Calculator {
void add(int a, int b) { System.out.println("int
version"); }
void add(double a, double b) { System.out.println("double
version"); }
}
class Test {
void print(Integer i) { System.out.println("Integer"); }
Page 19
void print(String s) { System.out.println("String"); }
}
class Adder {
int add(int a, int b) { return a + b; }
// double add(int a, int b) { return a + b; } // Compile
Error
}
class BankAccount {
private double balance;
class Address {
private String city;
// getters/setters
}
class Person {
private Address address;
Real-life example:
Imagine you are trying to withdraw money from an ATM. If your account has insuf cient balance,
the machine throws an error and stops the transaction. Similarly, Java throws exceptions when
something unexpected occurs.
• Error: Serious issues that are not meant to be handled (e.g., hardware failure, JVM crash).
• Checked Exceptions: Checked at compile time. Must be either caught or declared using
throws.
4. Types of Exceptions
A. Checked Exceptions
import java.io.FileReader;
• Occur during program execution and are not checked at compile time.
catch block:
nally block:
Optional. Runs after try and catch, whether an exception occurs or not. It is used to release
resources.
try {
int[] numbers = new int[3];
System.out.println(numbers[5]); // This line throws an
exception
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
} finally {
System.out.println("This block always executes.");
}
Used in method declarations to indicate that the method may throw an exception.
try {
int[] numbers = null;
System.out.println(numbers.length);
} catch (NullPointerException e) {
System.out.println("Null Pointer Exception caught");
} catch (Exception e) {
System.out.println("General Exception caught");
}
You can also catch multiple exceptions in a single catch block (Java 7+):
8. Custom Exceptions
Java allows you to create your own exceptions by extending the Exception class. This is useful
for business-speci c error handling.
class Voter {
void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Not eligible to
vote");
}
}
}
9. try-with-resources
Introduced in Java 7, it automatically closes resources like les or database connections.
• Do not leave catch blocks empty. Always log or handle the exception properly.
Wrap Up
Concept Description
try Wraps code that might throw an exception
catch Handles the exception
nally Executes after try/catch regardless of the outcome
throw Manually throws an exception
throws Declares exceptions in method signature
Checked Exception Must be handled at compile time
Unchecked
Occurs at runtime, optional to handle
Exception
User-de ned exception extending Exception
Custom Exception
class
fi
fi
fi
fi