Cos201 (Java)
Cos201 (Java)
Java is a high-level, general-purpose programming language that was designed by James Gosling
at Sun Microsystems and first released in 1995. It is object-oriented and intended to let developers
“write once, run anywhere” (WORA) – Java code is compiled into platform-independent
bytecode that runs on any device with a Java Virtual Machine (JVM). Java quickly gained
popularity and is now owned by Oracle Corporation (after it acquired Sun in 2010). It remains
widely used, with more than 3 billion devices running Java.
Java was developed by James Gosling and his team at Sun Microsystems in the early 1990s.
Originally designed for interactive television, the language was initially called Oak, but it was later
renamed Java in 1995 due to trademark issues.
2. Java Enterprise Edition (Java EE), now known as Jakarta EE, extends Java SE by adding
tools and libraries for building large-scale, distributed, and web-based enterprise
applications. It supports technologies like Servlets, JavaServer Pages (JSP), Enterprise
JavaBeans (EJB), and web services. This edition is widely used for developing enterprise-
level server-side applications and is popular in banking, e-commerce, and other large
organizations.
3. Java Micro Edition (Java ME) is a stripped-down version of Java designed for resource-
constrained devices like feature phones, smart cards, embedded systems, and Internet of
Things (IoT) devices. It includes a subset of Java SE libraries and provides a lightweight
runtime environment optimized for mobile and embedded applications.
4. JavaFX is a platform for building rich desktop applications with advanced user interfaces,
media playback, and graphics. Though not an official standalone edition like the others,
JavaFX is often used alongside Java SE to develop modern, visually appealing desktop
applications with support for 2D/3D graphics and animation.
A Simple Java Program: Once Java is installed, you can write your first program. All Java code
is defined inside classes.
For example, here is a simple “Hello World” program to demonstrate the structure of a Java
application:
public class HelloWorld {
public static void main(String[] args) {
[Link]("Hello, Java!");
}
}
In this code:
• public class HelloWorld declares a class named HelloWorld. The file name should match
the class name (e.g., [Link]).
• Inside the class, the main method is defined as public static void main(String[] args). This
method is the entry point of any Java application – when you run the program, the code
inside main executes.
• [Link](...) prints text to the console. Here it will print Hello, Java!.
To compile this program, you would use javac [Link] which produces a
[Link] (bytecode). Then run it with java HelloWorld, which invokes the JVM to execute
the main method.
• + (Addition)
• - (Subtraction)
• * (Multiplication)
• / (Division)
• % (Modulus)
Example:
int a = 10;
int b = 5;
[Link]("Addition: " + (a + b)); // Output: 15
[Link]("Subtraction: " + (a - b)); // Output: 5
[Link]("Multiplication: " + (a * b));// Output: 50
[Link]("Division: " + (a / b)); // Output: 2
[Link]("Modulus: " + (a % b)); // Output: 0
• = (Simple assignment)
Example:
int a = 10;
a += 5; // Equivalent to a = a + 5
[Link](a); // Output: 15
a -= 5; // Equivalent to a = a – 5
[Link](a); // Output: 5
• == (Equal to)
Example:
int a = 10;
int b = 5;
[Link](a == b); // Output: false
[Link](a > b); // Output: true
[Link](a < b); // Output: false
• + (Unary plus)
• - (Unary minus)
• ++ (Increment)
• -- (Decrement)
Example:
int a = 10;
[Link](++a); // Output: 11
[Link](--a); // Output: 10
• || (Logical OR)
• ! (Logical NOT)
Example:
boolean x = true;
boolean y = false;
[Link](x && y); // Output: false
[Link](x || y); // Output: true
[Link](!x); // Output: false
Module 3: Control statements in Java Programming Language
Control statement in Java programming are the building blocks of any program that dictate the
flow of execution. They enable us to control how, when, and under what conditions different parts
of the program are executed. By utilizing control statements, we can make decisions, repeat actions,
or execute specific parts of the code based on certain conditions.
Decision making statement: if statements (and optional else/else if clauses) to execute code
based on conditions.
1. If Statement: The if statement evaluates a boolean expression and executes a block of code
only if the expression evaluates to true. It's used to make decisions in the program flow.
if (number > 0) {
[Link]("The number is positive.");
}
}
}
2. If-else Statement: The if-else statement in Java is a fundamental control flow mechanism that
allows a program to execute certain code blocks based on whether a given condition is true or
false. It helps create decision-making paths in your programs, meaning your code can react
differently depending on inputs or program states.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
import [Link];
public class VoterEligibility {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link]("Enter your age: ");
int age = [Link]();
// Use if-else to determine eligibility
if (age >= 18) {
[Link]("You are eligible to vote.");
} else {
[Link]("You are not eligible to vote.");
}
[Link]();
}
3. The if-else if-else Ladder: The if-else if-else ladder in Java is a powerful control structure that
allows you to test multiple conditions sequentially. It evaluates conditions one by one and executes
the code block corresponding to the first true condition, skipping the rest. This structure is
particularly useful when you have several mutually exclusive conditions to handle.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
} else if (condition2) {
// Code to execute if condition2 is true
} else {
// Code to execute if none of the above conditions are true
}
import [Link];
public class GradeAssigner {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt user for input
[Link]("Enter the student's score (0 - 100): ");
int score = [Link]();
String grade;
// Validate input and assign grade
if (score >= 70 && score <= 100) {
grade = "A";
} else if (score >= 60 && score <= 69) {
grade = "B";
} else if (score >= 50 && score <= 59) {
grade = "C";
} else if (score >= 45 && score <= 49) {
grade = "D";
} else if (score >= 40 && score <= 44) {
grade = "E";
} else if (score >= 0 && score <= 39) {
grade = "F";
} else {
grade = "Invalid score. Please enter a number between 0 and
100.";
}
// Display result
[Link]("Grade: " + grade);
[Link]();
}
Example 2: Write a Java program to develop a basic calculator that performs addition, subtraction,
multiplication, and division based on user input:
import [Link];
public class BasicCalculator {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Get first number from user
[Link]("Enter the first number: ");
double num1 = [Link]();
// Get operator from user
[Link]("Enter an operator (+, -, *, /): ");
char operator = [Link]().charAt(0);
// Get second number from user
[Link]("Enter the second number: ");
double num2 = [Link]();
double result;
// Perform calculation based on the operator
if (operator == '+') {
result = num1 + num2;
[Link]("Result: " + result);
} else if (operator == '-') {
result = num1 - num2;
[Link]("Result: " + result);
} else if (operator == '*') {
result = num1 * num2;
[Link]("Result: " + result);
} else if (operator == '/') {
if (num2 != 0) {
result = num1 / num2;
[Link]("Result: " + result);
} else {
[Link]("Error: Division by zero is not
allowed.");
}
} else {
[Link]("Invalid operator. Please use +, -, *, or
/.");
}
[Link]();
}
}
Example 3: Write a java program that determines the days of the week based on user input
import [Link];
public class DayOfWeek {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Ask the user to enter a number between 1 and 7
[Link]("Enter a number (1 to 7) to get the
corresponding day of the week: ");
int dayNumber = [Link]();
String day;
// Determine the day based on user input
if (dayNumber == 1) {
day = "Monday";
} else if (dayNumber == 2) {
day = "Tuesday";
} else if (dayNumber == 3) {
day = "Wednesday";
} else if (dayNumber == 4) {
day = "Thursday";
} else if (dayNumber == 5) {
day = "Friday";
} else if (dayNumber == 6) {
day = "Saturday";
} else if (dayNumber == 7) {
day = "Sunday";
} else {
day = "Invalid input. Please enter a number between 1 and
7.";
}
// Print result
[Link]("Day: " + day);
[Link]();
}
}
4. Switch Statement: The switch statement in Java is a control statement used to simplify
complex decision-making when multiple conditions are based on the same variable or
expression. It serves as a cleaner alternative to long if-else-if chains, especially when checking a
single variable against many constant values.
Syntax:
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// default code block
}
• The expression must evaluate to a byte, short, int, char, String, or enum (since Java 7, String
is supported).
• The case labels must be constant values.
• The break statement terminates the switch block; without it, fall-through occurs, meaning
execution continues to the next case even if it doesn't match.
• The default case is optional and acts as a fallback if no case matches.
Example 1: Using switch statement, write a Java program to determine the days of the week based
on user input
int day = 3;
switch (day) {
case 1:
[Link]("Monday");
break;
case 2:
[Link]("Tuesday");
break;
case 3:
[Link]("Wednesday");
break;
case 4:
[Link]("Thursday");
break;
case 5:
[Link]("Friday");
break;
case 6:
[Link]("Saturday");
break;
case 7:
[Link]("Sunday");
break;
default:
[Link]("Invalid day number");
}
Example 2: Using switch statement, write a java programming to generate remarks based on letter
grades
Loops in Java Programming Language: In Java programming, loops are essential constructs that
allow a set of statements to execute repeatedly based on a condition. This process of repetition is
called iteration, and Java provides three primary types of loops: the for loop, the while loop, and
the do-while loop. Each of these loops is used in different scenarios, depending on the nature and
predictability of the condition that governs repetition.
The while loop is an entry-controlled loop. It checks the condition before executing the loop
body. If the condition is false from the beginning, the loop body will not execute even once.
Syntax
while (condition) {
// code block to be executed repeatedly
}
Flowchart Explanation:
int i = 1;
while (i <= 5) {
[Link](i);
i++;
}
int sum = 0;
int i = 1;
while (i <= 100) {
sum += i;
i++;
}
[Link]("Sum is: " + sum);
The do-while loop is an exit-controlled loop. The loop body executes at least once, regardless
of the condition. After the first execution, the condition is checked.
Syntax:
do {
// loop body
} while (condition);
Flowchart Explanation:
import [Link];
do {
[Link]("Enter password: ");
password = [Link]();
} while ();
[Link]("Access Granted");
3. For Loop
The for loop is the most commonly used loop when the number of iterations is known ahead of
time. It is especially suitable for situations where a variable needs to be initialized, a condition
needs to be checked before every iteration, and a counter or iterator needs to be updated after
each pass.
Syntax:
Here, the initialization occurs once at the beginning of the loop. The condition is evaluated before
every iteration, and if it is true, the body of the loop is executed. After executing the body, the
update expression runs. Then the condition is evaluated again, and the cycle repeats until the
condition becomes false.
Example:
This loop prints the numbers from 1 to 5. The variable i starts at 1 and increases by 1 on each
iteration until it exceeds 5.
Example 1: Write a java program to print the sum of First N Natural Numbers
Explanation: This program calculates the sum of the first 10 natural numbers using a for loop. The
loop starts at 1 and adds each number to sum until it reaches 10.
int num = 7;
for (int i = 1; i <= 10; i++) {
[Link](num + " x " + i + " = " + (num * i));
}
int n = 5;
int factorial = 1;
Condition checked Before each iteration Before each iteration After each iteration
Introduction to Methods
A method in Java is a block of code that performs a specific task. It is also known as a function
in other programming languages. Methods help break a program into smaller, manageable parts,
encourage reusability, and enhance readability.
Java methods are defined inside classes and can be called (invoked) to execute when needed.
• returnType: The type of value the method returns (e.g., int, String, void).
• methodName: The name of the method (should follow Java naming conventions).
• parameters: Inputs passed to the method (optional).
• method body: The code that runs when the method is called.
void display() {
[Link]("This method returns nothing.");
}
double square(double x) {
return x * x;
}
Method Overloading
Java allows multiple methods with the same name as long as they have different parameter
lists (number, type, or order of parameters). This is called method overloading.
Example: Overloaded methods
Recursion in Java
What is Recursion?
Recursion is the process where a method calls itself to solve a problem. A recursive method
solves a small part of a problem and relies on itself to solve the remaining part.
int factorial(int n) {
if (n == 0 || n == 1) {
return 1; // Base case
} else {
return n * factorial(n - 1); // Recursive case
}
}
Advantages of Recursion
• Simplifies problems that have recursive nature (like tree traversal, backtracking, etc.).
• Reduces code length for complex algorithms.
Disadvantages of Recursion
What is an Array?
An array in Java is a container object that holds a fixed number of elements of the same data
type. The elements are stored in contiguous memory locations and accessed using indexing,
starting from index 0.
// Or combined:
int[] numbers = new int[5];
Assigning Values:
numbers[0] = 10;
numbers[1] = 20;
...
Types of Arrays
1. One-Dimensional Arrays
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
1. Linear Search: This is the simplest searching technique used in arrays. It works by checking each
element of the array one after the other until it finds the element being searched for or reaches the
end of the array. If the element is found, its index is returned or printed; otherwise, a message
indicates that the element is not present. This method is ideal for unsorted arrays.
2. Bubble Sort (Ascending Order): This is a basic sorting technique used to arrange elements in
ascending or descending order. It repeatedly compares adjacent elements and swaps them if they
are in the wrong order. This process is repeated for each pass through the array until the entire
array is sorted. Although simple, bubble sort is not efficient for large datasets.
4. Merging Two Arrays: This combines two different arrays into a single one. This is done by
creating a new array large enough to hold all the elements from both arrays and then copying the
elements from the first and second arrays in sequence. Merging is used in data integration or
sorting procedures.
5. Removing Duplicate Elements from an array involves checking whether an element has already
occurred earlier in the array. If it has, it is skipped; otherwise, it is printed or stored. This approach
helps in filtering unique values from data.
Sum and Average: Sum and Average calculation in an array is used when the total or the mean of
all values is needed. The sum is obtained by adding all elements in a loop, and the average is then
calculated by dividing the sum by the number of elements in the array. This is commonly used in
applications like report cards or statistics.