0% found this document useful (0 votes)
14 views15 pages

COS - 211 Practical Material

The document provides an overview of Java programming, focusing on basic data types, type conversion, variable declaration, and installation instructions for Java on Windows and MacOS. It includes examples of Java code for data types, operators, string processing, and mathematical operations. Additionally, it outlines how to run a simple Java program and the structure of a Java application.
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)
14 views15 pages

COS - 211 Practical Material

The document provides an overview of Java programming, focusing on basic data types, type conversion, variable declaration, and installation instructions for Java on Windows and MacOS. It includes examples of Java code for data types, operators, string processing, and mathematical operations. Additionally, it outlines how to run a simple Java program and the structure of a Java application.
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/ 15

COS 211 COMPUTER PROGRAMMING I

PRACTICALS IN JAVA PROGRAMMING


BASIC DATA TYPES
The Java’s Type System is categorized into two which are Primitives and Reference
Type system. StronglyTypedLanguage: Java enforces type checking at compile time.
Every variable must have a declared type, and operations between mismatched types
are not allowed without explicit conversion.
• PrimitiveTypes:
Represent simple values such as(e.g., numbers, characters, Booleans) and are stored
directly in memory. They include:
o Numeric Types: byte, short, int, long, float, double
o Character Type: char
o Boolean Type: boolean
• Reference Types:
Store references (or addresses) to objects. They include classes, arrays, and
interfaces. For example, a String is a reference type.

Detailed Look at Primitive Data Types


1. Numeric Types:
Integer Types:
byte:
• 8-bit signed integer.
• Range: -128 to 127.
short:
• 16-bit signed integer.
• Range: -32,768 to 32,767.
int:
• 32-bit signed integer; the most commonly used for whole numbers.
long:
• 64-bit signed integer; used for large integer values.
• Suffix literal with an L (e.g., 123456789L).
2. Floating-Point Types:
float:
• 32-bit floating point.
• Use the suffix f or F (e.g., 3.14f).
double:
• 64-bit floating point; offers greater precision and is used by default for decimal
numbers.
3. Character Type:

char:
• 16-bit Unicode character.
• Declared with single quotes (e.g., 'A').

4. Boolean Type:
boolean:
• Represents one of two values: true or false. This can also be represented by
• True or False
• On or Off
• Zero and One
Example of variable declarations for all the data types are listed below:
byte smallNumber = 100;
int wholeNumber = 5000;
long largeNumber = 1234567890123L; // Note the L at the end
float piApprox = 3.14f;
double precisePi = 3.141592653589793;
char letter = 'Z';
boolean isJavaFun = true;

Type Conversion

1. Implicit (Widening) Conversion:


Automatically converts a smaller type of number to a larger type. For example
int myInt = 100;
long myLong = myInt; // int is widened to long automatically

2. Explicit (Narrowing) Conversion:


Converting from a larger type to a smaller type requires a cast. This can lead to data loss:
double myDouble = 9.99;
int myInt = (int) myDouble; // myInt becomes 9; decimal portion i

3. Autoboxing/Unboxing:
Converting between primitives and their corresponding wrapper classes happens
automatically.
Integer wrappedInt = 10; // Autoboxing: int to Integer
int unwrappedInt = wrappedInt; // Unboxing: Integer to int

Variables
A variable is a named storage location in memory that holds a value. In Java, every
variable must have a declared type, which defines what kind of data the variable can hold.
Variables allow you to store, modify, and retrieve data during the execution of a program.

Declaration, Initialization, and Assignment

• Declaration: Tells the compiler the variable's name and type


int age;
double salary;
• Initialization: Assigns an initial value to the variable at the time of declaration.
int age = 25;
double salary = 50000.00;
• Assignment: assigning or reassigning a value to an already declared variable.
age = 30; // Updating the value of age
salary = 55000.50; // Changing the salary

