Methods and dividing the program into smaller parts
Seoul National University of Science and Technology
Information Technology Management
Lecture slides index
April 9, 2025
main
method) as well as from inside other methods.System.out.println()
, and the reading of values with Integer.valueOf(scanner.nextLine())
. if
has been used in conditional statements, and while
and for
in loops.if
, while
, and for
in that the print and read commands are followed by parentheses, which may include parameters passed to the command.System.out.println("I am a parameter given to the method!")
calls a methods that performs printing to the screen.main
, yet inside out the “outermost” curly braces.greet
.greet
.public static void
.import java.util.Scanner;
public class ProgramStructure {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// program code
System.out.println("Let's try if we can travel to the method world:");
greet();
System.out.println("Looks like we can, let's try again:");
greet();
greet();
greet();
}
// own methods
public static void greet() {
System.out.println("Greetings from the method world!");
}
}
import java.util.Scanner;
public class ProgramStructure {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// program code
System.out.println("Print main method 1");
greet();
System.out.println("Print main method 2");
greet();
greet();
greet();
}
// own methods
public static void greet() {
System.out.println("Print greet method");
}
}
main
) in order from top to bottom, one at a time.main
) itself is a method.main
.printText
which prints the phrase “In a hole in the ground there lived a method” and a newline.public static void main(String[] args) {
printText();
}
public static void printText() {
// Write some code in here
}
Sample Output
public static void main(String[] args) {
// ask the user for the number of times that the phrase will be printed
// use the while command to call the method a suitable number of times
}
public static void printText() {
// write some code in here
}
Sample Output
How many times?
(user input) 7
In a hole in the ground there lived a method
In a hole in the ground there lived a method
In a hole in the ground there lived a method
In a hole in the ground there lived a method
In a hole in the ground there lived a method
In a hole in the ground there lived a method
In a hole in the ground there lived a method
Note
Print the prompt How many times?
on its own separate line!
greet
is defined.int
type parameter called numOfTimes
.greet
with different values.numOfTimes
is assigned the value 1
on the first call, and 3
on the second.System.out.println
, you can pass an expression as a parameter.3
and the final method call is of the form greet(3);
.public static void printUntilNumber(int number)
.public static void printFromNumberToOne(int number)
.public static void sum(int first, int second) {
System.out.println("The sum of numbers " + first + " and " + second + " is " + (first + second));
}
Examples of calling the sum
method.
public static void division(int numerator, int denominator)
that prints the result of the division of the numerator by the denominator.Sample method call
Sample Output
public static void divisibleByThreeInRange(int beginning, int end)
that prints all the numbers divisible by three in the given range.number
in the main method.incrementByThree
.// main program
public static void main(String[] args) {
int number = 1;
System.out.println("The value of the variable 'number' in the main program: " + number);
incrementByThree(number);
System.out.println("The value of the variable 'number' in the main program: " + number);
}
// method
public static void incrementByThree(int number) {
System.out.println("The value of the method parameter 'number': " + number);
number = number + 3;
System.out.println("The value of the method parameter 'number': " + number);
}
The execution of the program produces the following output.
number
is incremented inside the incrementByThree
method, there’s no issue.number
variable of the main program (main
method).number
variable living in the main program is different from the number
variable of the method.number
is copied for the method’s use, i.e., a new variable called number
is created for incrementByThree
method, to which the value of the variable number
in the main program is copied during the method call.number
inside the method incrementByThree
exists only for the duration of the method’s execution and has no relation to the variable of the same name in the main program.public static void main(String[] args) {
int number = 10;
modifyNumber(number);
System.out.println(number);
}
public static void modifyNumber(int number) {
number = number - 4;
}
void
is used in the definition.void
, meaning that they have not returned values.void
means that the method returns nothing.alwaysReturnsTen
which returns an integer-type (int
) variable (in this case the value 10).return
followed by the value to be returned (or the name of the variable whose value is to be returned).int
-type value of 10
when called.public static void main(String[] args) {
int number = alwaysReturnsTen();
System.out.println("the method returned the number " + number);
}
int
type variable as with any other int
value.All the variable types we’ve encountered so far can be returned from a method.
Type of return value
Example
Method returns int
type variable
Method returns double
type variable
public static int numberUno()
that returns the value 1.public static String word()
.return
commandreturn
, the execution of that method ends and the value is returned to the calling method.return
are never executed.return
return
command from a void methodpublic static void nameOfMethod()
it is possible to return from itreturn
command that is not followed by a value.sum
and avg
are used to help in the calculation.public static double average(int number1, int number2, int number3) {
int sum = number1 + number2 + number3;
double avg = sum / 3.0;
return avg;
}
One way to call the method is as follows.
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int first = Integer.valueOf(scanner.nextLine());
System.out.print("Enter the second number: ");
int second = Integer.valueOf(scanner.nextLine());
System.out.print("Enter the third number: ");
int third = Integer.valueOf(scanner.nextLine());
double averageResult = average(first, second, third);
System.out.print("The average of the numbers: " + averageResult);
}
sum
and avg
defined inside the method average
are not visible in the main program.public static void main(String[] args) {
int first = 3;
int second = 8;
int third = 4;
average(first, second, third);
// trying to use a method's internal variable, DOES NOT WORK!
System.out.print("The average of the numbers: " + avg);
}
avg
that has been defined inside the method average
and print its value.avg
only exists inside the method average
, and it cannot be accessed outside of it.public static void main(String[] args) {
int first = 3;
int second = 8;
int third = 4;
// trying to use the method name only, DOES NOT WORK!
System.out.print("The average of the numbers: " + average);
}
average
as if it were a variable.public static void main(String[] args) {
int first = 3;
int second = 8;
int third = 4;
// calling the method inside the print statement, DOES WORK!
System.out.print("The average of the numbers: " + average(first, second, third));
}
public static void main(String[] args) {
int first = 5;
int second = 10;
beginningToMiddle(first, second);
System.out.println(first);
}
public static void beginningToMiddle (int start, int end) {
int middle = (start + end)/2;
while (start < middle) {
System.out.println("step");
start++;
}
}
return first + second;
, the expression first + second
is evaluated, and then its value is returned.sumOfNumbers
."The combined sum of the numbers is: "+ sum(first, second)
.first
and second
and copies their values as the values of the method sum
’s parameters.sum
method then adds the values of the parameters together, after which it returns a value.sum
method call, whereby the sum is appended to the string "The combined sum of the numbers is: "
.public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int first = Integer.valueOf(scanner.nextLine());
System.out.print("Enter the second number: ");
int second = Integer.valueOf(scanner.nextLine());
System.out.print("The combined sum of the numbers is: " + sum(first, second));
}
public static int sum(int first, int second) {
return first + second;
}
first
and second
) “by accident”.public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the first number: ");
int number1 = Integer.valueOf(scanner.nextLine());
System.out.print("Enter the second number: ");
int number2 = Integer.valueOf(scanner.nextLine());
System.out.print("The total sum of the numbers is: " + sum(number1, number2));
}
public static int sum(int first, int second) {
return first + second;
}
number1
is copied as the value of the method parameter first
, and the value of the variable number2
is copied as the value of the parameter second
.public static void main(String[] args) {
int number = 3;
modifyNumber(number);
System.out.println(addAndReturn(number));
}
public static void modifyNumber(int number) {
number = number + 2;
}
public static int addAndReturn(int number) {
return number + 10;
}
sum
in the exercise template so that it calculates and returns the sum of the numbers that are given as the parameters.public static int sum(int number1, int number2, int number3, int number4) {
// write your code here
// remember to include return (at the end)!
}
public static void main(String[] args) {
int answer = sum(4, 3, 6, 1);
System.out.println("Sum: " + answer);
}
Sample Output
Note
return
command that returns the wanted data.System.out.println
)
smallest
that returns the smaller of the two numbers passed to it as parameters.public static int smallest(int number1, int number2) {
// write your code here
// do not print anything inside the method
// there must be a return command at the end
}
public static void main(String[] args) {
int answer = smallest(2, 7);
System.out.println("Smallest: " + answer);
}
Sample Output
greatest
that takes three numbers and returns the greatest of them.public static int greatest(int number1, int number2, int number3) {
// write some code here
}
public static void main(String[] args) {
int answer = greatest(2, 7, 3);
System.out.println("Greatest: " + answer);
}
Sample Output
average
that calculates the average of the numbers passed as parameters.sum
must be used inside this method!public static int sum(int number1, int number2, int number3, int number4) {
// you can copy your implementation of the method sum here
}
public static double average(int number1, int number2, int number3, int number4) {
// write your code here
// calculate the sum of the elements by calling the method sum
}
public static void main(String[] args) {
double result = average(4, 3, 6, 1);
System.out.println("Average: " + result);
}
Sample Output
public class Example {
public static void main(String[] args) {
// program code
System.out.println("Print main method 1");
greet();
System.out.println("Print main method 2");
greet();
greet();
greet();
}
// own methods
public static void greet() {
System.out.println("Print greet method");
}
}
public static void main(String[] args) {
int beginning = 1;
int end = 5;
printStars(beginning, end);
}
public static void printStars(int beginning, int end) {
while (beginning < end) {
System.out.print("*");
beginning++; // same as beginning = beginning + 1
}
}
main
method.beginning
and end
, and also assign values to them.printStars
:public static void main(String[] args) {
int beginning = 1;
int end = 5;
printStars(beginning, end);
}
public static void printStars(int beginning, int end) {
while (beginning < end) {
System.out.print("*");
beginning++; // same as beginning = beginning + 1
}
}
printStars
is called, the main
method enters a waiting state.beginning
and end
to be created for the method printStars
, to which the values passed as parameters are assigned to.beginning
and end
of the main
method.printStars
is illustrated below.public static void main(String[] args) {
int beginning = 1;
int end = 5;
printStars(beginning, end);
}
public static void printStars(int beginning, int end) {
while (beginning < end) {
System.out.print("*");
beginning++; // same as beginning = beginning + 1
}
}
beginning++
is executed within the loop, the value of the variable beginning
that belongs to the method currently being executed changes.public static void main(String[] args) {
int beginning = 1;
int end = 5;
printStars(beginning, end);
}
public static void printStars(int beginning, int end) {
while (beginning < end) {
System.out.print("*");
beginning++; // same as beginning = beginning + 1
}
}
main
remain unchanged.printStart
would continue for some time after this.main
method.Tip
main
method of the program calls a separate start
method, inside of which two variables are created, the sum
method is called, and the the value returned by the sum
method is printed.int sum = sum(first, second);
creates the variable sum
in the method start
and calls the method sum
.start
enters a waiting state.number1
and number2
are defined in the method sum
, they are created right at the beginning of the method’s execution, after which the values of the variables given as parametes are copied into them.sum
adds together the values of the variables number1
and number2
.return
returns the sum of the numbers to the method that is one beneath it in the call stack - the method start
in this case.sum
.main
method.main
method, the execution of the program ends.multiplicationTable
that prints the multiplication table of the given number.printMultiplicationTableRow
method.public static void multiplicationTable(int max) {
int number = 1;
while (number <= max) {
printMultiplicationTableRow(number, max);
number++;
}
}
public static void printMultiplicationTableRow(int number, int coefficient) {
int printable = number;
while (printable <= number * coefficient) {
System.out.print(" " + printable);
printable += number;
}
System.out.println("");
}
printStars
that prints the given number of stars and a line break.
public static void printStars(int number) {
// you can print one star with the command
// System.out.print("*");
// call the print command n times
// in the end print a line break with the comand
// System.out.println("");
}
public static void main(String[] args) {
printStars(5);
printStars(3);
printStars(9);
}
printSquare(int size)
that prints a suitable square with the help of the printStars
method.
printSquare(4)
results in the following output:Sample output
Important
printStars
method inside the printSquare
method.printRectangle(int width, int height)
that prints the correct rectangle by using the printStars
method.
printRectangle(17, 3)
should produce the following output:Sample output
printTriangle(int size)
that prints a triangle by using the printStars
method.printTriangle(4)
should print the following:Sample output
printSpaces(int number)
that produces the number of spaces specified by number
.
printStars
method from your previous exercise or reimplement it in this exercise template.printTriangle(int size)
that uses printSpaces
and printStars
to print the correct triangle.
printTriangle(4)
should print the following:Sample output
christmasTree(int height)
that prints the correct Christmas tree.
printSpaces
and printStars
.main
method) as well as from inside other methods.Computer Language