You are on page 1of 60

Copyright©

Java Practical Module

Author : Mohd Amran bin Md Ali

Fonts : Book Antiqua & Consolas

First Published… … October 2018

© All rights reserved. No part of this publication may be reproduced, stored in a


retrieval system, or transmitted, in any form or by any means, electronic,
mechanical, photocopying, recording, or otherwise without the prior written
permission of the publisher.

ISBN 978 – 967 – 16416 – –

Pulished by:

Mohd Amran bin Md Ali

i
Contents

CONTENTS

PRACTICAL 1: INTRODUCTION TO JAVA™ PROGRAMMING (4 HOURS) .....................1

Task 1: Using Java editor (jGRASP) ........................................................................................................... 1

Task 2: Use Output Statement to Display Messages ................................................................................ 5

Task 3: Displaying Formatted Output Using Escape Sequence \n and \t ........................................... 7

Task 4: Exercises ....................................................................................................................................... 8

PRACTICAL 2: DATA TYPES, OPERATORS, AND EXPRESSIONS (4 HOURS) ............... 9

Task 1: Displaying Values of Variables ...................................................................................................... 9

Task 2: Displaying Values of Variables Entered by User ......................................................................... 11

Task 3: Arithmetic Calculations .............................................................................................................. 12

Task 4: Using Relational Operators......................................................................................................... 13

Task 5: Using Relational and Logical Operators ...................................................................................... 14

Task 6: Exercise ....................................................................................................................................... 14

PRACTICAL 3: SEQUENCE CONTROL STRUCTURE (2 HOURS)....................................15

Task 1: Adding two numbers .................................................................................................................. 15

Task 2: Difference between two numbers ............................................................................................. 17

Task 3: Calculate and display the average of three (3) marks entered by user. ..................................... 19

Task 4: Exercise ....................................................................................................................................... 20

PRACTICAL 4: SELECTION CONTROL STRUCTURE (2 HOURS) .................................. 22

Task 1: Single Selection using if statement ........................................................................................ 22

Task 2: Exercise ....................................................................................................................................... 23

Task 3: Dual Selection using if/else statement ............................................................................... 24

Task 4: Exercise ....................................................................................................................................... 25

Task 5: Multiple Selection using if else if statement .................................................................. 26

Task 6: Exercise ....................................................................................................................................... 27

ii
Contents

PRACTICAL 5: REPETITION CONTROL STRUCTURE (2 HOURS)................................. 28

Task 1: Repetition using while statement.......................................................................................... 28

Task 2: Repetition using while statement.......................................................................................... 29

Task 3: Repetition using while statement.......................................................................................... 29

Task 4: Repetition using while statement.......................................................................................... 30

Task 5: Repetition using for statement .............................................................................................. 31

Task 6: Exercise ....................................................................................................................................... 33

Task 7: Repetition using sentinel-controlled .......................................................................................... 34

Task 8: Exercise ....................................................................................................................................... 35

PRACTICAL 6: ARRAYS (6 HOURS) .............................................................................. 36

Task 1: Declare and Enter Data into Arrays ............................................................................................ 36

Task 2: Accessing Elements in an Array .................................................................................................. 38

Task 3: Displaying Elements in an Array ................................................................................................. 39

Task 4: Linear Search .............................................................................................................................. 39

Task 5: Find Average ............................................................................................................................... 40

Task 6: Maximum ................................................................................................................................... 41

Task 7: Frequency ................................................................................................................................... 42

Task 8: Exercise ....................................................................................................................................... 43

PRACTICAL 7: NON-STATIC METHODS (8 HOURS) ....................................................44

Task 1: Understanding the Concept of Methods .................................................................................... 44

Task 2: A Method Accepting No Arguments and Returning No Value ................................................... 47

Task 3: A Method Accepting No Arguments and Returning No Value ................................................... 48

Task 4: A Method with Arguments and Returning No Value .................................................................. 49

Task 5: A Method with Arguments and Returning No Value .................................................................. 50

Task 6: A Method without Arguments and Returning Value .................................................................. 51

Task 7: A Method Accepting Arguments and Returning Value .............................................................. 52

iii
Contents

