Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Tutorial 01 - Java Methods

Question 01
Input two numbers from the key board and then find a largest number among two numbers
using a java method.
Note: You can use ‘built-in method’ for that.

import java.util.Scanner;

public class Ex01 {

public static void main(String[] args) {


Scanner inputNum = new Scanner(System.in);
System.out.print("Number one: ");
int x = inputNum.nextInt();
System.out.print("Number two:");
int y = inputNum.nextInt();

System.out.print("The largest number is =" + largestNum(x, y));


}

public static int largestNum(int x, int y) {


int z;
z = Math.max(x, y);
return z;
}
}

Result:
Number one: 9
Number two:5
The largest number is =9

1
Object Oriented System Design - ICT 325
Question 02
Write a program with a method named getAvg that accepts two integers as an argument and
return its average. You can get two integer numbers from the key board and print the results
by calling this method from main().

import java.util.Scanner;

public class Ex02 {


public static void main(String[] args) {
Scanner num = new Scanner(System.in);
int n1, n2;

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


n1 = num.nextInt();

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


n2 = num.nextInt();

int average = getAvg(n1, n2);

System.out.println("Average: " + average);


}

public static int getAvg(int num1, int num2) {


return (num1 + num2) / 2;
}
}

Result:
Enter first number: 5
Enter second number: 8
Average: 6

2
Object Oriented System Design - ICT 325
Question 03
Create a method to find out given number is odd or even. You can define a number inside the
program.

class Ex03 {

public static void main(String[] args) {


System.out.println("Number is " + numType(30));
}

public static String numType(int x) {


String type;
if (x % 2 == 0) {
type = "even";
} else {
type = "odd";
}
return type;
}
}

Result:
Number is even

Question 04
“A method which calls itself is called recursive method.” Use a recursive method to get a
factorial (factorial of 4 is 4x3x2x1 = 24) of a given number.

class Ex04 {

public static void main(String s[]) {


System.out.println("Factorial of 4 is " + calculation(4));
}

public static int calculation(int i) {


if (i == 1) {
return 1;
}

return i * calculation(i - 1);


}
}

Result:
Factorial of 4 is 24

3
Object Oriented System Design - ICT 325

You might also like