2
How to install Java
Java can be installed across multiple platforms. The guide provided will below will take you
through the installation process on Windows and MacOS
Windows MacOS
Follow the steps below to install Java on Windows: Here's a detailed The installation process on Windows is
explanation of each of the steps. similar to MAC. In step 1 of the download
process as shown for windows. It is
Step 1: Download JDK important to note that, For Intel-based Macs:
Go to the official Oracle website to download the JDK. Download the macOS x64 DMG Installer
For Apple Silicon (M1) Macs:
1. Download JDK(Java Development Kit) Download the macOS ARM64 DMG Installer.
• https://www.oracle.com/ng/java/technologies/downloads
/#jdk24-windjows to set up environment variables to tell your
• download x64 MSI Installer system where to find Java.
2. Run the Installer
Search for the Terminal app and type the
3. Configure Environment Variables following command:
• After the installation, environment variable needs to be
configured to enable your system know where to find Java. nano ~/.bash_profile
• The JDK installation is typically found in C:\Program This will open the .bash_profile file in a text
Files\Java\jdk-22\bin editor.
• Afterwards search for environment variables and click on the first
configuration setting Now, add the following lines at the end of the
Update the Path Variable: file to set the JAVA_HOME and PATH
Find the Path variable in the System variables section and click on variable.
Edit. Then, click New and paste your JDK bin path (i.e. C:\Program
Files\Java\jdk-22\bin). export
Finally, click Ok to close each window. JAVA_HOME=$(/usr/libexec/java_home)
Set JAVA_HOME Variable: export PATH=$JAVA_HOME/bin:$PATH
Back in the environment variables window, under the system
variables section, click New to create a new variable. Press Ctrl + X to exit, then Y to save the
Now, name the variable JAVA_HOME and set its value to the path of changes, and Enter to confirm the filename.
the JDK folder directory (i.e.C:\Program Files\Java\jdk-22). Close and reopen the terminal for the
4. Verify Installation changes to take effect. Then, confirm the
After the installation, you can verify whether Java is installed by using version of your JDK with the code “java –
the following command in the command prompt. version” to ensure the JDK setup is
java –version recognised by the system.
5. Download and install VScode with other extension packs from
the link below Download and install “Java Extension Pack”
https://code.visualstudio.com/docs/java/java-tutorial. for MacOS as shown in step 5.
If you have VScode installed on your system go to the left pane
of your window and click on market place search for “Java Finally, Go to the next paragraph on how to
Extension Pack” and click install. Afterwards you can go ahead run your first Java Program
and run your first Java program.

Run your first Java code


• Open Visual Studio Code
• Click on file at the top left bar and select new file or click new file by the left pane of the
VS-code Development environment
• Name your file e.g Myfirtcode.java note that your file must be labelled with the “.java”
extention
• Select your destination folder or locaton and click save
Note: the class name in your code must be the same with the named file you created
Copy and paste the code below and click on run

3
class Myfirtcode {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
You should see Hello World printed to the console of your VS code editor
Basic Structure of a Java Program
class Main {
public static void main(String[] args) {

...

}
}
Java programming language requires lots of codes even for a small program that prints
hello world. The above code is enclosed by braces is the medium through which all
Java codes are run. Codes must be written and replaced with the ... within the enclosed
braces.
Lets a take a look at another example that prints out different data types representing
student details
Code Sample
public class StudentInfo {
public static void main(String[] args) {
// Declaring variables for student information
String name = "John Doe";
String matricNumber = "MAT202045";
String department = "Computer Science";
double cgpa = 3.85;
int level = 300;

// Printing out the student information


System.out.println("Student Information:");
System.out.println("Name: " + name);
System.out.println("Matriculation Number: " + matricNumber);
System.out.println("Department: " + department);
System.out.println("CGPA: " + cgpa);
System.out.println("Level: " + level);
}
}

Java Operators
Operators are typical mathematical symbols used to perform operations on variables
and values. The figure below further illustrates this definition.

4
Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from x-y


another

* Multiplication Multiplies two values x*y

/ Division Divides one value by x/y


another

% Modulus Returns the division x%y


remainder

++ Increment Increases the value of a ++x


variable by 1

-- Decrement Decreases the value of a --x


variable by 1

Assignment operators
Assignment operators are used to assign values to variables. This implies that any value
attributed to the declared variable serves a storage location which can be used as
access point to that value.
Example
int x = 15
and
int x = 10;
x += 5; // This assignment operator adds a value to the declared variable without an
output of 15
The list of assignment operators typically used in Java is provided and described in the
figure below.

Operator Example Same As Description

= x=5 x=5 Assigns 5 to x

+= x += 3 x=x+3 Adds 3 to x and assigns the result to x

-= x -= 3 x=x-3 Subtracts 3 from x and assigns the result to x

*= x *= 3 x=x*3 Multiplies x by 3 and assigns the result to x

/= x /= 3 x=x/3 Divides x by 3 and assigns the result to x (in


floating-point format)

5
%= x %= 3 x=x% Assigns the remainder of x divided by 3 to x

&= x &= 3 x=x&3 Performs a bitwise AND operation between x


and 3 and assigns the result to x

|= x |= 3 x=x|3 Performs a bitwise OR operation between x and


3 and assigns the result to x

^= x ^= 3 x=x^3 Performs a bitwise XOR operation between x


and 3 and assigns the result to x

>>= x >>= 3 x = x >> 3 Shifts the bits of x right by 3 positions and


assigns the result to x

<<= x <<= 3 x = x << 3 Shifts the bits of x left by 3 positions and assigns
the result to x

Java Logical Operators


Logical operators are used to perform logical operations on boolean values (True or
False). They help in decision-making by evaluating conditions. The figure below shows
the logical operators used in Java.

Operator Name Description Example

&& Logical Returns true if both statements x < 5 && x <


and are true 10

|| Logical Returns true if one of the x < 5 || x <


or statements is true 4

! Logical Reverse the result, returns false !(x < 5 && x


not if the result is true < 10)

String Processing in Java


String processing in Java involves manipulating and handling string data using built-in
methods from the String class. Below are some common string operations with
examples.

1. Finding String Length (length())

6
The length() method returns the number of characters in a string.

Code sample
public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";
System.out.println("Length: " + str.length()); // Output: 16
}
}

