[go: up one dir, main page]

0% found this document useful (0 votes)
3 views24 pages

JAVA Unit-1

The document provides an overview of Java, a high-level, object-oriented programming language, highlighting its key features such as platform independence, security, and robustness. It also compares Java with C++, discusses Java tokens, keywords, data types, access specifiers, and introduces core object-oriented programming principles like inheritance, abstraction, polymorphism, and encapsulation. Additionally, it explains the structure of classes and objects, memory allocation, and the concept of packages and sub-packages in Java.
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)
3 views24 pages

JAVA Unit-1

The document provides an overview of Java, a high-level, object-oriented programming language, highlighting its key features such as platform independence, security, and robustness. It also compares Java with C++, discusses Java tokens, keywords, data types, access specifiers, and introduces core object-oriented programming principles like inheritance, abstraction, polymorphism, and encapsulation. Additionally, it explains the structure of classes and objects, memory allocation, and the concept of packages and sub-packages in Java.
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
You are on page 1/ 24

Page 1

Chapter 1: Java Fundamentals

1. Introduction to Java

What is Java?

Java is a high-level, object-oriented programming language created by James Gosling in 1995 at


Sun Microsystems. It’s now maintained by Oracle Corporation. It was designed to be simple,
secure, and platform-independent.

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.

Main Features of Java

• Simple: Easy to understand, similar to C and C++ but without complex features like pointers and
operator overloading

• Object-Oriented: Everything is treated as an object

• Platform-Independent: Code runs on JVM, not directly on OS

• Secure: Java does not allow explicit use of pointers, and has a security manager

• Robust: Strong memory management and exception handling

• Multithreaded: Java allows multiple threads of execution

• Portable: Code can run across different platforms

• Distributed: Supports remote method invocation and networking features

• High Performance: Uses Just-In-Time compiler for better performance

2. Difference Between C++ and Java

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++.

Feature C plus plus Java


Platform Platform dependent Platform independent using JVM
Memory Manual using new and
Automatic using Garbage Collector
Management delete
Pointers Supports explicit pointers Does not support pointers
Not supported directly, uses
Multiple Inheritance Supported using classes
interfaces
Compilation Compiled to machine code Compiled to bytecode
Header Files Uses include preprocessor Uses import statements for packages
Operator
Supported Not supported
Overloading
Global Variables Allowed Not allowed
Structure and Union Supported Not supported
Exception Handling Basic support Robust built-in handling
3. Java Tokens
Java programs are made up of tiny pieces called tokens. The compiler recognizes these tokens.

Here are some types of tokens:

- 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.

- Literals: These are constant values like numbers or characters.

- 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:

- ‘class’: De nes a class.

- ‘public’: Makes a class public.

- ‘static’: Makes a method static.

- ‘void’: Makes a method void.

- ‘int’: Makes a variable an integer.

- ‘return’: Returns a value from a method.

- ‘if’: Conditionally executes a block of code.

- ‘else’: Executes a block of code if the ‘if’ condition is false.

- ‘while’: Repeats a block of code as long as a condition is true.

- ‘try’: Attempts to execute a block of code.

- ‘catch’: Handles errors that occur during execution.

- ‘extends’: De nes a class that extends another class.

- ‘implements’: De nes a class that implements an interface.

- ‘ nal’: Makes a variable nal.

- ‘private’: Makes a variable private.

- ‘protected’: Makes a variable protected.

- ‘this’: Accesses the current object.

- ‘super’: Accesses the superclass.

5. Data Types in Java

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.

• - ‘byte’: Represents a single byte of data, ranging from -128 to 127.

• - ‘short’: Represents a short integer, which is 2 bytes.

• - ‘int’: Represents an integer, which is 4 bytes.

• - ‘long’: Represents a long integer, which is 8 bytes.

• - ‘ oat’: Represents a oating-point number, which is 4 bytes.

• - ‘double’: Represents a double-precision oating-point number, which is 8 bytes.

• - ‘char’: Represents a single character.

• - ‘boolean’: Represents a boolean value, which is 1 bit.

- Non-Primitive Data Types: These refer to objects and include:

- ‘String’: Represents a string of characters.

- ‘Array’: Represents a collection of elements.

- ‘Class’: Represents a class de nition.

- ‘Interface’: Represents a class interface.

- ‘Enum’: Represents a class with prede ned values.

6. Access Speci ers: public, private, protected