Task 8: A Method Accepting Arguments and Returning Value .............................................................. 53

Task 9: A Method Accepting Arguments and Returning Value .............................................................. 54

Task 10: Exercise ....................................................................................................................................... 55

iv
Practical 1 : Introduction to Java™ Programming

Practical 1: Introduction
to Java™ Programming
(4 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Create a new Java program,
ii. Type Java code,
iii. Save the Java file,
iv. Use output statements,
v. Construct Java™ program,
vi. Compile Java code, and
vii. Execute the Java program.

Task 1: Using Java editor (jGRASP)


STEP INSTRUCTIONS REMARKS
1 Create a new Java program.
Press keyboard key [Ctrl]+[N]
simultaneously.
2 Choose [Java], and
Click [OK].

Page 1
Practical 1 : Introduction to Java™ Programming

3 Type the following code:

class HelloWorld{
public static void main(String[] args){
System.out.print("Hello, world!");
}
}

4 Save the file.


Press keyboard key [Ctrl]+[S]
simultaneously.

5 At the [Look in:], choose your own


folder

6 In [File Name:], type the filename


exactly the same as class name.
For example: HelloWorld.java

Click the button [Save].


7 Compile the program. ----jGRASP exec: javac -g
Press keyboard key [Ctrl]+[B] HelloWorld.java
simultaneously.
----jGRASP: operation
complete.
8 Run the program. ----jGRASP exec: java
Press key [Ctrl]+[R] HelloWorld
simultaneously. Hello, world!
----jGRASP: operation
complete.
9 Verify the output.

Page 2
Practical 1 : Introduction to Java™ Programming

A Complete Java Program & Output

HelloWorld.java

class HelloWorld{

public static void main(String[] args){

System.out.print("Hello, world!");

Hello, world!

Java Source Code Explanation:

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{

public static void main(String[] args){

System.out.print("My name is Mohd.");


System.out.print("I am 18 years old.");
System.out.print("I study at Matriculation.");

}
}

3. Save the file as AboutMe.java. ([Ctrl]+[S])


4. Compile the program. ([Ctrl]+[B])
5. Run the program. ([Ctrl]+[R])
6. Verify the output.

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

Task 2: Use Output Statement to Display Messages


1. Create a new Java program ([Ctrl]+[N]).
2. Type the following code:

class DisplayMessages{
public static void main(String[] args){

System.out.print("I Like Computer Science.");


System.out.print("I Love Programming.");
System.out.print("I Learn Java.");

}
}

3. Save the file as DisplayMessages.java in your preferred folder. ([Ctrl]+[S])


4. Compile and run the program. ([Ctrl]+[B])  ([Ctrl]+[R])
5. Verify the output.

I Like Computer Science.I Love Programming.I Learn Java.

In your opinion, why is the messages displayed in one consecutive line?

This is because, the output statement System.out.print will display the


output in one line.

So, how do we display the output messages in three (3) different lines?

There are two (2) options to do that:

Option 1. By replacing System.out.print with System.out.println, or


Option 2. Put the escape sequence \n that represent a new line, before
starting any new message.

Page 5
Practical 1 : Introduction to Java™ Programming

For example:

DisplayMessages1.java

class DisplayMessages1{
public static void main(String[] args){

System.out.println("I Like Computer Science.");


System.out.println("I Love Programming.");
System.out.println("I Learn Java.");

}
}

OR

DisplayMessages2.java

class DisplayMessages2{
public static void main(String[] args){

System.out.print("\nI Like Computer Science.");


System.out.print("\nI Love Programming.");
System.out.print("\nI Learn Java.");

}
}

Re-run the program, and the output displayed should be like this:

I Like Computer Science.


I Love Programming.
I Learn Java.

*Note: Both files DisplayMessages1.java and DisplayMessages2.java


produced the same output.

Page 6
Practical 1 : Introduction to Java™ Programming

Task 3: Displaying Formatted Output Using Escape Sequence


\n and \t
Suppose we want the output messages displayed as follows:

I Like Computer Science.


I Love Programming.
I Learn Java.

How do we do? Use the output statement, System.out.print().

1. Create a new Java program.


2. Type the following code:

class DisplayMessages3{
public static void main(String[] args){

System.out.print("\nI Like Computer Science.");


System.out.print("\n\tI Love Programming.");
System.out.print("\n\t\tI Learn Java.");

}
}

3. Save the file as DisplayMessages3.java


4. Compile and run the program.
5. Verify the output.

I Like Computer Science.


I Love Programming.
I Learn Java.

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

Kolej Matrikulasi Kedah


Kementerian Pendidikan Malaysia
06010 Changloon, Kedah

2. Output 2

Kolej Matrikulasi Kedah


Kementerian Pendidikan Malaysia
06010 Changloon, Kedah

3. Output 3

My name is <your nickname>.


I am <age> years old.
I target <cgpa> for my final result.
Today date is <day> of <month>, <year>.

4. Output 4

0 2 4 6 8 is even numbers less than 10.


11 13 15 17 19 is odd numbers between 10 and 20.

5. Output 5

1 2 3 4 5 is positive integers less than 6.


-1 -2 -3 -4 -5 is negative integers greater than -
6.

6. Output 6

#
# # #
# # # # #
# # #
#

Page 8
Practical 2 : Data Types, Operators, and Expressions

Practical 2: Data Types,


Operators, and
Expressions (4 hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Use primitive data types in a program,
ii. Use arithmetic operators,
iii. Use relational operators,
iv. Use logical operators, and
v. Construct simple programs using primitive data types, operators and
expressions.

Task 1: Displaying Values of Variables


Create a complete Java program that will display the contents of variables such
as name, age, weight, marital status, and gender. Save, compile, and run the
program. Verify the output.

class DisplayVariables{
public static void main(String[] args){
String name="Marilyn";
int age=18;
double weight=65.4;
boolean married=true;
char gender='F';

System.out.println("Name: "+ name);


System.out.println("Age: "+ age);
System.out.println("Weight: "+ weight);
System.out.println("Married? "+ married);
System.out.println("Gender: "+ gender);
}
}
Name: Marilyn
Age: 18
Weight: 65.4
Married? true
Gender: F

Page 9
Practical 2 : Data Types, Operators, and Expressions

Concept of Variables

Code Description

A variable named name is declared as data type


String name="Marilyn";
String and store the value “Marilyn”.

A variable named age is declared as data type


int age=18;
integer, int and store the value 18.

A variable named weight is declared as data


double weight=65.4;
type double and store the value 65.4.

A variable named married is declared as data


boolean married=true;
type boolean and store the value true.

A variable named gender is declared as data


char gender='F';
type character, char and store the value ‘F’.

Variable’s value “Marilyn” 18 65.4 true ‘F’

Variable’s name name age weight married gender

The output statements

System.out.println("Name: "+ name);


System.out.println("Age: "+ age);
System.out.println("Weight: "+ weight);
System.out.println("Married? "+ married);
System.out.println("Gender: "+ gender);

will display the values stored in the variables on the console.

Name: Marilyn
Age: 18
Weight: 65.4
Married? true
Gender: F

Page 10
Practical 2 : Data Types, Operators, and Expressions

Task 2: Displaying Values of Variables Entered by User


Create a complete Java program (DisplayEnteredVariables.java) that will enable
user to enter name, age, height, marital status, and favorite character, then
display the values of the variables. Save, compile, and run the program. Verify
the output.

Import java.util.Scanner;
class DisplayEnteredVariables{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

System.out.print("Enter name: ");


String name=sc.next();
System.out.print("Enter age: ");
int age=sc.nextInt();
System.out.print("Enter height: ");
double height=sc.nextDouble();
System.out.print("Enter marital status: ");
boolean married=sc.nextBoolean();
System.out.print("Enter favorite letter: ");
char letter=sc.next().charAt(0);

System.out.println("Name: "+ name);


System.out.println("Age: "+ age);
System.out.println("Height: "+ height);
System.out.println("Married? "+ married);
System.out.println("Fav. Letter: "+ letter);
}
}
Enter name: Monroe
Enter age: 63
Enter height: 1.86
Enter marital status: false
Enter favorite letter: A
Name: Monroe
Age: 18
Height: 1.86
Married? false
Fav. Letter: A

Complete the following concept:

Variable’s value 18 false ‘A’

Variable’s name name P Q R S

Page 11
Practical 2 : Data Types, Operators, and Expressions

Task 3: Arithmetic Calculations


Create a complete Java program (ArithmeticMain.java) that will calculate and
display all the arithmetic result from two integers entered by user.

import java.util.Scanner;

class ArithmeticMain{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

System.out.print("Enter two numbers: ");


int num1=sc.nextInt();
int num2=sc.nextInt();

int add = num1 + num2;


int sub = num1 - num2;
int mul = num1 * num2;
int div = num1 / num2;
int mod = num1 % num2;

System.out.println("Addition: "+ add);


System.out.println("Subtraction: "+ sub);
System.out.println("Multiplication: "+ mul);
System.out.println("Division: "+ div);
System.out.println("Modulus: "+ mod);
}
}

Enter two numbers: 9 3


Addition: 12
Subtraction: 6
Multiplication: 27
Division: 3
Modulus: 0

Page 12
Practical 2 : Data Types, Operators, and Expressions

Task 4: Using Relational Operators


Create a complete Java program (MarksApp.java) that will calculate and display
the average of three marks entered by user, then determine the status “PASS” or
“FAIL”. (Passing marks is 40)

import java.util.Scanner;

class MarksApp{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

System.out.print("Enter three marks: ");


double mark1=sc.nextDouble();
double mark2=sc.nextDouble();
double mark3=sc.nextDouble();

double avg = (mark1+mark2+mark3)/3;


System.out.println("Average is "+ avg);

if(avg > 40)


System.out.println("\nPASS");
else
System.out.println("\nFAIL");
}
}

Enter three marks: 97.5 75.3 46.8


Average is 73.2
PASS

*Note:

Relational and logical operators are mainly used as expressions in:

 selection control structures using if() statement, and


 repetition control structures using while() or for() statements.

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

Task 5: Using Relational and Logical Operators


Create a complete Java program (MarksGrade.java) that will determine the grade
for the marks entered by user based on the following table:

Marks Range Grade


80 – 100 A
60 – 79.9 B
50 – 59.9 C
40 – 49.9 D
0 – 39.9 F

import java.util.Scanner;
class MarksGrade{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
char grade='Z';

System.out.print("Enter a mark (0 - 100): ");


double mark=sc.nextDouble();

if(mark>=80 && mark<=100)


grade = 'A';
else if(mark>=60 && mark<80)
grade = 'B';
else if(mark>=50 && mark<60)
grade = 'C';
else if(mark>=40 && mark<50)
grade = 'D';
else if(mark>=0 && mark<40)
grade = 'F';
else
System.out.println("Mark not in range.");

System.out.println("Grade: "+ grade);


}
}
Enter a mark (0 - 100): 97.5
Grade: A

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:

