[Go to site: main page, start]

0% found this document useful (0 votes)
4 views23 pages

Java Programming

The document provides detailed notes on Java programming for BCA/B.Tech 3rd Semester, covering four units: an overview of Java and its basic elements, arrays, strings, class fundamentals, inheritance, interfaces, exception handling, and packages. Key concepts include object-oriented programming principles, data types, control structures, and exception management. The notes emphasize Java's platform independence, the use of the Java Development Kit (JDK), and the importance of classes, constructors, and inheritance in Java programming.

Uploaded by

pawanrd2005
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)
4 views23 pages

Java Programming

The document provides detailed notes on Java programming for BCA/B.Tech 3rd Semester, covering four units: an overview of Java and its basic elements, arrays, strings, class fundamentals, inheritance, interfaces, exception handling, and packages. Key concepts include object-oriented programming principles, data types, control structures, and exception management. The notes emphasize Java's platform independence, the use of the Java Development Kit (JDK), and the importance of classes, constructors, and inheritance in Java programming.

Uploaded by

pawanrd2005
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

Java Programming – Detailed Notes (All 4 Units)

For: BCA/[Link] 3rd Semester (MDU, Rohtak)

Unit I – Overview of Java & Basic Language Elements Overview of Java & Basic Language
Elements Java is an object-oriented, platform-independent, and secure programming language.
Key features: simple, portable, robust, and multithreaded. Java Development Kit (JDK) includes
compiler, JVM, and libraries. Java Virtual Machine (JVM) executes bytecode, ensuring platform
independence. Basic elements include identifiers, keywords, literals, and data types. Operators
perform arithmetic and logical operations. Control statements like if-else, switch, for, while,
and do-while manage decision-making and loops.

Unit II – Arrays, Strings, and Class Fundamentals Arrays, Strings, and Class Fundamentals Arrays
are collections of similar data types. Types include single-dimensional and multi-dimensional
arrays. Strings are immutable objects of the String class; mutable versions include StringBuffer
and StringBuilder. A class defines data and behavior through variables and methods.
Constructors initialize objects. Access modifiers (public, private, protected, default) control
visibility. Method overloading and recursion are key class concepts.

Unit III – Inheritance and Interfaces Inheritance and Interfaces Inheritance enables a subclass to
inherit properties from a superclass using 'extends'. Supports single, multilevel, and hierarchical
types. The super keyword accesses parent members. Method overriding achieves runtime
polymorphism. The final keyword restricts modification. Interfaces achieve multiple inheritance
using 'implements'. They contain abstract methods and constants. Java 8 added default and
static methods. Interfaces provide abstraction and modular design.

Unit IV – Exception Handling and Packages Exception Handling and Packages Exceptions handle
runtime errors using try, catch, finally, throw, and throws. Checked exceptions are verified at
compile time; unchecked occur during runtime. Custom exceptions are created by extending
the Exception class. Packages organize related classes. Built-in packages include [Link],
[Link], [Link]. User-defined packages use the 'package' keyword. Import statements allow
use of external classes. Access modifiers define scope across packages
Unit I – Overview of Java & Basic Language Elements
1. Introduction to Java

 Java is an object-oriented, platform-independent, and secure programming


language developed by James Gosling at Sun Microsystems (1995).
 It follows the principle “Write Once, Run Anywhere (WORA)”, as compiled Java code
(bytecode) can run on any system having JVM.

Key Features of Java

1. Simple – Syntax is easy and similar to C/C++.


2. Object-Oriented – Everything is treated as an object.
3. Platform-Independent – Bytecode can run on any OS with JVM.
4. Robust – Exception handling and memory management reduce crashes.
5. Secure – No pointers, runs inside JVM sandbox.
6. Portable – Same program runs anywhere.
7. Multithreaded – Multiple tasks can run simultaneously.
8. Distributed – Supports networking and remote method invocation (RMI).

2. Java Development Environment

Java Development Kit (JDK)

 A software development kit for writing, compiling, and running Java programs.
 Includes:
o Compiler (javac)
o Java Virtual Machine (JVM)
o Java Runtime Environment (JRE)
o Java libraries & tools

Java Virtual Machine (JVM)

 Converts bytecode (.class) into machine code for the specific OS.
 Handles memory allocation and garbage collection.

Java Runtime Environment (JRE)

 Provides the environment for executing Java programs (includes JVM + libraries).
Steps to Run a Java Program

1. Write code → Save as .java file.


