0% found this document useful (0 votes)
17 views

METHODS

Uploaded by

Queenzlet Turao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views

METHODS

Uploaded by

Queenzlet Turao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 26

JAVA JUMBLE

LET'S PLAY A GAME!


METHODS
INSRTRUCTION SPECIALIST: CARL DREDD ROSALES
Modularity
modularity: Writing code in smaller, more manageable components or modules. Then
combining the modules into a cohesive system.

– Modularity with methods. Break complex code into smaller tasks and organize it
using methods.

Methods define the behaviors or functions for objects.

An object’s behavior refers to what the object can do (or what can be done to it). A
method is simply a named group of statements.
– main is an example of a method
Example
Consider the following code which asks the user to enter two numbers
and print out the average.

Scanner console = new Scanner(System.in);


System.out.print("Enter a number: ");
int num1 = console.nextInt();
System.out.print("Enter a number: ");
int num2 = console.nextInt();
System.out.println("The average is " + (num1 + num2)/2.0);

What if we need to do this again?


We don't want to repeat this code by copying and pasting as shown in the next
slide.
Example
If we need to repeat this task, we do not want to simply copy and paste out code:

Scanner console = new Scanner(System.in);


int num1, num2; Let's factor out this piece
System.out.print("Enter a number: "); of code, convert it into a
num1 = console.nextInt(); method by giving it a
System.out.print("Enter a number: "); name!
num2 = console.nextInt();
System.out.println("The average is " + (num1 + num2)/2.0);
Then we can call it
System.out.print("Enter a number: "); repeatedly if we wish to
num1 = console.nextInt(); run the code.
System.out.print("Enter a number: ");
num2 = console.nextInt();
System.out.println("The average is " + (num1 + num2)/2.0)
Method
One way to organize code and to make it more readable and reusable is to factor
out useful pieces into reusable methods.

A method is a named group of programming instructions that accomplish a


specific task. If we want to perform the task, we simply "call" the method by its
name. A method may be called as many times as we wish to redo the task.

The "30 seconds" button on the microwave is an example of a method. If we press


it(call it by its name), it will run the microwave 30 seconds. Later, if we want to heat
something else, we can press it again to run the microwave another 30 seconds.

In other programming languages, methods are also called procedures or


functions.
Syntax
modifier static returnType nameOfMethod (parameter1, parameter2, ...) {

// method body

}
6 Methods Declaration Components
1. Modifiers- such as public, private
2. The return type — the data type of the value returned by the
method, or void if the method does not return a value.
3. The method name — the rules for field names apply to method
names as well, but the convention is a little different.
4. The parameter list in parenthesis - a comma-delimited list of
input parameters, preceded by their data types, enclosed by
parentheses, ( ). If there are no parameters, you must use empty
parentheses.
6 Methods Declaration Components

5. An exception list —to be discussed later.


6. The method body, enclosed between braces —the method's
code, including the declaration of local variables, goes here.
Method
A method is a group of code that has a name and can be called using parentheses.
public class Main{
public static void main(String[] args){ Enter a number: 4
// calling it the first time Enter a number: 6
average(); The average is 5.0
// calling it again to repeat the task
average();
}
public static void average(){ Enter a number: 10
Scanner console = new Scanner(System.in); Enter a number: 11
int num1, num2; The average is 10.5
System.out.print("Enter a number: ");
num1 = console.nextInt();
System.out.print("Enter a number: ");
num2 = console.nextInt();
System.out.println("The average is " + (num1 + num2)/2.0);
}}
Static Method Inside Driver Class
The driver class is the class with the main method. Note that the main method is the begin
point of a run of any program.