At the end of this lesson, students should be able to:


i. Construct program using sequence control structures.

Task 1: Adding two numbers


Problem Statement
Adding two numbers which values are initialized by the system.

Type the following code, then save, compile, and run the code. Verify the output.

AddNumbers.java
class AddNumbers{

public static void main(String[] args){

int num1=3, num2=9, add=0;

add = num1 + num2;

System.out.print("Total: "+ add);


}
}
Total: 12

Explanation:
In this problem statement, the value for the variables num1, num2, and add is
declared and initialized by the system, i.e:

int num1=3, num2=9, add=0;

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

add = num1 + num2;

means, the result from the addition of the variables num1 and num2 is assigned to
the variable named add.

The output statement

System.out.print("Total: "+ add);

will display output, Total: , concatenate (+) with the value stored in the variable
add.

3 9 12

num1 num2 add

Computer Memory

Page 16
Practical 3 : Sequence Control Structure

Task 2: Difference between two numbers


Problem Statement
Create a complete Java program name SubtractNumbers.java that will accept two
numbers from user and find the difference between numbers entered.

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;

System.out.print("Enter first number: ");


num1=sc.nextInt();

System.out.print("Enter second number: ");


num2=sc.nextInt();

result=num1-num2;

System.out.print("Difference: "+ result);


}
}
Enter first number: 3
Enter second number: 9
Difference: -6

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;

