File 61
File 61
Objectives:
Methods:
A Java method is a collection of statements that are grouped together to perform some
specific task with or without returning anything to the caller. A method definition consists of
its method name, parameters, return value type, and body. The syntax for defining a method
is as follows:
The following code shows how to define and call a method in Java.
1
public static void maxPrint(int num1, int num2) {
if (num1>num2)
System.out.println("Max: " + num1);
else
System.out.println("Max: " + num2);
}
if (num1>num2)
result = num1;
else
result = num2;
return result;
}
}
2
String and Method: The following code shows how to pass a string as an argument and
manipulate that string in Java.
return thanksMsg.concat(userInformation);
}
}
Array and Method: In Java, array is passed as a reference. The following code shows how
to pass an array as an argument and reverse the elements of that array using methods.
3
for(int i=0; i<arrLen/2; i++) {
int temp = arr[i];
arr[i] = arr[arrLen-1-i];
arr[arrLen-1-i] = temp;
}
}
}
Lab Tasks:
1. Write a method countVowels(String sentence) that takes a String as a parameter
and returns the number of vowels.
3. Write a method sumDigit() that takes an integer and returns the sum of digits.
4. Write a method isPrime() that takes an integer and returns true if it’s prime or false
otherwise. Then using isPrime() method write another method generatePrime() that
takes two integers and prints all the prime numbers in that range.