ch05
ch05
Badour AlBahar
Kuwait University
• Syntax of a Method:
accessModifier returnType methodName(parameterList) {
// method body
}
Declaring Methods
accessModifier returnType methodName(parameterList) {
// method body
Method header
• Modifiers, return type, method name and parameters
Method body
• Delimited by left and right braces
• Contains one or more statements that perform the method’s task
A return statement
• returns a value (or just control) to the point in the program from which the
method was called
Declaring Methods
accessModifier returnType methodName(parameterList) {
// method body
// method body
returnType:
• Specifies the type of data a method returns (that is, gives back to its
caller) to the calling method after performing its task
• In some cases, you’ll define methods that perform a task but will not
return any information
• Such methods use the return type void.
Declaring Methods
accessModifier returnType methodName(parameterList) {
// method body
methodName:
• Method names begin with an initial lowercase letter.
• For a method that requires additional information to perform its task, the
method can specify one or more parameters (parameterList) that represent
that additional information.
• Defined in a comma-separated parameter-list located in the parentheses that follow
the method name
• Each parameter must specify a type and an identifier
• A method’s parameters are considered to be local variables of that method and can
be used only in that method’s body
static Methods
• Sometimes a method performs a task that does not depend on the
contents of any object
• Method applies to the class in which it’s declared as a whole and is known as
a static method or a class method
• For any class imported into your program, you can call the class’s
static methods by specifying the name of the class in which the
method is declared, followed by a dot (.) and the method name
• All Math class methods are static
• Each is called by Math followed by a dot (.) and the name of the method.
• Method arguments may be constants, variables or expressions
static Methods
• static methods in the same class can call each other directly
• Any other class that uses a static method must fully qualify the
method name with the class name
• For now, we begin every method declaration with the keywords
public and static
• You’ll learn about non-public and non-static methods in Chapter 7.
Why Is Method main Declared static?
• When you execute the Java Virtual Machine (JVM) with the java
command, the JVM attempts to invoke the main method of the class
you specify
• Declaring main as static allows the JVM to invoke main without
creating an object of the class
Exercise
MaximumFinder
• Write a method named maximum that takes three double values as
input parameters and returns the largest of the three.
Declaring Methods Example
• Class MaximumFinder has two methods—main (lines 8–25) and
maximum (lines 28–41)
• The maximum method determines and returns the largest of three
double values
• Most methods do not get called automatically
• You must call method maximum explicitly to tell it to perform its task
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Class Math
• Class Math declares two constants
• Math.PI (3.141592653589793)
• is the ratio of a circle’s circumference to its diameter
• Math.E (2.718281828459045)
• is the base value for natural logarithms (calculated with static Math method log)
• These constants are declared in class Math with the modifiers public, static and
final.
• public allows you to use these fields in your own classes
• static allows them to be accessed via the class name Math and a dot (.) separator
• final indicates that they are constants—value cannot change after they are initialized.
• A class’s variables are sometimes called fields.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
Class Math
We can implement method maximum by reusing method Math.max
• The entire body of our maximum method could also be implemented with
two calls to Math.max, as follows:
• Usage Example:
Day today = Day.MONDAY;
• Figure 5.9 demonstrates scoping issues with static and local variables.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
String concatenation
• String concatenation allows you to assemble String objects into larger
strings by using operators + or +=
• When both operands of operator + are String objects, operator +
creates a new String object in which the characters of the right
operand are placed at the end of those in the left operand
• Example:
• "Hello" + " World" creates "Hello World".
String concatenation
• Every primitive value and object in Java can be represented as a String
• When one of the + operator’s operands is a String, the other is
converted to a String, then the two are concatenated
• Example:
• "Age: " + 25 creates "Age: 25"
• "Result: " + 4.5 creates "Result: 4.5"
String concatenation
• If a boolean is concatenated with a String, the boolean is converted to
the String "true" or "false"
• Example:
boolean status = true;
"Status: " + status creates "Status: true"
© 1992-2015 by Pearson Education, Inc. All Rights Reserved.
int y = 5;
System.out.println("y+2= " + y+2); y+2= 52
int y = 5;
System.out.println("y+2= " + (y+2)); y+2= 7
printInfo(10 + 20);
printInfo("Sum: "+10+20);
printInfo("Sum: "+(10+20));
Exercise
Given this method:
public static void printInfo(String message) {
System.out.println(message);
}
printInfo("Hello");
printInfo(10);
printInfo(102.75);
printInfo('A');
Exercise
Given this method:
public static void printInfo(String message) {
System.out.println(message);
}
• How would you combine the two Strings firstName and lastName to
get one String: ?
fullName = "Zain Saleh"
Exercise
Guess the Number Game
Write a Java program that lets the user guess a randomly generated
number.
In your program include a method, checkGuess, that evaluates the
user's guess:
• If the user’s guess is too high, print "Too high! Try again.”
• If the user’s guess is too low, print "Too low! Try again.”
• If the user guesses correctly, print "Congratulations! You guessed the
number!”
This method should return true if the guess is correct, or false if the
guess is incorrect.
Exercise
Guess the Number Game
• Try adding:
• Attempt Counter:
• Keep track of the number of guesses the user has made.
• Repeat the game option:
• After the correct guess, ask if they want to play again (Yes/No).
Exercise
Calculating Factorial Using Recursion
• The factorial of a number 𝑛 (written as 𝑛!) is the product of all
positive integers less than or equal to 𝑛.
𝑛! = 𝑛 × 𝑛 − 1 × 𝑛 − 2 × 𝑛 − 3 … 2 × 1
• For example:
5! = 5 × 4 × 3 × 2 × 1 = 120
Method factorial
// Recursive method to calculate factorial
public static int factorial(int n) {
// Base case: if n is 1, return 1 (since 1! = 1)
if (n == 1) {
return 1;
} else {
// Recursive case: n * factorial of (n - 1)
return n * factorial(n - 1);
}
}
How it Works
When factorial(5) is called:
• It returns 𝟓 × factorial(4)
• Which returns 4 × factorial(3)
• Which returns 𝟑 × factorial(2)
• Which returns 2 × factorial(1)
• Finally, factorial(1) returns 1 (base case).
Recursion
• Recursion is a powerful tool in programming but requires careful
design to avoid infinite loops. Each recursive function should have a
clear base case and move toward it in each recursive call.
Exercise
What will be the output?
public class Main {
public static void main(String[] args) {
countdown(5);
}