Then, the object sc will be created using class Scanner,

Scanner sc=new Scanner(System.in);

Next, the statement

System.out.print("Enter first number: ");

is a user-friendly feature that will prompt user to Enter first number:

Page 17
Practical 3 : Sequence Control Structure

Next, the statement

num1=sc.nextInt();

will read next integer input from user and assign it to the variable num1. Assume
user enter 3.

num1

The statements

System.out.print("Enter second number: ");

num2=sc.nextInt();

will prompt user to Enter second number: , and

read the next integer input and assign it to the variable num2. Assume user enter
9.

num2

Next, the statement

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

System.out.print("Difference: "+ result);

will display the output as Difference: -6.

3 9 -6
num1 num2 result

Computer Memory

Page 18
Practical 3 : Sequence Control Structure

Task 3: Calculate and display the average of three (3) marks


entered by user.
Problem Statement
Create a complete Java program (StudentMark.java) that will calculate and
display the total and average of three (3) marks entered by user.
StudentMark.java
import java.util.Scanner;

class StudentMark{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

int mark1=0, mark2=0, mark3=0;


double total=0, average=0;

System.out.print("Enter mark 1: ");


mark1 = sc.nextInt();
System.out.print("Enter mark 2: ");
mark2 = sc.nextInt();
System.out.print("Enter mark 3: ");
mark3 = sc.nextInt();

total = mark1+mark2+mark3;
average = (mark1+mark2+mark3)/3;

System.out.println("Total marks:"+ total);


System.out.println("Average marks:"+ average);
}
}
Enter mark 1: 90
Enter mark 2: 89
Enter mark 3: 79
Average marks:258.0
Average marks:86.0

