Bachelor of Computer Applications
Course Code BCA-S302T
Course Name Java Programming and Dynamic Webpage Design
Unit 1
Java is a high-level, object-oriented, and platform-independent programming language
developed by Sun Microsystems (now owned by Oracle Corporation) in 1995. It is designed to
have as few implementation dependencies as possible, which makes it ideal for building
applications that can run on many types of devices. It is widely used for building desktop, web,
and mobile applications, as well as large-scale enterprise systems.
Key Features of Java
1. Simple
o Easy to learn, especially for those with a background in C or C++.
2. Object-Oriented
o Everything in Java is an object (except primitive types).
o Emphasizes concepts like classes, inheritance, encapsulation, and polymorphism.
3. Platform-Independent
o Java code is compiled into bytecode, which runs on the Java Virtual Machine
(JVM), not directly on the OS.
o Bytecode is a highly optimized set of instructions designed to be executed by
what is called the Java Virtual Machine (JVM), which is part of the Java Runtime
Environment (JRE). In essence, the original JVM was designed as an interpreter
for bytecode.
o Write Once, Run Anywhere (WORA).
The designers of Java chose to use a combination of compilation and
interpretation. Programs written in Java are compiled into machine language, but
it is a machine language for a computer that doesn’t really exist. This so-called
“virtual” computer is known as the Java virtual machine. The machine language
for the Java virtual machine is called Java byte code. There is no reason why Java
bytecode could not be used as the machine language of a real computer, rather
than a virtual computer. However, one of the main selling points of Java is that it
can actually be used on any computer. All that the computer needs is an
interpreter for Java bytecode. Such an interpreter simulates the Java virtual
machine in the same way that Virtual PC simulates a PC computer.
Java Interpreter for
MAC OS
Java program Compiler java byte code Program
Java Interpreter for
Windows
Java Interpreter for
Linux
4. Secure
o Provides a secure runtime environment with features like bytecode verification
and sandboxing.
5. Robust
o Strong memory management and exception handling.
6. Multithreaded
o Supports multithreaded programming to perform multiple tasks simultaneously.
7. High Performance
o While not as fast as C/C++, Just-In-Time (JIT) compilers help boost performance.
8. Distributed
o Designed to support distributed computing via technologies like RMI and EJB.
Java Editions
1. Java SE (Standard Edition) – Core Java for general-purpose programming.
2. Java EE (Enterprise Edition) – For large-scale, distributed, web-based applications.
3. Java ME (Micro Edition) – For mobile and embedded devices.
4. JavaFX – For rich GUI applications.
Basic Structure of Java Program
public class HelloWorld
{
public static void main(String [] args)
{
System.out.println("Hello, World!");
}
}
Java Compilation Process
1. Source Code (.java) →
2. Compiler →
3. Bytecode (.class) →
4. JVM (Java Virtual Machine)` → Execution
Uses of Java
Android app development
Web servers and application servers
Financial services
Desktop GUI applications
Scientific and enterprise-level applications
Java Data Types
1. Primitive Data Types
These are the most basic types built into the Java language.
Data Type Size Description Example
byte 1 byte Small integers (-128 to 127) byte b = 100;
short 2 bytes Larger than byte (-32,768 to 32,767) short s = 30000;
int 4 bytes Default integer type int i = 123456;
long 8 bytes Very large integers long l = 123456789L;
float 4 bytes Single-precision decimal numbers float f = 5.75f;
double 8 bytes Double-precision decimal numbers double d = 19.99;
char 2 bytes Single Unicode character char c = 'A';
boolean 1 bit True or false values boolean b = true;
2. Non-Primitive (Reference) Data Types
These refer to objects and include:
Data Type Description Example
String Sequence of characters String s = "Hello";
Arrays Collection of elements of the same type int[] arr = {1, 2, 3};
Classes User-defined data types MyClass obj = new MyClass();
Interfaces Used for abstraction Runnable r = () -> {};
Control Structure in Java
In Java, control structures are used to control the flow of execution of a program. They are
essential for decision-making, looping, and branching. They fall into three main categories:
1. Decision-Making (Conditional) Statements
These statements allow your program to make choices based on conditions.
a) if statement
if (condition)
// code to execute if condition is true
b) if-else statement
if (condition) {
// true block
} else {
// false block
c) if-else if-else ladder
if (condition1) {
// code
} else if (condition2) {
// code
} else {
// default code
d) switch statement
switch (variable) {
case value1:
// code
break;
case value2:
// code
break;
default:
// default code
}
2. Looping Statements
Used to execute a block of code repeatedly.
a) for loop
for (int i = 0; i < 5; i++) {
System.out.println(i);
b) while loop
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
c) do-while loop
Executes at least once before checking the condition.
int i = 0;
do {
System.out.println(i);
i++;
} while (i < 5);
3. Branching Statements
Used to change the normal flow of execution.
a) break
Exits a loop or switch statement immediately.
for (int i = 0; i < 10; i++) {
if (i == 5) break;
System.out.println(i);
b) continue
Skips the current iteration and moves to the next one.
for (int i = 0; i < 5; i++) {
if (i == 2) continue;
System.out.println(i);
c) return
Exits from the current method.
public void display() {
System.out.println("Before return");
return;
// System.out.println("This won't be printed");
Basic Java Programs Based on control statements
1.Check whether a year is Leap Year or not.
2.Check whether a user is a Valid Voter or not.
3. Check whether a number is a Positive Number
4. Check whether a Number is Greater than 10
5. Find greatest among three numbers
6. Write a Java program that keeps a number from the user and generates an integer between 1
and 7 and displays the name of the weekday.
7. Write a Java program to find the number of days in a month
8.Write a program in Java to display the first 10 natural numbers
9.Write a program in Java to input 5 numbers from the keyboard and find their sum and average.
10. Write a program in Java to display the cube of the number up to a given an integer.
11.Write a program in Java to display the multiplication table of a given integer.
12.Check whether a given number is even or odd.
13.Check whether a given number is Palindrome Number
14.Check whether a given number is Armstrong Number
15. Find a Factorial of a number.
I/O in Java
Streams
Java programs perform I/O through streams. A stream is an abstraction that either produces or
consumes information. A stream is linked to a physical device by the Java I/O system. All
streams behave in the same manner, even if the actual physical devices to which they are linked
differ. Thus, the same I/O classes and methods can be applied to different types of devices. This
means that an input stream can abstract many different kinds of input: from a disk file, a
keyboard, or a network socket. Java implements streams within class hierarchies defined in the
java.io package.
Byte Streams and Character Streams
Java defines two types of streams: byte and character. Byte streams provide a convenient means
for handling input and output of bytes. Byte streams are used, for example, when reading or
writing binary data.
The Byte Stream Classes
Byte streams are defined by using two class hierarchies. At the top are two abstract classes:
InputStream and OutputStream. Each of these abstract classes has several concrete subclasses
that handle the differences among various devices, such as disk files, network connections, and
even memory buffers.
Stream Class Meaning
BufferedInputStream Buffered Input stream
BufferedOutputStream Buffered Output stream
FileInputStream Input stream that reads from file
FileOutputStream Output stream that writes to the file
Code for Writing and Reading Data from the buffer using BufferedInputStream and
BufferedOutputStream
import java.io.*;
import java.util.*;
public class InputOutput {
public static void main(String[] args) throws IOException {
File obj = new File("satish.txt");
BufferedOutputStream bout = new BufferedOutputStream(new FileOutputStream(obj));
bout.write(2);
System.out.println("file writing successful");
bout.close();
BufferedInputStream bin = new BufferedInputStream(new FileInputStream(obj));
int data=bin.read();
System.out.println(data);
bin.close();
}
}
Scanner Class in Java
The Scanner class in Java is a utility class found within the java.util package. Its primary purpose
is to facilitate the reading of input data from various sources, such as the console (standard
input), files, or strings. It is commonly used for obtaining user input and parsing different data
types.
Key features and uses of the Scanner class:
Input Acquisition:
It provides a convenient way to read primitive data types (like int, double, boolean)
and String values.
Parsing and Tokenization:
The Scanner class can break down input into tokens using a delimiter, which by default is
whitespace. This allows for easy extraction of individual words, numbers, or other data units.
Methods for Different Data Types:
It offers various methods to read specific data types, such as:
nextInt(): Reads the next integer.
nextDouble(): Reads the next double-precision floating-point number.
nextLine(): Reads the entire line, including spaces, until a newline character is encountered.
next(): Reads the next token (a word) until a whitespace character is encountered.
hasNextInt(), hasNextDouble(), etc.: Check if the next token matches a specific data type.
Example for Scanner Class
import java.util.Scanner;
public class Reverse {
public static void main(String[] args)
{
int rev=0,rem,num,n;
System.out.println("Enter the number");
Scanner Sc=new Scanner(System.in);
num=Sc.nextInt();
n=num;
while (num>0)
{
rem=num%10;
rev=rev*10+rem;
num=num/10;
}
System.out.println("The reverse of the number is\t"+rev);
if(n==rev)
{
System.out.println("the\t"+n+"\tis palindrome");
}
}
}
Arrays in Java
An array in Java is a data structure that stores multiple values of the same type in a single
variable.
Declaring an Array
int[] numbers; // declaration
numbers = new int[5]; // allocation (size 5)
Or in one line:
int[] numbers = new int[5];
Initializing an Array
int[] numbers = {10, 20, 30, 40, 50};
Accessing Array Elements
Array indices start at 0.
System.out.println(numbers[0]); // prints 10
numbers[1] = 25; // update second element
Iterating Over an Array
Using for loop:
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
Using enhanced for loop:
for (int num : numbers) {
System.out.println(num);
}
Full Example: Sum of Array Elements
public class ArraySum {
public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
int sum = 0;
for (int num : numbers) {
sum += num;
}
System.out.println("Sum: " + sum);
}
}
Array based programs
Read and display elements of an array
Find the sum and average of array elements
Find the maximum and minimum element in an array
Search an element in an array (Linear Search)
Count even and odd numbers in an array
String in Java
A String in Java is a sequence of characters. Strings are immutable, meaning once created, their
values cannot be changed.
Java provides the String class in the java.lang package to handle string data.
Declaring and Initializing Strings
String s1 = "Hello"; // using string literal
String s2 = new String("World"); // using 'new' keyword
Common String Methods
Method
length() Returns length of the string
charAt(index) Returns character at specified index
equals(s2) Checks string equality (case-sensitive)
equalsIgnoreCase(s2) Checks equality ignoring case
compareTo(s2) Lexicographically compares two strings
substring(start, end) Returns substring
toLowerCase() Converts string to lowercase
toUpperCase() Converts string to uppercase
indexOf(char) Returns first index of the character
replace(a, b) Replaces character or substring
trim() Removes leading and trailing spaces
split(" ") Splits string into array using delimiter
Example: Using String Methods
public class StringExample {
public static void main(String[] args) {
String str = " Java Programming ";
System.out.println("Original: '" + str + "'");
System.out.println("Length: " + str.length());
System.out.println("Trimmed: '" + str.trim() + "'");
System.out.println("Uppercase: " + str.toUpperCase());
System.out.println("Substring (5 to 16): " + str.substring(5, 16));
System.out.println("Replace 'a' with 'x': " + str.replace('a', 'x'));
Output
Original: ' Java Programming '
Length: 20
Trimmed: 'Java Programming'
Uppercase: JAVA PROGRAMMING
Substring (5 to 16): Programming
Replace 'a' with 'x': Jxvx Progrxmming
String Comparison
String a = "hello";
String b = "HELLO";
System.out.println(a.equals(b)); // false
System.out.println(a.equalsIgnoreCase(b)); // true
Vectors in Java
A Vector in Java is a dynamic array that can grow or shrink in size. It is part of the java.util
package and implements the List interface. Unlike arrays, Vectors can automatically resize and
are synchronized.
Importing Vector
import java.util.Vector;
Creating a Vector
Vector<Integer> v = new Vector<>();
Vector<String> names = new Vector<String>();
Common Methods of Vector
Method Description
add(element) Adds element at the end
add(index, element) Inserts element at specified index
get(index) Returns element at specified index
set(index, element) Updates element at index
remove(index) Removes element at specified index
size() Returns number of elements
clear() Removes all elements
contains(element) Checks if element exists
isEmpty() Checks if vector is empty
firstElement() Returns first element
lastElement() Returns last element
Example Program: Using Vector
import java.util.Vector;
public class VectorExample {
public static void main(String[] args) {
Vector<String> fruits = new Vector<>();
// Adding elements
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Mango");
fruits.add("Orange");
// Display elements
System.out.println("Fruits: " + fruits);
// Access element
System.out.println("First fruit: " + fruits.get(0));
// Update element
fruits.set(1, "Grapes");
// Remove element
fruits.remove(2);
// Check size and elements
System.out.println("Updated Fruits: " + fruits);
System.out.println("Total Fruits: " + fruits.size());
Output
Fruits: [Apple, Banana, Mango, Orange]
First fruit: Apple
Updated Fruits: [Apple, Grapes, Orange]
Total Fruits: 3
Classes in java
Classes in Java – The Building Blocks of OOP
A class in Java is a blueprint or template for creating objects. It defines the attributes (fields) and
behaviors (methods) that the created objects will have.
Basic Structure of a Class
class ClassName {
// Fields (Attributes or Properties)
dataType variableName;
// Constructor
ClassName() {
// initialization code
// Methods (Functions or Behaviors)
returnType methodName(parameters) {
// method body
Example: Simple Class in Java
class Car {
// Fields
String color;
int speed;
// Constructor
Car(String c, int s) {
color = c;
speed = s;
}
// Method
void displayInfo() {
System.out.println("Color: " + color);
System.out.println("Speed: " + speed + " km/h");
Using the Class in Main Method
public class Main {
public static void main(String[] args) {
Car myCar = new Car("Red", 120); // Creating object
myCar.displayInfo(); // Calling method
Output
Color: Red
Speed: 120 km/h
Inheritance in Java
Inheritance in Java is a fundamental Object-Oriented Programming (OOP) concept where one
class inherits the properties and behaviors (fields and methods) of another class.
It promotes code reusability, extensibility, and a hierarchical class structure.
Types of Inheritance in Java
Java supports the following types:
1. Single Inheritance ✅
2. Multilevel Inheritance ✅
3. Hierarchical Inheritance ✅
4. Multiple Inheritance ❌ (Not supported with classes, but possible with interfaces
1. Single Inheritance
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.sound(); // Inherited
d.bark(); // Own method
}
}
Output:
Animal makes sound
Dog barks
2. Multilevel Inheritance
class Animal {
void eat() {
System.out.println("Eating...");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking...");
}
}
class Puppy extends Dog {
void weep() {
System.out.println("Weeping...");
}
}
public class Main {
public static void main(String[] args) {
Puppy p = new Puppy();
p.eat(); // From Animal
p.bark(); // From Dog
p.weep(); // Own method
}
}
3. Hierarchical Inheritance
class Animal {
void sound() {
System.out.println("Animals make sound");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
class Cat extends Animal {
void meow() {
System.out.println("Cat meows");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
Cat c = new Cat();
d.sound();
d.bark();
c.sound();
c.meow();
}
}
Java Does Not Support Multiple Inheritance with Classes
interface A {
void show();
interface B {
void display ();
class C implements A, B {
public void show() {
System.out.println("Show from A");
public void display() {
System.out.println("Display from B");
super Keyword in Inheritance
1. Access Superclass Constructor
You can call the constructor of the superclass using:
super();
class Animal {
Animal() {
System.out.println("Animal constructor called");
}
}
class Dog extends Animal {
Dog() {
super(); // Calls Animal() constructor
System.out.println("Dog constructor called");
}
}
2. Access Superclass Method
you can call a method from the superclass that is overridden in the subclass.
super.methodName();
Example:
class Animal {
void sound() {
System.out.println("Animal makes sound");
}
}
class Dog extends Animal {
void sound() {
super.sound(); // Calls Animal's sound()
System.out.println("Dog barks");
}
}
3. Access Superclass Variable
If the subclass has a variable with the same name as the one in the superclass, you can access the
superclass variable using:
super.variableName;
Example:
class Animal {
String type = "Animal";
class Dog extends Animal {
String type = "Dog";
void display() {
System.out.println("Type: " + super.type); // prints Animal
System.out.println("Type: " + type); // prints Dog
Packages in Java
Definition:
A package in Java is a namespace that organizes a set of related classes and interfaces. Think of
it like a folder that groups Java files logically, helping to avoid name conflicts and making code
easier to maintain.
Types of Packages in Java
Built-in Packages
Provided by Java API. Examples:
java.lang – Contains core classes (e.g., String, Math, System)
java.util – Contains utility classes (e.g., ArrayList, HashMap, Date)
java.io – Input/Output operations (e.g., File, BufferedReader)
java.net – Networking classes
java.sql – Database connectivity
1. User-defined Packages
Created by programmers to group their own classes.
Creating a User-Defined Package
1. Create a class and declare a package at the top:
package mypackage;
public class MyClass {
public void display() {
System.out.println("Hello from MyClass in mypackage!");
}
}
2. Compile with folder structure:
javac -d . MyClass.java
This creates a folder mypackage with MyClass.class inside.
3. Use the package in another class:
import mypackage.MyClass;
public class Test {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Benefits of Using Packages
Avoid name conflicts (e.g., two classes named Employee)
Code reusability
Easier to maintain
Access control using public, protected, etc.
Common Java Packages (with purpose)
Package Name Description
java.lang Core language classes (automatically imported)
java.util Collections, date/time utilities
java.io File and stream handling
java.net Networking (sockets, URLs)
java.sql Database access
Package Name Description
javax.swing GUI components (buttons, frames)
Exception Handling in Java
Exception handling in Java is a mechanism to handle runtime errors (exceptions) so that the
normal flow of the program is not interrupted.
What is an Exception?
An exception is an event that disrupts the normal flow of a program during execution.
Example: Dividing a number by zero, accessing an invalid array index, etc.
Types of Exceptions
1. Checked Exceptions (Compile-time)
Must be handled using try-catch or declared with throws.
Examples: IOException, SQLException
2. Unchecked Exceptions (Runtime)
Occur at runtime; not checked at compile-time.
Examples: ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException
3. Errors
Serious issues that applications should not handle.
Examples: OutOfMemoryError, StackOverflowError
Java Exception Handling Keywords
Keyword Description
try Block of code to monitor for exceptions
catch Block of code to handle the exception
finally Block that always executes (optional)
throw Used to throw an exception
throws Declares exceptions a method may throw
Keyword Description
Example
public class Example {
public static void main(String[] args) {
try {
int a = 10 / 0; // This will cause ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
} finally {
System.out.println("Always executed");
}
}
}
Output:
Error: / by zero
Always executed
Multithreaded Programming
Multithreaded programming is a technique where multiple threads run concurrently within a
single Java program. Each thread runs independently, but shares the process memory, enabling
parallel task execution.
Why Use Multithreading?
Improves performance on multi-core systems
Increases responsiveness in interactive programs (e.g., UI)
Efficient resource utilization
Ideal for tasks like:
o Downloading files
o Playing music while working
o Animations
o Server handling multiple client requests
Basic Concepts
Term Description
Thread Smallest unit of execution within a process
Multithreading Executing multiple threads simultaneously
Main Thread The thread that runs the main() method
Concurrency Two or more tasks progress at overlapping times
Steps to Create a Thread
1. Extend Thread Class
class MyThread extends Thread {
public void run() {
System.out.println("Thread running");
}
}
public class Demo {
public static void main(String[] args) {
MyThread t = new MyThread();
t.start(); // Calls run() in a new thread
}
2. Implement Runnable Interface
class MyRunnable implements Runnable {
public void run() {
System.out.println("Runnable thread running");
public class Demo {
public static void main(String[] args) {
Thread t = new Thread(new MyRunnable());
t.start();
Thread Lifecycle
1. New – Thread is created
2. Runnable – Ready to run
3. Running – Currently executing
4. Blocked/Waiting – Paused, waiting for resource or signal
5. Terminated – Finished execution
Useful Thread Methods
Method Use
start() Starts a new thread
run() Contains the code to be run
sleep(ms) Pause for milliseconds
join() Wait for another thread to finish
isAlive() Check if thread is running
setPriority() Set execution priority
Thread Synchronization
To avoid data inconsistency when threads access shared resources:
synchronized void method() {
// thread-safe code
Example
class Count extends Thread {
public void run() {
for (int i = 1; i <= 3; i++) {
System.out.println(i);
public class Test {
public static void main(String[] args) {
Count t1 = new Count();
Count t2 = new Count();
t1.start();
t2.start();
Multithreading allows simultaneous execution.
Use Thread or Runnable to define threads.
Use synchronized to avoid conflicts.
Improves efficiency, responsiveness, and performance.