Access speci ers determine how accessible classes, variables, and methods are

Modi e Accessible in Same Same Subclass (Other Everywher


r Class Package Package) e
private Yes No No No
default Yes Yes No No
protecte
Yes Yes Yes No
d
public Yes Yes Yes Yes
Here’s a breakdown of the different access modi ers in Java:

- 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

1. Java Identi ers


What is an Identi er?

An identi er is the name used to identify:

• Variables

• Methods

• Classes

• Packages

• Interfaces

Rules for Writing Identi ers in Java:

1. Must begin with a letter (A–Z or a–z), underscore _, or dollar sign $

2. Cannot begin with a digit (0–9)

3. Cannot use Java reserved keywords like int, class, public

4. Case-sensitive: RollNumber and rollNumber are different

5. No special characters like @, #, !, %, etc.

6. Can be of any length

Examples:

Valid Identi ers Invalid Identi ers


studentNam
123name
e
_value int (keyword)
emp-name
$salary
(hyphen)
fi
fi
fi
fi
fi
fi
fi
fi
fi
Page 6

MAX_VALUE void (keyword)

2. Packages and Sub-Packages


What is a Package?

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:

1. Built-in Packages – provided by Java:


◦ java.lang – fundamental classes (automatically imported)

◦ java.util – collections, date, etc.

◦ java.io – input and output

◦ java.net – networking

◦ java.sql – database access

2. User-de ned Packages – created by the programmer.


Example:

package mypackage; // Package declaration (must be the


first line)

public class MyClass {


public void display() {
System.out.println("Hello from MyClass");
}
}
Accessing Classes from Packages:

import mypackage.MyClass; // Importing a class from user-


defined package

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?

A subpackage is a package inside another package.


Java does not support automatic import of subpackages; you must import them explicitly.

Example:

If you have:

• package university.students;

It is a sub-package students inside the main package university.

package university.students;

public class Student {


public void info() {
System.out.println("Student Details");
}
}
To use this:

import university.students.Student;

class Test {
public static void main(String args[]) {
Student s = new Student();
s.info();
}
}

4. Default Access Modi er (Package-Private)


If no access modi er (like public, private, protected) is speci ed, then the default
access modi er is applied.

Behavior:

• The member is accessible within the same package but not from outside the package.

• Also called package-private access.

Example:

class MyClass { // default access


fi
fi
fi
fi
Page 8
void show() { // default access
System.out.println("Hello");
}
}
• This class and method are accessible only within the same package.

Table for Access Levels:

Same Same Subclass (diff Other


Modi er
Class Package pkg) Packages
private ✔ ✘ ✘ ✘
default ✔ ✔ ✘ ✘
protecte
✔ ✔ ✔ ✘
d
public ✔ ✔ ✔ ✔

Object-Oriented Programming (OOP)


Object-Oriented Programming (OOP) is a programming paradigm that organizes software design
around objects rather than functions and logic. Java is a purely object-oriented language that
implements the following core OOP principles:

1. Classes and Objects

2. Inheritance

3. Abstraction

4. Polymorphism

5. Encapsulation and Data Privacy

6. Method Overloading vs. Method Overriding

1. Classes and Objects in Java


Class

A class is a blueprint or template that de nes the structure (attributes) and behavior (methods) of
objects.

Components of a Class:

• Fields (Variables): Store the state of an object.

• Methods (Functions): De ne the behavior of an object.


fi
fi
fi
Page 9
• Constructors: Initialize objects.

• Blocks: Used for initialization.

• Nested Classes: Classes inside another 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;

Car(String color, int speed) {


this.color = color;
this.speed = speed;
}

void accelerate() {
speed += 10;
}
}
Object

An object is an instance of a class. It has:

• State (stored in elds)

• Behavior (de ned by methods)

Creating an Object:

ClassName objectName = new ClassName();


fi
fi
Page 10
Example:

Car myCar = new Car("Red", 0);


myCar.accelerate(); // speed increases to 10
Memory Allocation:

• Objects are stored in the Heap.

• Reference variables are stored in the Stack.

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...");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Barking...");
}
}

public class Main {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat();
dog.bark();
}
}

3. Abstraction in Java
Abstraction hides implementation details and shows only the essential features.

Ways to Achieve Abstraction:

1. Abstract Classes

2. Interfaces

Abstract Class:

• Cannot be instantiated

