Lesson 4. Java Methods
Lesson 4. Java Methods
Topic #4
z
OBJECT ORIENTED
PROGRAMMING
02/15/2024
2
Java
z
is a full-fledged and powerful language
that can be used in many ways
z
A single space should be added on both
sides of a binary operator
PROGRAMMING
ERRORS
02/15/2024
7
z
Syntax Error
Errors that are detected by the compiler are called syntax errors
or compile errors.
Syntax errors result from errors in code construction, such as
mistyping a keyword, omitting some necessary punctuation, or
using an opening brace without a corresponding closing brace.
These errors are usually easy to detect because the compiler
tells you where they are and what caused them.
02/15/2024
8
z
Runtime Error
Runtime errors are errors that cause a program to terminate
abnormally. They occur while a program is running if the
environment detects an operation that is impossible to carry out.
z
Logic Error
z
Common Error
TRACING A
PROGRAM
02/15/2024
12
1 public class ComputeArea {
z
2 public static void main(String[] args) {
3 double radius; // Declare radius
4 double area; // Declare area
5
6 // Assign a radius
7 radius = 20; // radius is now 20
8
9 // Compute area
10 area = radius * radius * 3.14159;
11
12 // Display results
13 System.out.println("The area for the circle of radius " +
14 radius + " is " + area);
15 }
02/15/2024
16 }
13
JAVA
METHODS
02/15/2024
14
z
METHOD
A method is a block of code which only runs when it is
called. You can pass data, known as parameters, into a
method.
z
Syntax
z
Sample Code
z Definition of Terms
z
Call a Method
z Sample Code
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod(); Calling method
}
}
// Outputs: "I just got executed!"
02/15/2024
21
public
z class Main {
static void myMethod() {
System.out.println("I just got executed!");
}
public static void main(String[] args) {
myMethod();
myMethod();
myMethod();
Output: // I just got executed!
} // I just got
} executed!
02/15/2024
/ / I just got
22
z
PARAMETERS
ARGUMENTS
02/15/2024
23
z
Information can be passed to methods as parameter.
Parameters act as variables inside the method.
// Anja Saija
25
z
Key Take Aways
fname is a parameter
Liam, Jenny and Anja are arguments
02/15/2024
26
z
MULTIPLE
PARAMETERS
02/15/2024
27 public class Main {
static
z void myMethod(String fname, int
age) {
System.out.println(fname + " is " +
age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
Ouptut: // Liam is 5
} // Jenny
} is 8
02/15/2024
// Anja is
28
z
RETURN
VALUES
02/15/2024
29
z
Activity 1
Create a java program and a flowchart for this problem.
Score Grade
90 A
80 B
70 C
60 D
59-below FAILED
02/15/2024