2. Concatenation (+ and concat())


Strings can be joined using the + operator or the concat() method.

Code sample
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = " World";

// Using + operator
String result1 = str1 + str2;
System.out.println("Concatenation using +: " + result1);

// Using concat() method


String result2 = str1.concat(str2);
System.out.println("Concatenation using concat(): " + result2);
}
}

3. Converting Case (toUpperCase() & toLowerCase())


These methods convert a string to uppercase or lowercase.

Code sample
public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";

System.out.println("Uppercase: " + str.toUpperCase());


System.out.println("Lowercase: " + str.toLowerCase());
}
}

4. Extracting Substring (substring())


The substring() method extracts a portion of a string.
Code sample
public class StringExample {
public static void main(String[] args) {
String str = "Hello World";

7
System.out.println("Substring: " + str.substring(6)); // Output: "World"
System.out.println("Substring: " + str.substring(0, 5)); // Output: "Hello"
}
}

5. Checking Presence (contains(), startsWith(), endsWith())


These methods check if a string contains or starts/ends with a specific substring.
Code sample
public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";

System.out.println("Contains 'Java': " + str.contains("Java")); // true


System.out.println("Starts with 'Java': " + str.startsWith("Java")); // true
System.out.println("Ends with 'ing': " + str.endsWith("ing")); // true
}
}

6. Replacing Characters (replace())


The replace() method replaces characters or substrings.

Code sample
public class StringExample {
public static void main(String[] args) {
String str = "I love Java";

System.out.println("Replace 'Java' with 'Python': " + str.replace("Java",


"Python"));
}
}

7. Splitting a String (split())


The split() method splits a string into an array based on a delimiter.

Code sample
public class StringExample {
public static void main(String[] args) {
String str = "Java,Python,C++";
String[] languages = str.split(",");

for (String lang : languages) {


System.out.println(lang);
}
}
}

8
8. Comparing Strings (equals() & equalsIgnoreCase())
These methods check if two strings are equal.
Code sample
public class StringExample {
public static void main(String[] args) {
String str1 = "Hello";
String str2 = "hello";

System.out.println("Equals: " + str1.equals(str2)); // false


System.out.println("Equals Ignore Case: " + str1.equalsIgnoreCase(str2)); //
true
}
}
Maths Operation in Java
Method Description Example Output
Math.abs(x) Returns the absolute (positive) Math.abs(-10) 10
value of x.
Math.max(x, y) Returns the larger of x and y. Math.max(8, 12) 12
Math.min(x, y) Returns the smaller of x and y. Math.min(8, 12) 8
Math.sqrt(x) Returns the square root of x. Math.sqrt(25) 5.0
Math.pow(x, y) Returns x raised to the power of Math.pow(2, 3) 8.0
y.
Math.round(x) Rounds x to the nearest integer. Math.round(4.7) 5
Math.floor(x) Rounds x down to the nearest Math.floor(4.7) 4.0
integer.
Math.ceil(x) Rounds x up to the nearest Math.ceil(4.2) 5.0
integer.
Math.random() Returns a random number Math.random() e.g.,
between 0.0 and 1.0. 0.6784
Math.sin(x) Returns the sine of an angle x (in Math.sin(Math.PI/2) 1.0
radians).
Math.cos(x) Returns the cosine of an angle x Math.cos(0) 1.0
(in radians).
Math.tan(x) Returns the tangent of an angle x Math.tan(Math.PI/4) 1.0
(in radians).
Math.log(x) Returns the natural logarithm Math.log(10) 2.3025
(base e) of x.
Math.exp(x) Returns e^x (Euler's number Math.exp(2) 7.3891
raised to x).