public class MyClass{


public static void main(String[] args){
method2();
method1();
}
public static void method1(){
System.out.println(“running method1”);
}
public static void method2(){
System.out.println(“running method2”);
}
}
Static Method Inside Driver Class
The order of the methods in the driver class does not matter and does not affect the
run or output of the program. The program below has the exact same output as the
program from the previous slide. The main method is always the starting point of the
run of any program.
public class MyClass{
public static void method1(){
System.out.println(“running method1”);
}
public static void main(String[] args){
method2();
method1();
}
public static void method2(){
System.out.println(“running method2”);
}
}
Control flow
When a method is called, the program's execution...
"jumps" into that method, executing its statements, then
"jumps" back to the point where the method was called.
What is the output?
public class MethodsExample {
public static void main(String[] args) {
public static void message1() {
message1();
System.out.println("This is message1.");
}

message2();
public static void message2() {
} System.out.println("This is message2.");
System.out.println("Done with message2.");
Output:
}
} This is message1.
This is message2.
Done with message2.
...
}
Method Signature
A method signature for a method consists of the method name and the ordered, possibly empty,
list of parameter types.
public void name(parameters){
statements;
}
Examples:
public static void method1(){
… void: no value is no parameters
} returned when
method ends.
public static void method2(int x, double y){

}
The parameters in the method header are formal parameters.
Static Example
When calling a method with parameters, values provided in the parameter list
need to correspond to the order and type in the method signature.
public class MyProgram{
public static void main(String[] args){
mystery1(3, 4); // error, incompatible types!
mystery1(); // missing actual parameters
mystery1(3); // missing actual parameters
mystery1(3, true); // correct
mystery2(3.2, 3.0); // error, incompatible types!
double a = 2.5;
int b = 5;
mystery2(double a, int b); // error, no type in actual parameters
mystery2(a, b); // correct

}
public static void mystery1(int x, boolean y){

}
public static void mystery2(double x, int z){

}
}
Method Returns
Methods in Java can have return types. Such non-void methods return values
back that can be used by the program. A method can use the keyword “return” to
return a value.

public type methodName(type var1,…, type var2){



}
Examples: Note: Method
public static int method1(){ parameters are
… its inputs and
} return types method returns
are its outputs.
public static double method2(int x){

}
Example
public class Main {
public static void main(String[] args) {
int a = 5;
int b = 10;
int maximum = max(a, b);
System.out.println("Maximum of " + a + " and " + b + "
is: " + maximum);
}

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


if (x > y)
return x
else
return y;
}
}
METHODS
VOID METHODS
Void methods do not have return values and are therefore not called as part of an expression.
public class MyClass{
public static void main(String[] args){
int a = 3 + printX(5); //error! Does not return!
int b = 5 * twiceX(3); // correct, b = 30
printX(5); // correct
// Output: The input x is 5
}
public static void printX(int x){
System.out.println(“The input x is” + x);
}
public static int twiceX(int x){
return 2 * x;
}
}
OVERLOADED METHODS
Methods are said to be overloaded when there are multiple methods with the same name but a
different signature.
public class MyClass{
public static void main(String[] args){
double a = add(1, 2) + add(1.8, 5.2) + add(1, 2, 3);
System.out.println(a); // 16.0
}
public static int add(int x, int y){
return x + y;
}
public static double add(double x, double y){
return x + y;
}
public static int add(int x, int y, int z){
return x + y + z;
}
}
Value Semantics
Parameters are passed using call by value or value semantics. Call by value initializes the formal parameters with
copies of the actual parameters.
When primitive variables (int, double,boolean) and String(the only object class that does this) are passed as
parameters, their values are copied.
– Modifying the parameter will not affect the variable passed in.

public class MyClass{ The x variable in


public static void main(String[] args){ main is different
int x = 23;
than the x
strange(x);
System.out.println("2. x = " + x);
variable in
}
strange.
public static void strange(int x){
x = x + 1;
System.out.println("1. x = " + x);
Output:
} 1. x = 24
}
Note: The value of x in main did not change.
2. x = 23
Value Semantics
Value semantics: methods cannot change the values of primitive
types(int, boolean, float) and String.
public class MyClass{
public static void main(String[] args){
int x = 5;
doubleMyNumber(x);
System.out.println(“My number is” + x); //My number is 5
}
public static void doubleMyNumber(int x){
x = x * 2;
}
}

Note: The value of x in main did not change.


USING
CONFIRM
DIALOG
BOXES
A confirm dialog box that displays the
options Yes, No, and Cancel can be
created using the showConfirmDialog()
method in the JOptionPane class.
To create a confirm dialog box

int choice = JOptionPane.showConfirmDialog(parentComponent, "Prompt


message", "Title", JOptionPane.YES_NO_CANCEL_OPTION,
JOptionPane.QUESTION_MESSAGE);
THANK YOU!

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy