Download presentation
Presentation is loading. Please wait.
1
lab6 PROGRAMMING 1 metheds chapter5
2
BEFORE WE START Your Cell Phone Silent Please Keep Quite
Find Your Computer and Switch On Ins.Ebtesam AL-Etowi
3
content To define methods. To invoke methods with a return value.
To invoke methods without a return value. To pass arguments by value. To determine the scope of variables. The Math Class. Ins.Ebtesam AL-etowi
4
Defining a Method The syntax for defining a method is as follows:
modifier returnValueType methodName (list of parameters) { // Method body; } Ins.Ebtesam AL-etowi
5
Calling a Method There are two ways to call a method in main, depending on whether the method returns a value or not. 1- If the method returns a value, a call to the method is usually treated as a value. For example, example1 : int larger = max(3, 4); System.out.println(larger); calls max(3, 4) and assigns the result of the method to the variable larger. 2- Another example of a call that is treated as a value is example2 : System.out.println(max(3, 4)); which prints the return value of the method call max(3, 4). Example for first case Ins.Ebtesam AL-etowi
6
method without a return value
void Method Example: Open braces main Call method close braces main Name of method Parameter Void not return Body of method Ins.Ebtesam AL-etowi
7
(cont..) Output: Ins.Ebtesam AL-etowi
8
method with a return value
Return value of type int Ins.Ebtesam AL-etowi
9
Passing Parameters by Values
Parameter by value call Method name Ins.Ebtesam AL-etowi
10
scope of variables A variable declared in a method is called a local variable. The scope of a local variable starts from its declaration and continues to the end of the block that contains the variable. A local variable must be declared and initialized before it isused. Example : Ins.Ebtesam AL-etowi
11
The Math Class The Math class contains the methods needed to perform basic mathematical functions. For example: System.out.print(Math.pow(2,8)); Ins.Ebtesam AL-etowi
12
Exercise1 Write a class that contains the following two methods:
/** Converts from Celsius to Fahrenheit */ public static double celsiusToFahrenheit(double celsius) /** Converts from Fahrenheit to Celsius */ public static double fahrenheitToCelsius(double fahrenheit) Ins.Ebtesam AL-etowi
13
Cont….. Ins.Ebtesam AL-etowi
14
Cont….. output Ins.Ebtesam AL-etowi
15
Exercise2 Write the following two methods:
// Return the reversal of an integer, i.e. reverse(456) returns 654 public static int reverse(int number) // Return true if number is palindrome public static boolean isPalindrome(int number) Ins.Ebtesam AL-etowi
16
Exercise2 Ispalindrome method Ins.Ebtesam AL-etowi
17
Exercise2 Revers method Ins.Ebtesam AL-etowi
18
Cont….. Output: Ins.Ebtesam AL-etowi
19
Thank You !
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.