COS - 211 Practical Material
COS - 211 Practical Material
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
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.
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.
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;
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
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.
5
%= x %= 3 x=x% Assigns the remainder of x divided by 3 to x
<<= x <<= 3 x = x << 3 Shifts the bits of x left by 3 positions and assigns
the result to x
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
}
}
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);
Code sample
public class StringExample {
public static void main(String[] args) {
String str = "Java Programming";
7
System.out.println("Substring: " + str.substring(6)); // Output: "World"
System.out.println("Substring: " + str.substring(0, 5)); // Output: "Hello"
}
}
Code sample
public class StringExample {
public static void main(String[] args) {
String str = "I love Java";
Code sample
public class StringExample {
public static void main(String[] args) {
String str = "Java,Python,C++";
String[] languages = str.split(",");
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";
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
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");
}
}
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
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
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
Code Sample
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
int countdown = 3;
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:
This outputs all elements in the fruits array using the foreach loop. Arrays will be discussed in
subsequent Sections
JAVA ARRAYS
15