*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

For example, "5000 seconds = 1 hours, 23 minutes, and 20 seconds".


(Hint: Use the modulus operator.)

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:

At the end of this lesson, students should be able to:


i. Construct program using selection control structures.

Task 1: Single Selection using if statement


Write a complete Java program that will determine the “PASS” status of a
student based on mark keyed in by user. (Passing mark is 40)

Pass.java

import java.util.Scanner;

class Pass{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

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

Task 3: Dual Selection using if/else statement


Write a complete Java program that will determine the “PASS” or “FAIL” status
of a student based on mark entered by user. (Passing mark is 40)

PassFail.java

import java.util.Scanner;

class PassFail{

public static void main(String[] args){

Scanner sc = new Scanner(System.in);

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

Task 5: Multiple Selection using if else if statement


Write a complete Java program that will print the grade of a student based on
mark entered by user. The student’s grade determined according to the following
table:

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;

System.out.print("Enter mark: ");


mark=sc.nextDouble();

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);
}
}

Enter mark: 97.5


Grade: A

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:

Weight Categories BMI (kg/m2)


Underweight < 18.5
Healthyweight 18.5 – 24.9
Overweight 25 – 29.9
Obese 30 – 34.9
Severely Obese 35 – 39.9
Morbidly Obese >= 40

Exercise 4:
Calculate water bill based on water consumption as given below:

Usage less than 20 m3 - charge is 43 sen per m3

Usage between 20 m3 to 40 m3 - charge is 21 sen per m3

More than 40 m3 - charge is 13 sen per m3

Exercise 5:
Calculate phone bill based on the following term:

Usage less than RM50 per month - no discount will be given

Usage less than RM100 per month - get 7% discount

Usage more than RM100 per month - get 21% discount

Page 27
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Practical 5: Repetition
Control Structure (2
hours)
Learning Outcomes:

At the end of this lesson, students should be able to:


i. Construct program using repetition control structures.

Task 1: Repetition using while statement


Write a complete Java program that will print message “I Love Computer
Science” 7 times.

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;
}
}
}

I Love Computer Science


I Love Computer Science
I Love Computer Science
I Love Computer Science
I Love Computer Science
I Love Computer Science
I Love Computer Science

Page 28
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 2: Repetition using while statement


Write a complete Java program that will print first 10 integers.