• Can have abstract and concrete methods

Syntax:

abstract class AbstractClass {


abstract void abstractMethod();
void concreteMethod() {
// Body
}
}
Example:

abstract class Shape {


abstract void draw();
Page 12
void display() {
System.out.println("Displaying shape...");
}
}

class Circle extends Shape {


void draw() {
System.out.println("Drawing Circle");
}
}
Interface:

• Contains abstract methods by default

• From Java 8, can also have default and static methods

Syntax:

interface InterfaceName {
void method1();
default void method2() { }
static void method3() { }
}
Example:

interface Drawable {
void draw();
}

class Circle implements Drawable {


public void draw() {
System.out.println("Drawing Circle");
}
}
Abstract Class vs Interface:

Abstract Class Interface


Partial abstraction Full abstraction
Single inheritance Multiple inheritance
Cannot have
Can have constructors
constructors
Can have non- nal
All variables are nal
variables

4. Polymorphism in Java
fi
fi
Page 13
Polymorphism means "many forms" and allows methods to behave differently based on the object
type.

Types:

1. Compile-time Polymorphism (Method Overloading)

2. Runtime Polymorphism (Method Overriding)

Method Overloading:

• Same method name, different parameters

• Happens in the same class

Example:

class Calculator {
int add(int a, int b) {
return a + b;
}

double add(double a, double b) {


return a + b;
}
}
Method Overriding:

• Same method name and parameters, different implementation

• Happens in parent and child classes

Example:

class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

5. Encapsulation and Data Privacy


Page 14
Encapsulation binds data and methods into one unit and restricts direct access to elds.

How to Achieve:

1. Make elds private

2. Provide public getter and setter methods

Example:

class Student {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

public class Main {


public static void main(String[] args) {
Student s = new Student();
s.setName("Alice");
System.out.println(s.getName());
}
}
Bene ts:

• Data Hiding

• Controlled Access

• Flexibility

• Reusability

• Maintainability

6. Method Overloading vs Method Overriding


Feature Method Overloading Method Overriding
Same method name, different Same method name and parameters in
De nition
parameters subclass
fi
fi
fi
fi
Page 15

Occurs in Same class Parent and child classes


Return Type Can be different Must be same or covariant
Polymorphis
Compile-time Runtime
m
add(int a, int b) vs add(double a,
Example Animal.sound() vs Dog.sound()
double b)

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

1. Static and Inner Classes


(A) Why Use Inner Classes?

• Group related classes (e.g., LinkedList.Node)

• Improve encapsulation (hide details)

• Access outer class private members

• Simplify code in GUI/event handling

(B) Types of Inner Classes:

1. Non-static (Regular) Inner Class

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;

static class StaticInner {


void display() {
System.out.println(y);
}
}
}

public class Main {


public static void main(String[] args) {
Outer.StaticInner inner = new Outer.StaticInner();
inner.display(); // Output: 20
}
}
3. Local Inner Class

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();
}

public class Main {


public static void main(String[] args) {
Page 17
Greeting greeting = new Greeting() {
public void greet() {
System.out.println("Hello, World!");
}
};
greeting.greet(); // Output: Hello, World!
}
}
(C) Key Differences: Static vs. Non-Static Inner Class

Feature Non-Static Inner Class Static Inner Class


Access to outer elds Yes Only static members
Requires outer
Yes No
instance
Holds reference to outer No reference to
Memory overhead
class outer

2. Runtime Polymorphism Limitations


(A) Limitations:

1. Static Methods: No Overriding (Method Hiding)

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

class Parent { int x = 10; }


fi
Page 18
class Child extends Parent { int x = 20; }

public class Main {


public static void main(String[] args) {
Parent obj = new Child();
System.out.println(obj.x); // Output: 10
}
}
(B) Real-World Analogy:

• Animal animal = new Dog();

• animal.sound() → Works polymorphically.

• animal.breed → Refers to Animal's version, not Dog's.

3. Method Overloading
(A) Resolution Rules:

• Exact match preferred over promotion.

• Type promotion: byte → short → int → long → float → double,


char → int

