IBRAHEEM I.O.
CMP 202: Computer Programming II – Java Programming
This course builds upon the foundational knowledge acquired in Computer Programming I. It
looks deeper into the Java programming language, emphasizing key concepts like structured
programming, debugging, testing.
Computer programming is the process of writing instructions that tell a computer what to do.
These instructions are written in a specific language, which the computer then interprets and
executes.
Why learn computer programming?
Problem-solving skills: Programming helps you develop logical thinking and problem-solving
abilities.
Automation: You can automate repetitive tasks and make your work more efficient.
Career opportunities: Programming is a valuable skill in many fields, from software
development to data science.
Creativity: You can create new and innovative solutions to problems.
Principles of Good Programming
Readability: Code should be easy to understand, with meaningful variable and function names,
consistent indentation, and clear comments.
public class ReadableCode {
public static void main(String[] args) {
1|Pa ge
IBRAHEEM I.O.
int age = 20;
String name = "John";
if (age >= 18) {
[Link](name + " is an adult.");
} else {
[Link](name + " is not an adult.");
}
}
}
Efficiency: Code should execute quickly and use minimal system resources.
Maintainability: Code should be easily modifiable and adaptable to changing requirements.
Modularity: Code should be organized into reusable components (functions, classes) for better
structure and flexibility.
Robustness: Code should handle errors gracefully and prevent unexpected behavior.
Security: Code should protect against vulnerabilities like input validation, data encryption, and
access control.
Structured Programming
Top-down design: Breaking down a problem into smaller, manageable subproblems.
Modularization: Encapsulating code into functions or methods for reusability.
Control flow: Using conditional statements (if-else) and loops (for, while) to control program
execution.
Data structures: Organizing data efficiently using arrays, linked lists, stacks, and queues.
2|Pa ge
IBRAHEEM I.O.
Debugging and Testing
Debugging: The process of finding and fixing errors in code.
Types of errors: Syntax errors, runtime errors, and logical errors.
Debugging tools: Debuggers, print statements, and unit tests.
Testing: Verifying that code produces correct results and behaves as expected.
Unit testing: Testing individual code units (functions, methods).
Integration testing: Testing how different code components interact.
System testing: Testing the entire system to ensure it meets requirements. \
Comments
Comments are non-executable statements in the code that are used to explain the code or
make notes for the programmer. They are ignored by the compiler. Comments are essential for
making code more understandable.
Types of Java Comments
There are three main types of comments in Java:
• Single-line comments (using //)
• multi-line comments (using /* */).
• Documentation Comment (/** */)
Single-line comments are typically used for brief explanations.
3|Pa ge
IBRAHEEM I.O.
public class CommentExample1 {
public static void main(String[] args) {
int i=10; //Here, i is a variable
[Link](i);
}}
Multi-line comments are used for longer descriptions or documentation. Comments do not
affect the execution of the program but are crucial for helping developers (including the original
author) understand the purpose and function of the code.
public class CommentExample2 {
public static void main(String[] args) {
/* Let's declare and
print variable in java. */
int i=10;
[Link](i);
}
}
Documentation Comment is used to create documentation API.
/** The Calculator class provides methods to get addition and subtraction of given 2
numbers.*/
public class Calculator {
/** The add() method returns addition of given numbers.*/
public static int add(int a, int b){return a+b;}
/** The sub() method returns subtraction of given numbers.*/
public static int sub(int a, int b){return a-b;
}}
Methods
A method is a block of code that performs a specific task and can be called upon to execute.
Methods allow code to be reused and organized into logical sections.
In Java, methods are used to define the behaviors or functionalities that an object can perform.
For example, a calculateSum method might take two numbers as input and return their sum.
4|Pa ge
IBRAHEEM I.O.
Methods help to modularize code, making it easier to read, debug, and maintain. They can also
accept parameters and return values.
public class Calculator {
public int calculateSum (int num1, int num2) {
int sum = num1 + num2;
return sum;
}
public static void main (String [] args) {
Calculator calculator = new Calculator ();
int result = [Link](5, 10);
[Link]("The sum is: " + result);
}
}
Variable
A variable in Java is a container or storage location in memory that holds a value. Each variable
has a data type, which determines the type of values it can store (e.g., int, String, boolean).
Variables can be thought of as labels for the data, allowing the program to manipulate and
access the stored values.
Variables in Java must be declared before they can be used, which involves specifying the
variable's type and name. Variables can be reassigned new values throughout the program
unless they are declared as final, in which case they are constants and cannot be changed after
initialization.
public class VariableExample {
public static void main(String[] args) {
int age = 25; // Integer variable
String name = "Alice"; // String variable
double height = 5.7; // Double variable
[Link]("Name: " + name);
[Link]("Age: " + age);
[Link]("Height: " + height + " feet");
5|Pa ge
IBRAHEEM I.O.
}
}
Data Types
In Java, data types specify the size and type of values that can be stored in variables. They are
broadly categorized into two types: Primitive Data Types and Non-Primitive Data Types.
Primitive Data Types
Primitive data types are the most basic data types built into the Java language. There are eight
primitive data types in Java:
Data Type Size (bytes) Value Example
Byte 1 0 byte smallNumber =
100;
Short 2 0 short
mediumNumber =
10000;
Int 4 0 int number = 100000;
Long 8 0L long largeNumber =
100000L;
6|Pa ge
IBRAHEEM I.O.
Float 4 0.0f float decimalNumber
= 5.75f;
Double 8 0.0d double
largeDecimalNumber
= 19.99;
Char 2 ‘a000’ char letter = 'A';
Bolean ~ 1bit True or False boolean isJavaFun =
true;
A byte is an 8-bit signed integer. It is used to save space in large arrays by storing small numbers.
public class ByteExample {
public static void main(String[] args) {
byte smallNumber = 100;
[Link]("Byte value: " + smallNumber);
}
}
A short is a 16-bit signed integer. It is used to save memory in large arrays where the memory
savings actually matter.
public class ShortExample {
public static void main(String[] args) {
short mediumNumber = 10000;
[Link]("Short value: " + mediumNumber);
}
}
An int is a 32-bit signed integer. It is the most commonly used integer data type in Java.
public class IntExample {
public static void main(String[] args) {
int number = 50000;
[Link]("Int value: " + number);
}
}
A long is a 64-bit signed integer. It is used when a wider range than int is needed.
public class LongExample {
public static void main(String[] args) {
long largeNumber = 100000L;
[Link]("Long value: " + largeNumber);
}
7|Pa ge
IBRAHEEM I.O.
A float is a single-precision 32-bit floating-point data type. It is used to save memory in large
arrays of floating-point numbers.
public class FloatExample {
public static void main(String[] args) {
float decimalNumber = 5.75f;
[Link]("Float value: " + decimalNumber);
}
}
A double is a double-precision 64-bit floating-point data type. It is generally used as the default
data type for decimal values.
public class DoubleExample {
public static void main(String[] args) {
double largeDecimalNumber = 19.99;
[Link]("Double value: " + largeDecimalNumber);
}
}
A char is a single 16-bit Unicode character. It is used to store any character like a letter, digit, or
special symbol.
public class CharExample {
public static void main(String[] args) {
char letter = 'A';
[Link]("Char value: " + letter);
}
}
A boolean represents one bit of information and can have only two possible values: true or
false. It is used for simple flags that track true/false conditions.
public class BooleanExample {
public static void main(String[] args) {
boolean isJavaFun = true;
[Link]("Boolean value: " + isJavaFun);
}
}
8|Pa ge
IBRAHEEM I.O.
Non-Primitive Data Types
Non-primitive data types are more complex and include strings, classes, arrays, and interfaces.
Unlike primitive types, non-primitive types can be used to call methods to perform certain
operations.
String
A string in Java is a sequence of characters. Strings are used to store and manipulate text. In
Java, strings are objects of the String class, which is a part of the [Link] package. Strings are
immutable, meaning once a string is created, it cannot be changed. However, you can create
new strings based on the original string.
public class StringExample {
public static void main(String[] args) {
// Creating a string
String greeting = "Hello, World!";
// Displaying the string
[Link](greeting); // Output: Hello, World!
// Getting the length of the string
int length = [Link]();
[Link]("Length: " + length); // Output: 13
// Converting the string to uppercase
String upperCaseGreeting = [Link]();
[Link]("Uppercase: " + upperCaseGreeting); // Output: HELLO, WORLD!
// Concatenating two strings
String welcomeMessage = greeting + " Welcome to Java!";
[Link](welcomeMessage); // Output: Hello, World! Welcome to Java!
// Extracting a substring
String substring = [Link](7, 12);
[Link]("Substring: " + substring); // Output: World
9|Pa ge
IBRAHEEM I.O.
}
}
Class
A class is a blueprint for creating objects (instances). It defines the attributes (fields) and
behaviors (methods) that the objects created from the class will have. A class in Java is like a
template that describes the properties and actions that an object of that class can have. For
instance, a Car class might have attributes like color, model, and year, and methods like start,
drive, and stop. When you create an object from a class, you’re essentially creating a specific
instance that adheres to the structure defined by the class.
class Car {
String model;
int year;
}
Array
An array is a collection of elements, all the same type, stored in a contiguous block of memory.
Each element can be accessed using its index.
Arrays in Java are used to store multiple values of the same type in a single variable. For
example, you might use an array to store a list of integers or a list of strings. Arrays have a fixed
size, which means the number of elements they can hold is determined when the array is
created. They are useful for handling large amounts of data that need to be stored and accessed
in an organized manner.
int[] numbers = {1, 2, 3, 4, 5};
public class NumberCheck {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
10 | P a g e
IBRAHEEM I.O.
if (numbers[0] > 3) {
[Link]("First element is greater than 3");
} else {
[Link]("First element is not greater than 3");
}
}
}
Conditional Statements
Conditional statements are programming constructs that allow the code to make decisions and
execute certain blocks of code based on specified conditions.
In Java, conditional statements like if, else if, else, and switch are used to control the flow of a
program based on conditions. For example, an if statement will execute a block of code only if
a specified condition is true. Conditional statements are essential for making decisions within
a program, such as executing different actions based on user input or other runtime conditions.
They make the code dynamic and responsive to different scenarios.
If Statement
The if statement in Java is a conditional control structure that allows the program to execute a
block of code only if a specified condition is true. It is the most basic form of decision-making,
enabling the program to choose between executing one block of code or skipping it based on
whether the condition is met. The condition inside the if statement is usually a Boolean
expression that evaluates to either true or false.
public class IfExample {
public static void main(String[] args) {
int number = 5;
11 | P a g e
IBRAHEEM I.O.
// Checking if the number is positive
if (number > 0) {
[Link]("Positive number");
}
}
}
If-Else Statement
The if-else statement in Java is used to perform conditional operations. It allows the program
to execute a block of code if a specified condition is true. If the condition is false, an alternative
block of code in the else part is executed. The if-else statement is fundamental for controlling
the flow of a program based on conditions.
int number = 10;
if (number > 0) {
[Link]("The number is positive.");
} else {
[Link]("The number is non-positive.");
}
Else If (else-if) Statement
The else if statement in Java is used when multiple conditions need to be checked in sequence.
If the first if condition is false, the program checks the next else if condition, and so on. This
allows more than two possible execution paths.
int score = 85;
if (score >= 90) {
[Link]("Grade: A");
} else if (score >= 80) {
[Link]("Grade: B");
} else if (score >= 70) {
[Link]("Grade: C");
12 | P a g e
IBRAHEEM I.O.
} else {
[Link]("Grade: F");
}
Switch Statement
The switch statement in Java is a control structure that allows the program to execute one out
of several blocks of code based on the value of a variable or expression. The switch statement
evaluates the expression and matches its value against a series of case labels. If a match is
found, the corresponding block of code is executed. If no match is found, and an optional
default case is provided, the code in the default case is executed. The switch statement is useful
when you need to compare a variable to multiple potential values, making it a cleaner
alternative to multiple if-else statements.
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
// Switch statement to determine the day of the week
switch (day) {
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");
break;
case 3:
[Link]("Tuesday");
break;
default:
[Link]("Invalid day");
}
}
}
13 | P a g e
IBRAHEEM I.O.
Abstract Class
An abstract class is a class that cannot be instantiated on its own and is meant to be subclassed.
It can contain abstract methods (without implementation) as well as concrete methods (with
implementation).
Abstract classes in Java are used when you want to define a common structure and behavior
for a group of related classes but also allow individual subclasses to implement or override
certain methods. For example, you might have an abstract Animal class with an abstract
method makeSound, and subclasses like Dog and Cat would provide their own implementation
of makeSound. Abstract classes are useful when you want to enforce a certain hierarchy or
shared functionality among different classes.
abstract class Animal {
// Abstract method (no implementation)
abstract void sound();
}
class Dog extends Animal {
// Implementing the abstract method in Dog class
void sound() {
[Link]("Woof");
}
}
public class Main {
public static void main(String[] args) {
Animal dog = new Dog(); // Abstract class reference, Dog object
[Link](); // Calls Dog's implementation of sound
}
}
Polymorphism
14 | P a g e
IBRAHEEM I.O.
Polymorphism is the ability of an object to take on multiple forms. It allows one interface to be
used for a general class of actions, with the specific action determined by the exact nature of
the situation.
In Java, polymorphism allows methods to perform different tasks based on the object that
invokes them. This can be achieved through method overloading (same method name with
different parameters) or method overriding (subclass provides a specific implementation of a
method already defined in the superclass). Polymorphism enhances flexibility and
maintainability in code by allowing different objects to be treated as instances of the same
class.
class Shape {
// Method to simulate drawing a shape
void draw() {
[Link]("Drawing a shape");
}
}
class Circle extends Shape {
// Overriding the draw method for Circle
void draw() {
[Link]("Drawing a circle");
}
}
public class Main {
public static void main(String[] args) {
Shape shape = new Circle(); // Polymorphism: Shape reference, Circle object
[Link](); // Calls Circle's draw method
}
}
15 | P a g e
IBRAHEEM I.O.
Inheritance
Inheritance is a feature of object-oriented programming that allows a new class to inherit the
properties and behaviors of an existing class.
Inheritance promotes code reusability. In Java, a class that inherits from another class is called
a subclass (or derived class), and the class from which it inherits is called a superclass (or base
class). The subclass inherits all the fields and methods of the superclass but can also have
additional fields and methods or override existing ones. For example, if you have a Vehicle class,
you could create a Car class that inherits from Vehicle and adds specific features like
airConditioning or stereoSystem.
class Animal {
// Method to simulate eating behavior
void eat() {
[Link]("Eating...");
}
}
class Dog extends Animal {
// Method specific to Dog class
void bark() {
[Link]("Barking...");
}
}
public class Main {
public static void main(String[] args) {
Dog dog = new Dog(); // Creating an object of Dog class
[Link](); // Calling inherited method
[Link](); // Calling Dog class method
}
}
Operators in Java
Operators in Java are special symbols that perform operations on variables and values. They
are classified into several categories based on their functionality.
Arithmetic Operators
These operators are used to perform basic arithmetic operations.
16 | P a g e
IBRAHEEM I.O.
Addition (+): Adds two values.
int sum = 10 + 5; // sum = 15
Subtraction (-): Subtracts one value from another.
int difference = 10 - 5; // difference = 5
Multiplication (*): Multiplies two values.
int product = 10 * 5; // product = 50
Division (/): Divides one value by another.
int quotient = 10 / 5; // quotient = 2
Modulus (%): Returns the remainder of a division.
int remainder = 10 % 3; // remainder = 1
Example of a program with all arithmetic operation
public class ArithmeticOperations {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Addition
int sum = a + b;
[Link]("Sum: " + sum); // Output: 15
// Subtraction
int difference = a - b;
[Link]("Difference: " + difference); // Output: 5
// Multiplication
int product = a * b;
[Link]("Product: " + product); // Output: 50
// Division
int quotient = a / b;
[Link]("Quotient: " + quotient); // Output: 2
// Modulus
17 | P a g e
IBRAHEEM I.O.
int remainder = a % b;
[Link]("Remainder: " + remainder); // Output: 0
}
}
Assignment Operators
These operators are used to assign values to variables.
Simple Assignment (=): Assigns the right-hand value to the left-hand variable.
int number = 10; // number = 10
Addition Assignment (+=): Adds the right-hand value to the left-hand variable and assigns the
result.
int x = 5;
x += 3; // x = x + 3; x = 8
Subtraction Assignment (-=): Subtracts the right-hand value from the left-hand variable and
assigns the result.
int x = 5;
x -= 3; // x = x - 3; x = 2
Multiplication Assignment (*=): Multiplies the left-hand variable by the right-hand value and
assigns the result.
int x = 5;
x *= 3; // x = x * 3; x = 15
Division Assignment (/=): Divides the left-hand variable by the right-hand value and assigns
the result.
int x = 9;
18 | P a g e
IBRAHEEM I.O.
x /= 3; // x = x / 3; x = 3
Example of a program with all assignment operation
public class AssignmentOperations {
public static void main(String[] args) {
int x = 10;
// Simple Assignment
[Link]("Initial value: " + x); // Output: 10
// Addition Assignment
x += 5;
[Link]("After x += 5: " + x); // Output: 15
// Subtraction Assignment
x -= 3;
[Link]("After x -= 3: " + x); // Output: 12
// Multiplication Assignment
x *= 2;
[Link]("After x *= 2: " + x); // Output: 24
// Division Assignment
x /= 4;
[Link]("After x /= 4: " + x); // Output: 6
// Modulus Assignment
x %= 5;
[Link]("After x %= 5: " + x); // Output: 1
}
}
19 | P a g e