DisplayCounter.java
class DisplayCounter{

public static void main(String[] args){

int counter=1;

while(counter<=10){
System.out.print(counter);
counter=counter+1;
}

}
}
12345678910

Task 3: Repetition using while statement


Write a complete Java program that will calculate and display the sum of 10
numbers entered by user.

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)

Task 4: Repetition using while statement


Write a complete Java program that will accept 10 numbers entered by user. Then
find the sum for each odd and even numbers.

Sum.java

import java.util.Scanner;

class SumOddEven{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);

double counter=0, num=0, even=0, odd=0;

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;
}

System.out.print("\nSum of odd number: "+ odd);


System.out.print("\nSum of even number: "+ even);
}
}

Enter a number: 97.5


Enter a number: 100
Enter a number: 88.5
Enter a number: 64.5
Enter a number: 36.5
Enter a number: 99
Enter a number: 100
Enter a number: 86
Enter a number: 48
Enter a number: 72

Sum of odd number: 386.0


Sum of even number: 406.0

Page 30
Practical 5 : Repetition Control Structure (Sentinel-controlled)

Task 5: Repetition using for statement


Write a complete Java program that will accept 10 numbers entered by user. Then
find the sum for each odd and even numbers.

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);
}
}

Enter a number: 97.5


Enter a number: 100
Enter a number: 88.5
Enter a number: 64.5
Enter a number: 36.5
Enter a number: 99
Enter a number: 100
Enter a number: 86
Enter a number: 48
Enter a number: 72

Sum of odd number: 386.0


Sum of even number: 406.0

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.

while statement for statement

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:

 You can see that the loop-control-variable (counter) is exists in different


location, but the logic of execution still the same.
 The execution of expression counter = counter + 1; is similar and
equal to counter++;

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)

Task 7: Repetition using sentinel-controlled


Write a Java program that will accept marks from user and find the highest mark
entered. The process will continue until user keyed in -1.

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;

System.out.print("Enter mark: ");


mark = sc.nextDouble();
highest = mark;

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:

At the end of this lesson, students should be able to:


i. Construct programs that perform one-dimensional array operations for
problems involving frequency and total.

Task 1: Declare and Enter Data into Arrays


Create a Java program that contain two lists containing names and ages for seven
(7) persons. The data will be entered by user. Then display the lists.

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

//enter data into arrays


for(int i=0;i<name.length;i++){
System.out.print("Enter name and marks: ");
name[i] = sc.next();
age[i] = sc.nextInt();
}

//display data in arrays


for(int i=0;i<name.length;i++){
System.out.println("Name: "+ name[i] +", age: "+ age[i]);
}
}
}
Enter name and marks: Adam 930
Enter name and marks: Nuh 1000
Enter name and marks: Ibrahim 195
Enter name and marks: Ismail 137
Enter name and marks: Ishak 137
Enter name and marks: Yaakob 144
Enter name and marks: Muhammad 63
Name: Adam, age: 930

Page 36
Practical 6 : Arrays

Name: Nuh, age: 1000


Name: Ibrahim, age: 195
Name: Ismail, age: 137
Name: Ishak, age: 137
Name: Yaakob, age: 144
Name: Muhammad, age: 63

Explanation:
Code Explanation

Declare and create String array


String[] name = new String[7];
named name sized 7.

Declare and create int array named


int[] age = new int[7];
age sized 7.

The statements in loop-body will


for(int i=0;i<name.length;i++){
repeat name.length times i.e: 7
//loop-body
times.
}
name.length is the size of the array.

System.out.print("Enter name Prompt user to Enter name and


and marks: "); marks:

The element[i] of the array name will


name[i] = sc.next();
store String value entered by user.

The element[i] of the array age will


age[i] = sc.nextInt();
store int value entered by user.

The statements in loop-body will


for(int i=0;i<name.length;i++){
execute name.length times i.e: 7
//loop-body
times.
}
name.length is the size of the array.

System.out.println("Name: "+ will display output name and age,


name[i] +", age: "+ age[i]); and move to new line.

Page 37
Practical 6 : Arrays

Task 2: Accessing Elements in an Array


Given a lists of names and ages. Find the eldest among them.

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};

int oldest = age[0];