2. Compile: javac [Link] → creates .class file (bytecode).
3. Run: java filename → executes the program via JVM.

Example:

class HelloWorld {
public static void main(String args[]) {
[Link]("Hello, Java!");
}
}

3. Basic Language Elements

Identifiers

 Names used for variables, classes, methods, etc.


 Rules:
o Must start with a letter, _, or $.
o Case-sensitive.
o No spaces or keywords allowed.
o Example: studentName, addNumber.

Keywords

 Reserved words used by Java syntax (not usable as identifiers).


Example: class, int, static, public, if, while, void, return.

Literals

 Fixed constant values directly used in the program.


Types:
o Integer: 10, 200
o Float: 3.14
o Char: 'A'
o String: "Java"
o Boolean: true, false

Variables

 Used to store data values.


o Declaration: int a;
o Initialization: a = 5;
o Combined: int a = 5;
Data Types in Java

Category Type Size Example


Integer byte, short, int, long 1–8 bytes int x = 10;
Floating float, double 4–8 bytes float f = 3.14f;
Character char 2 bytes char c = 'A';
Boolean boolean 1 bit boolean flag = true;

4. Operators

Operators are symbols that perform operations on variables and values.

Type Examples Description


Arithmetic +, -, *, /, % Basic math operations
Increment/Decrement ++, -- Increase or decrease by 1
Relational <, >, <=, >=, ==, != Compare values
Logical &&, ||, ! Combine boolean expressions
Assignment =, +=, -=, *=, /= Assign values
Conditional ?: Ternary operator
Bitwise &, |, ^, <<, >> Operations on bits

5. Control Flow Statements

Decision-Making Statements

1. if Statement

if(a > b)
[Link]("a is greater");

2. if-else Statement

if(a > b)
[Link]("a is greater");
else
[Link]("b is greater");

3. Nested if

if(a > b) {
if(a > c)
[Link]("a is greatest");
}
4. switch Statement

switch(day) {
case 1: [Link]("Monday"); break;
case 2: [Link]("Tuesday"); break;
default: [Link]("Invalid day");
}

Looping Statements

1. for Loop

for(int i=1; i<=5; i++)


[Link](i);

2. while Loop

int i=1;
while(i<=5) {
[Link](i);
i++;
}

3. do-while Loop

int i=1;
do {
[Link](i);
i++;
} while(i<=5);

Jump Statements

 break: Exit loop or switch.


 continue: Skip current iteration.
 return: Exit from method.

✅Summary

 Java is platform-independent and object-oriented.


 Compilation → Bytecode → Execution via JVM.
 Understand keywords, variables, and data types.
 Control structures handle logic and repetition.
Unit II – Arrays, Strings, and Class Fundamentals

1. Arrays in Java

Definition

An array is a collection of similar data types stored in contiguous memory locations and
accessed using index numbers.

Syntax:

datatype[] arrayName = new datatype[size];

Example:

int[] marks = new int[5];


marks[0] = 90;
marks[1] = 85;

Types of Arrays

1. Single-Dimensional Array

int[] num = {10, 20, 30};


for(int i=0; i<[Link]; i++)
[Link](num[i]);

2. Multi-Dimensional Array (e.g., 2D array)

int[][] matrix = {{1,2}, {3,4}};


[Link](matrix[0][1]); // Output: 2

2. Operations on Arrays

 Traversing: Reading all elements.


 Insertion: Adding element at specific index.
 Deletion: Removing element (usually shifting elements).
 Searching: Finding an element’s position.
 Sorting: Arranging elements in order.

Example – Sum of array elements:

int[] a = {1, 2, 3, 4, 5};


int sum = 0;
for(int i : a)
sum += i;
[Link]("Sum = " + sum);

3. Strings in Java

Definition

A String is a sequence of characters enclosed in double quotes.


In Java, String is an object of the String class in the [Link] package.

Example:

String s1 = "Java";
String s2 = new String("Programming");

String Characteristics

 Immutable (cannot be changed once created).


 Stored in the String constant pool.
 Concatenation using +.

Common String Methods

Method Description Example


length() Returns string length [Link]()
charAt(i) Returns char at index [Link](2)
concat(str) Joins two strings [Link](s2)
equals(str) Compares two strings [Link](s2)
toUpperCase() Converts to uppercase [Link]()
substring(i,j) Extracts part of string [Link](2,5)
replace(a,b) Replaces characters [Link]('a','e')