class Calculator {
void add(int a, int b) { System.out.println("int
version"); }
void add(double a, double b) { System.out.println("double
version"); }
}

public class Main {


public static void main(String[] args) {
Calculator calc = new Calculator();
calc.add(5, 5); // int version
calc.add(5.0, 5.0); // double version
calc.add(5, 5.0); // double version
}
}
(B) Common Pitfalls:

1. Ambiguity with Autoboxing

class Test {
void print(Integer i) { System.out.println("Integer"); }
Page 19
void print(String s) { System.out.println("String"); }
}

public class Main {


public static void main(String[] args) {
Test test = new Test();
test.print(null); // Error: Ambiguous
}
}
2. Return Type Alone Cannot Overload

class Adder {
int add(int a, int b) { return a + b; }
// double add(int a, int b) { return a + b; } // Compile
Error
}

4. Encapsulation Best Practices


(A) Immutable Class

public final class Student {


private final String name;
private final int age;

public Student(String name, int age) {


this.name = name;
this.age = age;
}

public String getName() { return name; }


public int getAge() { return age; }
}
(B) Validation in Setters

class BankAccount {
private double balance;

public void setBalance(double balance) {


if (balance >= 0) {
this.balance = balance;
} else {
throw new IllegalArgumentException("Balance
cannot be negative!");
}
Page 20
}
}
(C) Deep vs. Shallow Copy

class Address {
private String city;
// getters/setters
}

class Person {
private Address address;

public Address getAddress() {


Address copy = new Address();
copy.setCity(this.address.getCity());
return copy;
}
}

Exception Handling in Java


1. What is an Exception?
An exception is an event that occurs during the execution of a program that disrupts the normal
ow of instructions. It usually represents errors like dividing by zero, accessing an invalid array
index, or trying to read a le that doesn’t exist.

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.

2. Difference Between Error and Exception


Featur Error Exception
e
De niti Serious issues that applications should not try Events that programs can handle and
on to handle. recover from.
Handlin Cannot be handled by code easily. Can be caught and handled using try-
g catch.
Exampl StackOver owError, OutOfMemoryError NullPointerException, IOException
es
fl
fi
fl
fi
fi
Page 21

3. Java Exception Hierarchy


In Java, all exceptions and errors are subclasses of the Throwable class. This class has two main
branches:

• Error: Serious issues that are not meant to be handled (e.g., hardware failure, JVM crash).

• Exception: Events that can be handled using Java code.

Exceptions are further divided into:

• Checked Exceptions: Checked at compile time. Must be either caught or declared using
throws.

• Unchecked Exceptions: Occur at runtime. Not checked by the compiler.

4. Types of Exceptions
A. Checked Exceptions

• These must be handled or declared using throws.

• Example: IOException, SQLException.

import java.io.FileReader;

public class Test {


public static void main(String[] args) throws Exception {
FileReader reader = new FileReader("file.txt"); //
Must be handled
}
}
B. Unchecked Exceptions

• These are subclasses of RuntimeException.

• Occur during program execution and are not checked at compile time.

• Examples: NullPointerException, ArithmeticException,


ArrayIndexOutOfBoundsException.

public class Example {


public static void main(String[] args) {
int a = 10 / 0; // ArithmeticException
}
}
Page 22

5. try, catch, and nally


try block:

Used to wrap the code that might throw an exception.

catch block:

Used to handle the exception.

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.");
}

6. throw vs. throws


throw:

Used to manually throw an exception.

throw new ArithmeticException("Division by zero");


throws:

Used in method declarations to indicate that the method may throw an exception.

void readFile() throws IOException {


FileReader reader = new FileReader("file.txt");
}
Both used together:

void checkAge(int age) throws IllegalArgumentException {


if (age < 18) {
throw new IllegalArgumentException("Age must be 18 or
above");
}
fi
fi
Page 23
}

7. Multiple catch blocks and multi-catch


You can catch multiple exceptions separately:

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+):

catch (ArithmeticException | NullPointerException e) {


System.out.println("Either arithmetic or null pointer
exception occurred");
}

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 InvalidAgeException extends Exception {


public InvalidAgeException(String message) {
super(message);
}
}

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.

try (FileReader reader = new FileReader("file.txt")) {


fi
fi
Page 24
// Use the resource
} catch (IOException e) {
System.out.println("File not found");
}
// FileReader is automatically closed
Any class that implements AutoCloseable or Closeable can be used in try-with-
resources.

10. Best Practices


• Use speci c exception types instead of the generic Exception.

• Use custom exceptions for application-speci c conditions.

• Always clean up resources using finally or try-with-resources.

• Do not catch Throwable or Error unless absolutely necessary.

• 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

You might also like