Lab 6_ Method in Java(Part 1)
Lab 6_ Method in Java(Part 1)
College of Science
Computer Department
2024-2025
Method in Java
First Part
Imperative Programming
Semester: 2
Lab 6
A block of code that performs a specific task. Code reusability and organization.
•int[][] matrix = new int[3][4]; // 3 rows, 4 columns
Example
Public static int sub(int a, int b) {
return a - b;
}
Method Parameters
Definition
Parameters are variables that allow you to pass information into methods.
Syntax
returnType methodName(parameterType parameterName) {
// method body
}
Example
Public static void printName(String name){
system.out.println(“Hello, ”+name);
}
Public static void main(String [] args){
Scanner scan = new Scanner(System.in);
String name = scan.next();
printName(name);
}
•int[][] matrix = new int[3][4]; // 3 rows, 4 columns
•arrayName[rowIndex][columnIndex];
Return Types
Definition
The return type specifies what type of value a method will return after execution.
Example
Public static boolen primeNum(int number){
int count=0;
for(int i=1 ; i<=number ; i++){
if(number%i == 0){
count++;
}
if(count>2){
return false;
}
Smallest Number Among Three
public static double smallestNum(double n1, double n2, double n3) {
if (n1 < n2 && n1 < n3) {
return n1;
} else if (n2 < n1 && n2 < n3) {
return n2;
} else {
return n3;
}
}
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Three Numbers:");
double num1 = s.nextDouble();
double num2 = s.nextDouble();
double num3 = s.nextDouble();
double smallest = smallestNum(num1, num2, num3);
System.out.println("The smallest number is: " + smallest);
}
Count Words in String
public static int countWords(String str) {
int count = 0;
for (int i = 0; i < str.length(); i++) {
if (str.charAt(i) == ' ') {
count++;
}
}
count = count + 1;
return count;
}
Details:
Hourly Rate: $10 per hour
Input: Number of hours worked in a day
Output: Total daily salary
Exercises
• Write a method to check if a number is prime.
• Write a Java method to count all vowels in a string.
• Write a method to calculate the power of a number.
• Write a method that converts Celsius to Fahrenheit.
• Write java method to calculate factorial to any given number.
• Write a Java method to compute the sum of the digits in an integer.
• Create a checkage() method with an integer variable called age If age is less than 18, print "access denied“, If age
is greater than, or equal to, 18, print "access granted“.
• Write a Java method to check whether a year (integer) entered by the user is a leap year or not.
• Create a program to manage employee salaries where you can add, remove, and update employee information.
• Methods could include calculating monthly or yearly salary, updating employee details, adding new employees,
and displaying employee information.