4. Mutable & Immutable Strings

 Immutable Strings: Created using String class (cannot be changed).


 Mutable Strings: Created using StringBuffer or StringBuilder.

StringBuffer Example (Mutable)

StringBuffer sb = new StringBuffer("Hello");


[Link](" Java");
[Link](sb); // Output: Hello Java
StringBuilder Example

 Similar to StringBuffer but not synchronized (faster, used in single-threaded


applications).

5. Collection Basics (Introduction)

A Collection in Java is a group of objects that can be stored and manipulated together.
Example classes: ArrayList, HashSet, LinkedList.
(Detailed study of collections is not part of this semester’s syllabus but helps in practical use.)

6. Class Fundamentals

What is a Class?

 A class is a blueprint or template that defines data (variables) and behavior (methods) of
objects.

Creating a Class and Object

class Student {
int rollNo;
String name;

void display() {
[Link](rollNo + " " + name);
}
}

public class Test {


public static void main(String args[]) {
Student s1 = new Student();
[Link] = 101;
[Link] = "Ankush";
[Link]();
}
}

7. Object Lifecycle

1. Object Creation: Using new keyword.


2. Initialization: Assigning values.
3. Usage: Accessing methods and variables.
4. Destruction: JVM removes objects automatically via garbage collection.
8. Constructors

Definition

 A constructor is a special method used to initialize objects.


 Name of constructor = Class name.
 No return type (not even void).

Types of Constructors

1. Default Constructor

class Demo {
Demo() {
[Link]("Default Constructor");
}
}

2. Parameterized Constructor

class Demo {
int x;
Demo(int a) {
x = a;
}
}

9. Access Modifiers

Modifier Access Level Used For


public Everywhere Classes, methods, variables
private Within same class Data hiding
protected Same package + subclasses Inheritance
default (no keyword) Same package only Package access

10. Inner Classes

A class inside another class.


Types:

 Member Inner Class


 Static Nested Class
 Anonymous Inner Class
Example:

class Outer {
int x = 10;
class Inner {
void display() {
[Link]("x = " + x);
}
}
}

11. Abstract Classes & Methods

 An abstract class cannot be instantiated.


 Contains one or more abstract methods (without body).

abstract class Shape {


abstract void draw();
}

class Circle extends Shape {


void draw() {
[Link]("Drawing Circle");
}
}

12. Method Overloading

 Same method name but different parameters.

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

13. Recursion

 A method calling itself repeatedly until a condition is met.

Example:

int factorial(int n) {
if(n == 1) return 1;
else return n * factorial(n - 1);
}

✅Summary of Unit II

 Arrays manage multiple data elements.


 Strings are immutable; use StringBuffer for changes.
 Classes and objects are core of OOP.
 Constructors, access modifiers, overloading, and recursion are essential building blocks.

Unit III – Inheritance and Interfaces

1. Introduction to Inheritance

Definition:
Inheritance is an object-oriented programming (OOP) concept that allows a class
(subclass/child) to inherit properties and methods from another class (superclass/parent).

It promotes code reusability and method overriding.

2. Terminology

 Superclass (Parent class): Class whose members are inherited.


 Subclass (Child class): Class that inherits from another.
 extends keyword: Used for inheritance.

Example:

class Animal {
void eat() {
[Link]("Eating...");
}
}

class Dog extends Animal {


void bark() {
[Link]("Barking...");
}
}

public class TestInheritance {


public static void main(String args[]) {
Dog d = new Dog();
[Link]();
[Link]();
}
}

✅Output:

Eating...
Barking...
3. Types of Inheritance in Java

Type Description Supported by Java


Single One class inherits from another ✅ Yes
Multilevel Derived from another derived class ✅ Yes
Hierarchical Multiple classes inherit one base class ✅ Yes
Multiple One class inherits multiple classes ❌ No (but can be done using interfaces)
Hybrid Combination of above types Partially via interfaces

a) Single Inheritance

class A {
void showA() { [Link]("Class A"); }
}
class B extends A {
void showB() { [Link]("Class B"); }
}

b) Multilevel Inheritance

class A { void displayA() { [Link]("A"); } }


class B extends A { void displayB() { [Link]("B"); } }
class C extends B { void displayC() { [Link]("C"); } }

c) Hierarchical Inheritance

class A { void msg() { [Link]("Parent"); } }


class B extends A { void msgB() { [Link]("Child B"); } }
class C extends A { void msgC() { [Link]("Child C"); } }