Code Sample
public class MathExample {
public static void main(String[] args) {
System.out.println("Absolute: " + Math.abs(-10)); // 10
System.out.println("Max: " + Math.max(8, 12)); // 12
System.out.println("Min: " + Math.min(8, 12)); // 8
System.out.println("Square Root: " + Math.sqrt(25)); // 5.0

9
System.out.println("Power: " + Math.pow(2, 3)); // 8.0
System.out.println("Rounded: " + Math.round(4.7)); // 5
System.out.println("Floor: " + Math.floor(4.7)); // 4.0
System.out.println("Ceiling: " + Math.ceil(4.2)); // 5.0
System.out.println("Random (0-1): " + Math.random()); // e.g., 0.6784
}
}
Java Control Structure
Control structures in Java define the flow of execution of a program. They allow the
program to make decisions, execute loops, and control how the program runs based on
conditions. Java has three main types of control structures

Sequential Control Structure


This is the default flow of execution where statements are executed one after another in
the order they appear.

Code sample
public class SequentialExample {
public static void main(String[] args) {
System.out.println("Step 1: Start program");
System.out.println("Step 2: Execute statement");
System.out.println("Step 3: End program");
}
}

This typically takes these three important stages which are


Step 1: Start Program
Step 2: Execute statement
Step 3: End Program

Selection (Decision-Making) Control Structure


Used for making decisions in a program based on conditions. The types of selection
structures in Java are

a) if statement:
Executes a block of code only if a specified condition is true. They syntax is provided below
if (condition) {
// block of code to be executed if the condition is true
}
Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an error.
Code Sample
public class IfExample {
public static void main(String[] args) {
int num = 10;
if (num > 5) {
System.out.println("Number is greater than 5");
}
}

10
}

b) if-else Statement:
Executes one block of code if the condition is true, otherwise executes another
block. The sysntax is provided below

if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}

Code Sample
public class IfElseExample {
public static void main(String[] args) {
int num = 3;
if (num > 5) {
System.out.println("Number is greater than 5");
} else {
System.out.println("Number is less than or equal to 5");
}
}
}

Code Sample
int doorCode = 1337;

if (doorCode == 1337) {
System.out.println("Correct code. The door is now open.");
} else {
System.out.println("Wrong code. The door remains closed.");
}

Code sample

int myAge = 25;


int votingAge = 18;

if (myAge >= votingAge) {


System.out.println("Old enough to vote!");
} else {
System.out.println("Not old enough to vote.");
}

c) if-else if-else Statement


Used when there are multiple conditions to check. The syntax format is provided below
if (condition1) {

11
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Code Sample

public class ElseIfExample {


public static void main(String[] args) {
int num = 10;
if (num > 10) {
System.out.println("Number is greater than 10");
} else if (num == 10) {
System.out.println("Number is exactly 10");
} else {
System.out.println("Number is less than 10");
}
}
}
d) Switch Statement
This is used when a variable has multiple possible values this is typically used
instead of multiple if else statements. The code syntax is provided below.

switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}

Code sample
public class SwitchExample {
public static void main(String[] args) {
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:

12
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
}
// Outputs "Thursday" (day 4)
}
}
}

When Java reaches a break keyword, it breaks out of the switch block. This will stop the
execution of more code and case testing inside the block. When a match is found, and
the job is done, it's time for a break. There is no need for more testing. A break can save
a lot of exe

Iteration (Looping) Control Structure


Used when a block of code needs to be executed repeatedly. The types of loops in Java
are:
a) for Loop
Executes a block of code a fixed number of times until a specific condition
is met. This specifically used when you know how many times you want to
loop through a block of code. This is shown in the syntax below

for (statement 1; statement 2; statement 3) {


// code block to be executed
}

Code Sample

public class ForLoopExample {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration: " + i);
}
}
}

13
b) while loop
This executes a block of code while a condition remains true. The code syntax is given
below
while (condition) {
// code block to be executed
}

Code Sample
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
c) do-while Loop

Similar to the while loop but ensures the code runs at least once. The code syntax is
provided below

do {
// code block to be executed
}
while (condition);

Code Sample

public class DoWhileExample {


public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration: " + i);
i++;
} while (i <= 5);
}
}
Code sample

int countdown = 3;

while (countdown > 0) {


System.out.println(countdown);
countdown--;
}

System.out.println("Happy New Year!!");

14
The example below uses a do/while loop. The loop will always be executed at least once,
even if the condition is false, because the code block is executed before the condition is
tested:

d) For- Each Loop


There is also a "for-each" loop, which is used exclusively to loop through elements in
an array (or other data sets). Refer to the syntax below.

for (type variableName : arrayName) {


// code block to be executed
}
Code Sample
String[] fruits = {"Mango", "Oranges", "Water Melon", "Apple"};
for (String i : fruits) {
System.out.println(i);
}

This outputs all elements in the fruits array using the foreach loop. Arrays will be discussed in
subsequent Sections

JAVA ARRAYS

15

You might also like