String nameold = name[0];
//accessing elements in an array
for(int i=1;i<name.length;i++){
if(age[i]>oldest){
oldest = age[i];
nameold = name[i];
}
}
System.out.print("The eldest is: "+ nameold +", "+
oldest);
}
}
The eldest is: Sulaiman, 180

Explanation:
Code Explanation

String[] name = {"Sulaiman", Declare String array named name


"Daud", "Musa", "Yusof", and initialize String values to the
"Muhammad"}; array name.

Declare int array named age and


int[] age = {180, 70, 123, 110,
initialize integer values to the array
63};
age.
Set the first element of array age to
int oldest = age[0];
the variable oldest.
if(age[i]>oldest){
Compare the element age[i] to
oldest = age[i];
oldest.
nameold = name[i];
If true then update oldest.
}

Page 38
Practical 6 : Arrays

Task 3: Displaying Elements in an Array


Write a complete Java program which create a double array marks, containing
the following values:

97.5 75.3 53.1 86.4 64.2

13.5 35.7 57.9 24.6 46.8

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

Task 4: Linear Search


Linear search or sequential search is a process for finding a target value within a
list.

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};

for(int i=0; i<array.length; i++){


if(search == array[i])
System.out.println(search + " is present "
+"at index " + i);
}
}
}

30 is present at index 2

Page 39
Practical 6 : Arrays

Task 5: Find Average


Write a complete Java program which accept ten (10) marks from user and store
it in the array marks, then display all elements in the array and the average of
the elements in the array.

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);
}
}

Enter mark: 97.5


Enter mark: 75.3
Enter mark: 53.1
Enter mark: 86.4
Enter mark: 64.8
Enter mark: 42
Enter mark: 100
Enter mark: 57.9
Enter mark: 46.8
Enter mark: 90
97.5 75.3 53.1 86.4 64.8 42.0 100.0 57.9 46.8 90.0
Average: 71.38

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

Find the highest mark.

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};

double highest = marks[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;

System.out.print("Enter ten numbers: ");

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);
}
}

Enter ten numbers: 1 2 3 4 5 6 7 8 9 10


No. of even: 5
No. of odd: 5

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:

At the end of this lesson, students should be able to:


i. Construct programs that use standard and/or user-defined methods
based on given problem.

Task 1: Understanding the Concept of Methods


Methods must be defined before it is being called.

Method Definitions

Four (4) types of method defintions with examples:

Type 1. A method definition which return no value, receive no parameters


void showWelcome(){
System.out.print("Welcome to Java");
}

Type 2. A method definition which return no value, receive parameters


void sayHello(String name){
System.out.print("Hello "+ name);
}

Type 3. A method definition which return int value, receive no parameters


(this type of definition is rarely used)
int calcProduct(){
return 10*10;
}

Type 4. A method definition which return int value, receive parameters


int calcAdd(int x, int y){
return x+y;
}

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,

ClassName obj = new ClassName();

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:

1. Calling a Type 1 method, receive no value, pass no arguments:


obj.showWelcome();

2. Calling a Type 2 method, receive no value, pass arguments:


obj.sayHello(String name);

3. Calling a Type 3 method, receive value, pass no arguments (rarely used):


obj.calcProduct();

4. Calling a Type 4 method, receive value, pass arguments:


obj.calcAdd(x, y);

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();

System.out.print("Enter your name and 2 numbers: ");


String name = sc.next();
int num1 = sc.nextInt();
int num2 = sc.nextInt();

obj.showWelcome();
obj.sayHi(name);
int result = obj.calcAdd(num1, num2);
System.out.print("Addition: "+ result);
}

void showWelcome(){
System.out.println("Welcome to Java");
}

void sayHi(String name){


System.out.println("Hello "+name);
}

int calcAdd(int x, int y){


return x+y;
}
}

Enter your name and 2 numbers: Amran 9 3


Welcome to Java
Hello Amran
Addition: 12

Page 46
Practical 7 : Methods

Task 2: A Method Accepting No Arguments and Returning No


Value
Write a complete Java program which print out a message “I Love Computer
Science” from a method named printMessage().

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");
}
}

I Love Computer Science

Page 47
Practical 7 : Methods