4. The super Keyword

Used for three main purposes:

1. Access parent class data members


2. Invoke parent class methods
3. Call parent class constructor

Example:

class A {
int num = 10;
}
class B extends A {
int num = 20;
void show() {
[Link]([Link]); // Access parent variable
}
}

5. Constructor Chaining

When a subclass object is created, parent constructor executes first, then the subclass
constructor.

Example:

class A {
A() { [Link]("Parent constructor"); }
}
class B extends A {
B() { [Link]("Child constructor"); }
}
✅Output:

Parent constructor
Child constructor

6. Method Overriding

When a subclass defines a method with the same name and parameters as in the parent class.

 Used for runtime polymorphism.


 Requires inheritance.
 The @Override annotation is used.

Example:

class Animal {
void sound() { [Link]("Animal Sound"); }
}
class Dog extends Animal {
@Override
void sound() { [Link]("Bark"); }
}

7. Final Keyword

Used to restrict inheritance and modification.

Usage Example Effect


Usage Example Effect
final variable final int x = 10; Cannot be changed
final method final void show() Cannot be overridden
final class final class Demo {} Cannot be extended

8. Dynamic Method Dispatch (Runtime Polymorphism)

When a superclass reference variable refers to a subclass object, and the method to be
executed is determined at runtime.

Example:

class A { void display() { [Link]("A"); } }


class B extends A { void display() { [Link]("B"); } }

public class Test {


public static void main(String args[]) {
A obj = new B(); // Upcasting
[Link](); // Output: B
}
}

9. The Object Class

 Every class in Java implicitly inherits from the Object class.


 Common methods:
o toString()
o equals()
o hashCode()
o clone()
o getClass()

Example:

public String toString() {


return "Object Info";
}

Interfaces

1. Definition
An interface in Java is a fully abstract class that contains abstract methods and constants.
It is used to achieve multiple inheritance and abstraction.

Syntax:

interface Printable {
void print();
}
class Document implements Printable {
public void print() {
[Link]("Printing document...");
}
}

2. Features of Interfaces

 Contains abstract methods (implicitly public and abstract).


 All fields are public, static, and final.
 A class implements an interface using the implements keyword.
 A class can implement multiple interfaces.

3. Multiple Inheritance using Interfaces


interface A { void showA(); }
interface B { void showB(); }

class C implements A, B {
public void showA() { [Link]("A method"); }
public void showB() { [Link]("B method"); }
}

✅Output:

A method
B method

4. Extending Interfaces

Interfaces can also inherit other interfaces using the extends keyword.

interface A { void show(); }


interface B extends A { void display(); }

5. Default and Static Methods in Interfaces (Java 8+)


 Default Method: Has a body, can be overridden in subclass.
 Static Method: Belongs to interface, not to implementing class.

Example:

interface Vehicle {
default void start() {
[Link]("Vehicle started");
}
static void info() {
[Link]("Vehicle Info");
}
}

6. Abstract Classes vs Interfaces

Feature Abstract Class Interface


Keyword abstract interface
Methods Can have abstract + non-abstract Only abstract (and default/static)
Variables Can be non-final Always public, static, final
Inheritance Single Multiple
Constructors Yes No

7. Example Program
interface Shape {
void area();
}

class Circle implements Shape {


public void area() {
[Link]("Area = πr²");
}
}

class Rectangle implements Shape {


public void area() {
[Link]("Area = l × b");
}
}

public class TestInterface {


public static void main(String args[]) {
Shape s = new Circle();
[Link]();
}
}
✅Output:
Area = πr²
✅Summary of Unit III

 Inheritance → Code reuse and polymorphism.


 super → Access parent class members.
 Overriding → Redefining parent method in child.
 final → Restricts inheritance or modification.
 Interface → Achieves multiple inheritance and abstraction.

Unit IV – Exception Handling and Packages

1. Introduction to Exceptions
Definition
An exception is an abnormal condition or error that occurs during the execution of a program,
which disrupts its normal flow.
Java uses a structured method called Exception Handling to manage these runtime errors.

Example:
int a = 10, b = 0;
int c = a / b; // causes ArithmeticException

Without handling, the program terminates abruptly.


Exception handling ensures the program continues smoothly after managing errors.

2. Exception Hierarchy

All exceptions in Java are subclasses of the Throwable class.

Throwable
├── Exception
│ ├── IOException

