Practical Module SC025
Practical Module SC025
Practical Module SC025
Pulished by:
i
Contents
CONTENTS
Task 3: Calculate and display the average of three (3) marks entered by user. ..................................... 19
ii
Contents
iii
Contents
iv
Practical 1 : Introduction to Java™ Programming
Practical 1: Introduction
to Java™ Programming
(4 hours)
Learning Outcomes:
Page 1
Practical 1 : Introduction to Java™ Programming
class HelloWorld{
public static void main(String[] args){
System.out.print("Hello, world!");
}
}
Page 2
Practical 1 : Introduction to Java™ Programming
HelloWorld.java
class HelloWorld{
System.out.print("Hello, world!");
Hello, world!
Code Explanation
class HelloWorld{ A class is required to write a Java
program.
} class is a keyword for a Java
program.
HelloWorld is any valid
identifiers to represent name of
the class.
Open and close braces, { }
indicate the start and end of the
class.
A method main() is compulsory in
public static void main(String[] a Java class to:
args){ run the program, or
call a method.
}
Open and close braces, { } indicate
the start and end of the method.
System.out.print() is an
output statement to display
System.out.print("Hello,
output on the console.
world!");
"Hello, world!" is the message
to be displayed on the console.
Page 3
Practical 1 : Introduction to Java™ Programming
Exercise 1:
Using the same file HelloWorld.java
1. Add an output statement that display a second message after the "Hello,
world!". Type something like, "I Like Computer Science." Compile
and run the program again.
2. Add another output statement that display a third message such as, "I
Learn Java." Compile and run the program again.
3. Add a comment to the program stating the author name and the purpose
of the program, recompile, and run it again. The new comment should not
affect the result. (*Hint: Use // or /* */)
Exercise 2:
1. Create a new Java program. ([Ctrl]+[N])
2. Type the following code:
class AboutMe{
}
}
Exercise 3:
Write a complete Java program to display the following output:
Java
Java Again
Still Java
Always Java
Java Forever
Page 4
Practical 1 : Introduction to Java™ Programming
class DisplayMessages{
public static void main(String[] args){
}
}
So, how do we display the output messages in three (3) different lines?
Page 5
Practical 1 : Introduction to Java™ Programming
For example:
DisplayMessages1.java
class DisplayMessages1{
public static void main(String[] args){
}
}
OR
DisplayMessages2.java
class DisplayMessages2{
public static void main(String[] args){
}
}
Re-run the program, and the output displayed should be like this:
Page 6
Practical 1 : Introduction to Java™ Programming
class DisplayMessages3{
public static void main(String[] args){
}
}
As you can see, the use of escape sequence \n and \t will result to the desired
output.
Page 7
Practical 1 : Introduction to Java™ Programming
Task 4: Exercises
Write a complete Java program that will display the following output:
1. Output 1
2. Output 2
3. Output 3
4. Output 4
5. Output 5
6. Output 6
#
# # #
# # # # #
# # #
#
Page 8
Practical 2 : Data Types, Operators, and Expressions
class DisplayVariables{
public static void main(String[] args){
String name="Marilyn";
int age=18;
double weight=65.4;
boolean married=true;
char gender='F';
Page 9
Practical 2 : Data Types, Operators, and Expressions
Concept of Variables
Code Description
Name: Marilyn
Age: 18
Weight: 65.4
Married? true
Gender: F
Page 10
Practical 2 : Data Types, Operators, and Expressions
Import java.util.Scanner;
class DisplayEnteredVariables{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Page 11
Practical 2 : Data Types, Operators, and Expressions
import java.util.Scanner;
class ArithmeticMain{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Page 12
Practical 2 : Data Types, Operators, and Expressions
import java.util.Scanner;
class MarksApp{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
*Note:
The result from the evaluation of relational and logical expressions would be in
form of Boolean value only i.e: true or false .
Page 13
Practical 2 : Data Types, Operators, and Expressions
import java.util.Scanner;
class MarksGrade{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
char grade='Z';
Task 6: Exercise
1. Write a complete Java program that will read and display your nickame,
age, gender, weight, height.
2. Write a complete Java program that will calculate and display your BMI
based on your weight and height. Then give the status of your BMI.
Page 14
Practical 3 : Sequence Control Structure
Practical 3: Sequence
Control Structure (2
hours)
Learning Outcomes:
Type the following code, then save, compile, and run the code. Verify the output.
AddNumbers.java
class AddNumbers{
Explanation:
In this problem statement, the value for the variables num1, num2, and add is
declared and initialized by the system, i.e:
means, the variables num1, num2 and add are declared as integer data type (int)
and initialized with values 3, 9, and 0 respectively.
Page 15
Practical 3 : Sequence Control Structure
The expression
means, the result from the addition of the variables num1 and num2 is assigned to
the variable named add.
will display output, Total: , concatenate (+) with the value stored in the variable
add.
3 9 12
Computer Memory
Page 16
Practical 3 : Sequence Control Structure
Type the following code, then save, compile, and run the code. Verify the output.
SubtractNumbers.java
import java.util.Scanner;
class SubtractNumbers{
public static void main(String[] args){
Scanner sc=new Scanner(System.in);
int num1=0,num2=0,result=0;
result=num1-num2;
Explanation:
In this Java program (SubtractNumbers.java), the value for the variables (num1
and num2) is entered by user through the keyboard. Hence, we need to import the
class Scanner from package java.util using the statement
import java.util.Scanner;
Page 17
Practical 3 : Sequence Control Structure
num1=sc.nextInt();
will read next integer input from user and assign it to the variable num1. Assume
user enter 3.
num1
The statements
num2=sc.nextInt();
read the next integer input and assign it to the variable num2. Assume user enter
9.
num2
result=num1-num2;
Suppose the user entered 3 for first input, and 9 for second input, the variable
result will store the value from the subtraction between 3 and 9 i.e -6. So the
value -6 will be stored in the variable result.
-6
result
The statement
3 9 -6
num1 num2 result
Computer Memory
Page 18
Practical 3 : Sequence Control Structure
class StudentMark{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
total = mark1+mark2+mark3;
average = (mark1+mark2+mark3)/3;
*Note: Remember to name the Java file created, same as the class name.
Page 19
Practical 3 : Sequence Control Structure
Task 4: Exercise
Exercise 1:
i. Create a new program named Date.java. Copy or type in something like
the hello world program and make sure you can compile and run it.
ii. Write a program that creates variables named day, date, month, and
year. The variable day will contain the day of the week (like Friday), and
date will contain the day of the month (like the 13th). What type is each
variable? Assign values to those variables that represent today's date.
iii. Display (System.out.println) the value of each variable on a line by
itself. This is an intermediate step that is useful for checking that
everything is working so far. Compile and run your program before
moving on.
iv. Modify the program so that it displays the date in standard American
format, for example: Thursday, July 16, 2015.
v. Modify the program so it also displays the date in European format. The
final output should be:
American format:
Thursday, July 16, 2015
European format:
Thursday 16 July 2015
Exercise 2:
Write a program that converts a temperature from Celsius to Fahrenheit.
(Fahrenheit=Celcius x 9/5 + 32)
It should
(1) prompt the user for input,
(2) read a double value from the keyboard,
(3) calculate the result, and
(4) display the output.
Exercise 3:
Write a program that converts a total number of seconds to hours, minutes, and
seconds. It should
(1) prompt the user for input,
(2) read an integer from the keyboard,
(3) calculate the result, and
(4) display the output.
Page 20
Practical 3 : Sequence Control Structure
Exercise 4:
Find the area of a triangle (Given base=3, height=4).
Exercise 5:
Calculate and display the perimeter and area of a rectangle. (Given length=3.5,
width=7.9)
Exercise 6:
Calculate and display the circumference and area of a circle based on the radius
entered by user.
Exercise 7:
Calculate and display Body Mass Index (BMI) based on weight in kilograms and
height in meters entered by user.
Page 21
Practical 4 : Selection Control Structure
Practical 4: Selection
Control Structure (2
hours)
Learning Outcomes:
Pass.java
import java.util.Scanner;
class Pass{
int mark=0;
mark=sc.nextInt();
if(mark>=40)
System.out.print("PASS");
}
}
97
PASS
Page 22
Practical 4 : Selection Control Structure
Task 2: Exercise
Exercise 1:
If a student is in Modul 2 group, display the message “The student is taking
Computer Science subject”.
Exercise 2:
Print the message “You’re entitle to vote” for a person whose age is above 20.
Exercise 3:
Display a message “You are an excellent student” for a student whose
cumulative grade point average (CGPA) is 3.75 or above.
Exercise 4:
Determine whether the number keyed in by user is a positive number.
Exercise 5:
Determine whether a number entered by a user is an even number. (Hint: use
modulus operator %)
Page 23
Practical 4 : Selection Control Structure
PassFail.java
import java.util.Scanner;
class PassFail{
double mark=0;
mark=sc.nextDouble();
if(mark>=40)
System.out.print("PASS");
else
System.out.print("FAIL");
}
}
39.9
FAIL
Page 24
Practical 4 : Selection Control Structure
Task 4: Exercise
Exercise 1:
If a student is in Modul 2 and Modul 3 group, display the message “The student
is taking Computer Science subject”. Otherwise, display the message “The
student is taking Pure Science subject”.
Exercise 2:
Print the message “You’re entitle to vote” for a person whose age is above 20.
Otherwise print message “You’re not entitle to vote”.
Exercise 3:
Display a message “You are an excellent student” for a student whose
cumulative grade point average (CGPA) is 3.75 or above. Otherwise print “Try
again”.
Exercise 4:
Determine whether the number keyed in by user is a positive number or a
negative number.
Exercise 5:
Determine whether a number entered by a user is an even or odd number. (Hint:
use modulus operator %)
Page 25
Practical 4 : Selection Control Structure
Marks Grade
Greater than or equal to 80 A
Greater than or equal to 70 B
Greater than or equal to 50 C
Greater than or equal to 40 D
Less than 40 F
StudentGrade.java
import java.util.Scanner;
class StudentGrade{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double mark=0;
char grade;
if(mark>=80)
grade = 'A';
else if(mark>=70)
grade = 'B';
else if(mark>=50)
grade = 'C';
else if(mark>=40)
grade = 'D';
else
grade = 'F';
System.out.print("Grade: "+ grade);
}
}
Page 26
Practical 4 : Selection Control Structure
Task 6: Exercise
Exercise 1:
Determine whether the number keyed in by user is positive, negative or zero.
Exercise 2:
Create a program that will ask a user to enter age for two peoples. Display “The
first person is older” when age1 is greater than age2, else display “The second
person is older”. If both are not true, display “Both person are same age”.
Exercise 3:
Calculate and display Body Mass Index (BMI) based on weight in kilograms and
height in meters entered by user. Then display the appropriate message based on
the following table:
Exercise 4:
Calculate water bill based on water consumption as given below:
Exercise 5:
Calculate phone bill based on the following term:
Page 27
Practical 5 : Repetition Control Structure (Sentinel-controlled)
Practical 5: Repetition
Control Structure (2
hours)
Learning Outcomes:
DisplayMessage.java
class DisplayMessage{
public static void main(String[] args){
int counter=0;
while(counter<7){
System.out.println("I Love Computer Science");
counter=counter+1;
}
}
}
Page 28
Practical 5 : Repetition Control Structure (Sentinel-controlled)
DisplayCounter.java
class DisplayCounter{
int counter=1;
while(counter<=10){
System.out.print(counter);
counter=counter+1;
}
}
}
12345678910
Sum.java
import java.util.Scanner;
class Sum{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int counter=0, sum=0;
while(counter<10){
System.out.print("Enter a number: ");
sum = sum + sc.nextInt();
counter=counter+1;
}
System.out.print("Sum: "+ sum);
}
}
Enter a number: 13
Enter a number: 65
Enter a number: 78
Enter a number: 98
Enter a number: 34
Enter a number: 56
Enter a number: 73
Enter a number: 99
Enter a number: 100
Enter a number: 43
Sum: 659
Page 29
Practical 5 : Repetition Control Structure (Sentinel-controlled)
Sum.java
import java.util.Scanner;
class SumOddEven{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(counter<10){
System.out.print("Enter a number: ");
num = sc.nextDouble();
if(num%2==0)
even = even+num;
else
odd = odd+num;
counter=counter+1;
}
Page 30
Practical 5 : Repetition Control Structure (Sentinel-controlled)
SumOddEven.java
import java.util.Scanner;
class SumOddEven{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double num=0, even=0, odd=0;
for(int counter=0;counter<10;counter++){
System.out.print("Enter a number: ");
num = sc.nextDouble();
if(num%2==0)
even = even+num;
else
odd = odd+num;
}
System.out.print("\nSum of odd number: "+ odd);
System.out.print("\nSum of even number: "+ even);
}
}
Page 31
Practical 5 : Repetition Control Structure (Sentinel-controlled)
*Note: You will get the same output similar to a while statement, even though
you are using a for loop. Why?
This is because, the for loop does not change the logic of the program but the
difference is the syntax used in the program.
int counter = 0;
for(int counter = 0;counter<limit;
while(counter < limit){ counter++){
System.out.print(“Test”); System.out.print(“Test”);
counter = counter+1; }
*Note:
Page 32
Practical 5 : Repetition Control Structure (Sentinel-controlled)
Task 6: Exercise
Exercise 1:
Calculate and display the average of 10 numbers entered by user.
Exercise 2:
Print first 10 even numbers.
Exercise 3:
Print odd numbers from 3 to 39.
Exercise 4:
Print multiples of 5 which are less than 30.
Exercise 5:
Print the squares of first 10 integers.
Exercise 6:
Calculate and display the total for the first 20 integers.
Exercise 7:
Calculate and display the average for the first 20 integers.
Exercise 8:
Calculate the sum of all even numbers from 2 to 100.
Exercise 9:
Calculate the area of 10 rectangles.
Exercise 10:
Find the average marks for 10 tests that have been taken by a student.
Exercise 11:
Calculate and print the average of three tests for 30 students.
Page 33
Practical 5 : Repetition Control Structure (Sentinel-controlled)
Pseudocode
Start
Read mark
Set mark as highest
While mark not equal to sentinel value
Read mark
If mark > highest
Set mark as highest
Endwhile
Print highest
End
HighestMark.java
import java.util.Scanner;
class HighestMark{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double mark=0, highest;
while(mark != -1){
System.out.print("Enter mark: ");
mark = sc.nextDouble();
if(mark>highest)
highest = mark;
}
System.out.print("Highest: "+ highest);
}
}
Enter mark: 87.6
Enter mark: 43.2
Enter mark: 90.2
Enter mark: 54.6
Enter mark: 98
Enter mark: 34.7
Enter mark: 23.5
Enter mark: -1
Highest: 98.0
Page 34
Practical 5 : Repetition Control Structure (Sentinel-controlled)
Task 8: Exercise
Exercise 1:
Write a Java program that will accept marks from user and calculate the total
marks. The process will continue until the user enters -1.
Exercise 2:
Design an algorithm to calculate the total temperature for a list of daily
temperatures that will be entered by user. The calculation will stop when the
value of temperature is -999.
Exercise 3:
A program will calculate the average for a few integers entered by user. The user
should key in 0 to terminate the sequence.
Exercise 4:
Write a pseudocode to find factorial of number entered by user using while
statement.
Exercise 5:
A program will print first ten multiplication value based on number entered by
user.
Page 35
Practical 6 : Arrays
Practical 6: Arrays (6
hours)
Learning Outcomes:
import java.util.Scanner;
class ArrayMain{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] name = new String[7];//declare array of String
int[] age = new int[7]; //declare array of integer
Page 36
Practical 6 : Arrays
Explanation:
Code Explanation
Page 37
Practical 6 : Arrays
import java.util.Scanner;
class ArrayMain{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
String[] name = {"Sulaiman", "Daud", "Musa", "Yusof",
"Muhammad"};
int[] age = {180, 70, 123, 110, 63};
Explanation:
Code Explanation
Page 38
Practical 6 : Arrays
Then display all the elements in the array and sum of the elements in the array.
PrintArray.java
class PrintArray{
public static void main(String[] args){
double[] marks =
{97.5,75.3,53.1,86.4,64.2,13.5,35.7,57.9,24.6,46.8};
double sum=0;
for(int i=0;i<marks.length;i++){
System.out.print(marks[i] +"\t");
sum=sum+marks[i];
}
System.out.print("\nSum: "+ sum);
}
}
97.5 75.3 53.1 86.4 64.2 13.5 35.7 57.9 24.6 46.8
Sum: 555.0
It sequentially checks each element of the list for the target value until a match is
found or until all the elements have been searched.
class LinearSearch{
public static void main(String[] args){
int search=30, array[]={10,20,30,40,50,60,70};
30 is present at index 2
Page 39
Practical 6 : Arrays
PrintArray2.java
import java.util.Scanner;
class PrintArray2{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double[] marks = new double[10];
double sum=0, avg=0;
for(int i=0;i<marks.length;i++){
System.out.print("Enter mark: ");
marks[i] = sc.nextDouble();
}
for(int i=0;i<marks.length;i++){
System.out.print(marks[i] +"\t");
sum = sum + marks[i];
}
avg = sum / marks.length;
System.out.print("\nAverage: "+ avg);
}
}
Page 40
Practical 6 : Arrays
Task 6: Maximum
Write a complete Java program which initialized a group of marks in an array as
follows:
97.5 75.3 53.1 86.4 64.8 42.0 100.0 57.9 46.8 90.0
PrintHighest.java
class PrintHighest{
public static void main(String[] args){
double[] marks =
{97.5,75.3,53.1,86.4,64.8,42.0,100.0,57.9,46.8,90.0};
for(int i=1;i<marks.length;i++){
if(marks[i]>highest)
highest = marks[i];
}
System.out.print("Highest: "+ highest);
}
}
Highest: 100.0
Page 41
Practical 6 : Arrays
Task 7: Frequency
Create a complete Java program which determine the number of odd and even
numbers based on ten (10) numbers entered by user.
import java.util.Scanner;
class FreqArray{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
int[] arr = new int[10];
int even=0, odd=0;
for(int i=0;i<arr.length;i++){
arr[i] = sc.nextInt();
if(arr[i]%2==0)
even = even + 1;
else
odd = odd + 1;
}
System.out.println("No. of even: "+ even);
System.out.print("No. of odd: "+ odd);
}
}
Page 42
Practical 6 : Arrays
Task 8: Exercise
1. Write a program to read 10 students’ marks into an array called
marks, and print the best student marks.
2. Write a program to read 10 students’ names and marks into two
respective arrays called names and marks, and print the best
student name and marks.
3. Write a Java program which finds the minimum element in the
array.
4. Write a program which finds both the maximum and minimum
elements in the array, at the same time.
5. Write a program which asks the user for a value to look for in the
array and searches for the value in the array. The code should print
"Found!" to System out if the value exists, or "Not found" otherwise.
6. Write a program that takes a double array, a, and returns a new
array that contains the elements of a squared.
7. Write a program that takes an array of integers and returns the
index of the largest element.
8. Write a program that takes an integer parameter, n, and returns a
boolean array that indicates, for each number from 0 to n - 1,
whether the number is a prime number.
9. Write a program that takes an integer n and an array of integers,
and that returns true if the numbers in the array are all factors of n
(which is to say that n is divisible by all of them).
10. Write a program that takes an array of integers and two indexes,
lowIndex and highIndex, and finds the maximum value in the
array, but only considering the elements between lowIndex and
highIndex, including both.
Page 43
Practical 7 : Methods
Practical 7: Non-static
Methods (8 hours)
Learning Outcomes:
Method Definitions
Page 44
Practical 7 : Methods
Calling a Method
Before a method is called, we must create the object in order to call the specific
method. Object created using the statement,
where, ClassName is the name of the class, and obj can be any valid identifiers
to represent instance of the class.
Four (4) types of method calls based on method definitions with examples:
For calling Type 3 and Type 4 method, usually these types of methods either:
1. Assign to a variable then display the result using the output statement, or
2. Directly use output statement to display the output.
Page 45
Practical 7 : Methods
For example:
import java.util.Scanner;
class Arithmetic{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Arithmetic obj = new Arithmetic();
obj.showWelcome();
obj.sayHi(name);
int result = obj.calcAdd(num1, num2);
System.out.print("Addition: "+ result);
}
void showWelcome(){
System.out.println("Welcome to Java");
}
Page 46
Practical 7 : Methods
MethodCall1.java
class MethodCall1{
public static void main(String[] args){
MethodCall1 mc = new MethodCall1();
mc.printMethod();
void printMethod(){
System.out.print("I Love Computer Science");
}
}
Page 47
Practical 7 : Methods
Message 1: I Love Computer Science will be printed from the main() method.
Message 2: I Like Programming will be printed from calling methodName1().
Message 3: I Learn Java will be printed from calling methodName2().
MethodCall2.java
class MethodCall2{
public static void main(String[] args){
MethodCall2 mc = new MethodCall2();
void methodName1(){
System.out.println("I Like Programming");
}
void methodName2(){
System.out.println("I Learn Java");
}
}
Page 48
Practical 7 : Methods
Hello, <yourname>
MethodCall3.java
class MethodCall3{
public static void main(String[] args){
MethodCall3 mc = new MethodCall3();
mc.printName(name);
}
Hello, Amran
Page 49
Practical 7 : Methods
Hello, <yourname>
Your age now is <age> years old
MethodCall4.java
import java.util.Scanner;
class MethodCall4{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
MethodCall4 mc = new MethodCall4();
Page 50
Practical 7 : Methods
SquareMain.java
class SquareMain {
int result;
result = sm.square();
int square() {
return 10 * 10;
Page 51
Practical 7 : Methods
SquareMain.java
class SquareMain {
public static void main(String[] args) {
SquareMain sm = new SquareMain();
int result, n;
n = 3;
result = sm.square(n);
System.out.println("Square of 3 is: " + result);
n = 4;
result = sm.square(n);
System.out.println("Square of 4 is: " + result);
}
int square(int i) {
return i * i;
}
}
Square of 3 is: 9
Square of 4 is: 16
Page 52
Practical 7 : Methods
ArithmeticMain.java
class ArithmeticMain{
public static void main(String[] args) {
ArithmeticMain am = new ArithmeticMain();
10 + 20 = 30
20 x 40 = 800
Page 53
Practical 7 : Methods
SquareMain.java
class SquareMain {
public static void main(String[] args) {
SquareMain sm = new SquareMain();
int result=0;
Square of 1 is : 1
Square of 2 is : 4
Square of 3 is : 9
Square of 4 is : 16
Square of 5 is : 25
Page 54
Practical 7 : Methods
Page 55