Task 3: A Method Accepting No Arguments and Returning No


Value
Write a complete Java program which print out the following messages:

Message 1: I Love Computer Science


Message 2: I Like Programming
Message 3: I Learn Java

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();

System.out.println("I Love Computer Science");


mc.methodName1();
mc.methodName2();
}

void methodName1(){
System.out.println("I Like Programming");
}

void methodName2(){
System.out.println("I Learn Java");
}
}

I Love Computer Science


I Like Programming
I Learn Java

Page 48
Practical 7 : Methods

Task 4: A Method with Arguments and Returning No Value


Write a complete Java program with method calling which display the following
output:

Hello, <yourname>

MethodCall3.java

class MethodCall3{
public static void main(String[] args){
MethodCall3 mc = new MethodCall3();

String name = "Amran";

mc.printName(name);
}

void printName(String a){


System.out.println("Hello, "+ a);
}
}

Hello, Amran

Page 49
Practical 7 : Methods

Task 5: A Method with Arguments and Returning No Value


Write a complete Java program which accept name and age of a person, then
display the following output from the method named printNameAge():

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();

System.out.print("Enter name and age: ");


String name = sc.next();
int age = sc.nextInt();
mc.printName(name,age);
}

void printName(String a, int b){


System.out.println("Hello, "+ a);
System.out.println("Your age now is "+ b +" years old.");
}
}

Enter name: Amran


Enter age: 40
Hello, Amran
Your age now is 40 years old.

Page 50
Practical 7 : Methods

Task 6: A Method without Arguments and Returning Value


Write a complete Java program which find the square value of 10.

SquareMain.java

class SquareMain {

public static void main(String[] args) {

SquareMain sm = new SquareMain();

int result;

result = sm.square();

System.out.println("Squared value of 10 is: " + result);

int square() {

return 10 * 10;

Squared value of 10 is: 100

Page 51
Practical 7 : Methods

Task 7: A Method Accepting Arguments and Returning Value


Write a complete Java program which return the square of a number 3 and 4.

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

Task 8: A Method Accepting Arguments and Returning Value


Write a complete Java program which return the sum and the product of two
integers.

ArithmeticMain.java

class ArithmeticMain{
public static void main(String[] args) {
ArithmeticMain am = new ArithmeticMain();

System.out.println("10 + 20 = " + am.getIntegerSum(10, 20));

System.out.println("20 x 40 = " + am.multiplyInteger(20, 40));


}

int getIntegerSum (int i, int j) {


return i + j;
}

int multiplyInteger (int x, int y) {


return x * y;
}
}

10 + 20 = 30
20 x 40 = 800

Page 53
Practical 7 : Methods

Task 9: A Method Accepting Arguments and Returning Value


Write a complete Java program which takes int as a parameter. Based on the
argument passed, the method returns the squared value of it.

SquareMain.java

class SquareMain {
public static void main(String[] args) {
SquareMain sm = new SquareMain();

int result=0;

for (int i = 1; i <= 5; i++) {


result = sm.getSquare(i);
System.out.println("Square of "+ i +" is : "+ result);
}
}

int getSquare(int x){


return x * x;
}
}

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

Task 10: Exercise

1. Create a non-static method,


a. Write the first line of a method named myMethod that takes three
parameters: an int and two Strings.
b. Write a line of code that calls myMethod, passing as arguments the
value 501, the name of your favorite colour, and the name of the state
you grew up on.
2. Create a non-static method,
a. Write a method called printAmerican that takes the day, date, month
and year as parameters and that displays them in American format.
b. Test your method by invoking it from main and passing appropriate
arguments. The output should look something like this (except that the
date might be different):
Saturday, July 22, 2015
c. Once you have debugged printAmerican, write another method
called printEuropean that displays the date in European format.
3. Write a method called square that takes an integer and returns an
approximation of the square of the parameter. Test the method using
main method.
4. Write a method named isNotDivisible that takes two integers, p and
q, and that returns true if p is not divisible by q, and false otherwise.
5. Write a recursive method named oddSum that takes a positive odd integer
n and returns the sum of odd integers from 1 to n.

Page 55

You might also like