│ ├── SQLException
│ ├── RuntimeException
│ ├── ArithmeticException
│ ├── NullPointerException
│ ├── ArrayIndexOutOfBoundsException
│ └── NumberFormatException
└── Error
├── OutOfMemoryError
├── StackOverflowError

3. Types of Exceptions

Type Description Examples


Checked Exceptions Checked at compile time IOException, SQLException
Type Description Examples
Unchecked ArithmeticException,
Occur at runtime
Exceptions NullPointerException
Serious issues beyond
Errors OutOfMemoryError, StackOverflowError
control

4. Exception Handling Mechanism

Java uses five keywords for handling exceptions:

Keyword Purpose
try Contains code that may cause exception
catch Handles the exception
finally Executes code always (cleanup)
throw Used to throw an exception manually
throws Declares exceptions in method signature

5. Using try–catch Block

Syntax:

try {
// risky code
} catch (ExceptionType e) {
// handling code
}
Example:

try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Cannot divide by zero!");
}
✅Output:

Cannot divide by zero!

6. Multiple catch Blocks


Used when a block can generate more than one type of exception.

try {
int a[] = new int[5];
a[5] = 10;
} catch (ArithmeticException e) {
[Link]("Arithmetic Error");
} catch (ArrayIndexOutOfBoundsException e) {
[Link]("Array Index Error");
}

7. Nested try Blocks

You can place a try block inside another try block.

try {
try {
int a = 10 / 0;
} catch (ArithmeticException e) {
[Link]("Inner catch");
}
} catch (Exception e) {
[Link]("Outer catch");
}

8. The finally Block

 Always executes, whether an exception occurs or not.


 Used for cleanup operations like closing files or connections.

Example:

try {
int x = 5 / 0;
} catch (Exception e) {
[Link]("Exception caught");
} finally {
[Link]("Finally block executed");
}
✅Output:

Exception caught
Finally block executed

9. The throw Keyword


Used to throw an exception manually.

Example:
throw new ArithmeticException("Division by zero not allowed");

10. The throws Keyword


Used to declare exceptions in a method signature.

Example:

void myMethod() throws IOException {


throw new IOException("File not found");
}

If a method may cause an exception, you must declare it with throws.

11. Creating User-Defined (Custom) Exceptions

We can create our own exceptions by extending the Exception class.

class InvalidAgeException extends Exception {


InvalidAgeException(String msg) {
super(msg);
}
}

class Test {
void checkAge(int age) throws InvalidAgeException {
if (age < 18)
throw new InvalidAgeException("Not eligible to vote");
else
[Link]("Eligible to vote");
}
}

12. Difference Between throw and throws

Basis throw throws


Purpose Used to throw an exception Declares exception in method
Position Inside method Method signature
Number Single exception Multiple exceptions
Example throw new IOException(); void f() throws IOException

13. Packages in Java

Definition

A package is a group of related classes, interfaces, and sub-packages.


They help in organizing code and avoiding name conflicts.
Types of Packages:

1. Built-in (Java API packages) – e.g., [Link], [Link], [Link], [Link]


2. User-defined packages – Created by programmers.

14. Creating a User-defined Package

Step 1: Create the package

package mypack;

public class Message {


public void show() {
[Link]("Hello from mypack");
}
}

Step 2: Compile the file

javac -d . [Link]

(The -d . option creates the folder structure automatically.)

Step 3: Use the package

import [Link];

class TestPackage {
public static void main(String args[]) {
Message m = new Message();
[Link]();
}
}

✅Output:

Hello from mypack

15. Access Modifiers in Packages

Accessible within same Same Subclass (other Other


Modifier
class package package) package
public ✅ ✅ ✅ ✅
Accessible within same Same Subclass (other Other
Modifier
class package package) package
protected ✅ ✅ ✅ ❌
default (no
✅ ✅ ❌ ❌
modifier)
private ✅ ❌ ❌ ❌

16. Importing Packages

Method Example
Import single class import [Link];
Import entire package import [Link].*;

17. Using Static Import (Java 5+)

Allows access to static members without class name.

Example:

import static [Link].*;


class Test {
public static void main(String args[]) {
[Link](sqrt(16)); // No need for [Link]()
}
}

✅Summary of Unit IV

Concept Key Idea


Exception Handling Manages runtime errors using try, catch, finally
throw / throws Used for manual and declared exceptions
Custom Exception Extend Exception class
Packages Organize and group related classes
Access Modifiers Control visibility across packages

You might also like