Chapter 1 · Foundations
Methods and input
Step 1 of 20 · Concept
Name a piece of code
You have used two methods already: main, where Java starts, and println. A method is a named piece of
code. You call it by its name, and it runs.
In this lesson you will:
- write methods of your own,
- give them values and get answers back,
- read numbers that the user types.
Step 2 of 20 · Concept
A method of your own
| part | means |
|---|---|
static | the method belongs to its class (lesson 7 shows the other kind) |
int before the name | the return type: what the method gives back |
square | the method's name |
(int n) | the parameter: a box for the value the method gets |
return n * n; | gives the value back and ends the method |
A method with two parameters separates them with a comma: (int a, int b).
Step 3 of 20 · Quiz
What will it print?
main calls square four times, with i from 1 to 4. Type exactly what it prints.
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
System.out.println(i + " squared is " + square(i));
}
}
Step 4 of 20 · Demo
See it run
Run it and compare with your answer.
Step 5 of 20 · Trace
A call gets its own frame
Lesson 2 showed a frame going on the stack for each call. Press Next and watch square's frame come and go.
public class Square {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
int s = square(4);
System.out.println(s);
}
}mainruns. Line 7 callssquare(4).- A frame for
squaregoes on top ofmain's. Its boxnholds4. Line 3 is next. returngave back16, andsquare's frame was removed.16is stored ins.- Line 8 printed
16.mainends, and the stack is empty.
Step 6 of 20 · Concept
Arguments are copies
static int addOne(int n) {
n = n + 1;
return n;
}
The value in a call, such as x in addOne(x), is the argument. The method gets a copy of it in its own box,
n. Changing n never changes x.
Step 7 of 20 · Quiz
Which box changed?
main runs int x = 5;, then int y = addOne(x);. What do x and y hold then?
static int addOne(int n) {
n = n + 1;
return n;
}
Step 8 of 20 · Concept
return ends the method
return gives a value back and ends the method at once. So a method may have a return in each branch of an
if:
static String size(int n) {
if (n > 100) {
return "big";
}
return "small";
}
size(500) returns "big" and stops: the last line never runs. size(7) skips the if and returns "small".
The return type is String, so each return gives text.
Step 9 of 20 · Exercise
Your turn: the larger number
Write the method static int max(int a, int b). It returns the larger of its two parameters.
main already calls it. Until the method exists, javac says cannot find symbol. Then the program must print:
max(3, 8) is 8
max(10, 2) is 10
The method goes inside the class, next to main. Start it with static int max(int a, int b) {.
Like size: an if that returns a when a > b, then a return b; for every other case.
static int max(int a, int b) {
if (a > b) {
return a;
}
// what is left?
}
Step 10 of 20 · Concept
void: a method that answers nothing
Some methods do a job and give nothing back. Their return type is void, like main's.
static void greet(String name) {
System.out.println("Hello, " + name + "!");
}
Call it as a statement of its own: greet("Ada"); prints Hello, Ada!.
Step 11 of 20 · Exercise
Your turn: repeat
Complete repeat(s, n). It returns the text s written n times in a row: repeat("ab", 3) is "ababab".
Then the program prints:
============
| abababab |
============
result starts as empty text, "". A loop that runs n times adds s to its end each round.
for (int i = 0; i < n; i++) runs n rounds. += joins text too (lesson 3): result += s;.
for (int i = 0; i < n; i++) {
result += s;
}
Step 12 of 20 · Concept
Java's library has a Scanner
Scanner reads what the user types, the program's standard input. It is not part of the language but of
Java's library, in the package java.util.
import java.util.Scanner;
public class Sum {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
}
}
importat the top tells javac where to findScanner.System.inis standard input, asSystem.outis the output.new Scanner(System.in)makes a Scanner that reads it. The boxinholds a reference to it.
Step 13 of 20 · Concept
Read numbers with a Scanner
| call | gives |
|---|---|
in.nextInt() | the next whole number of the input |
in.hasNextInt() | true if the next item is a whole number, else false |
In this lesson the input is given in advance. In your own programs, type into the output area while the program runs.
Step 14 of 20 · Quiz
What adds up?
The input is 3, 4 and 5, one per line. What does this print?
int a = in.nextInt();
int b = in.nextInt();
System.out.println(a + b);
Step 15 of 20 · Exercise
Your turn: add them up
The input holds some numbers. Complete the method sum: it reads every number and returns their total. The
program must then print:
Sum: 12
You do not know how many numbers there are, so keep reading while there is one left.
while (in.hasNextInt()) { … } repeats while a number is left. Inside, add in.nextInt() to total.
while (in.hasNextInt()) {
total += in.nextInt();
}
Step 16 of 20 · Concept
A method in another class
Bigger programs are split into several classes, one per file. javac compiles them all.
public class Greeter {
static String greet(String name) {
return "Hello, " + name + "!";
}
}
greetisstatic: it belongs to the classGreeter.- From another class, call it with the class's name and a dot:
Greeter.greet("Ada").
Step 17 of 20 · Demo
Classes in two files
Main calls Greeter.greet, which lives in Greeter.java. Run it. In this block you can also add files
(+), rename them (double-click a tab) and delete them (×).
Step 18 of 20 · Check yourself
Check yourself: count and largest
Write the method stats(in) that main calls. It reads every number of the input, then prints how many there
were and the largest. With the input given, the output must be exactly:
Count: 5
Largest: 23
stats prints and gives nothing back. Keep two boxes, the count and the largest so far, and update both per number.
Step 19 of 20 · Challenge · optional
Challenge: the mean
Optional. It earns the lesson's third star.
Complete mean(in): it returns the average of every number of the input. With the input given, the program
must print:
Mean: 4.333333333333333
The average is the total divided by how many numbers there are. Count them while you add them up.
Two ints divide without the fraction, and you would get 4.0. Make the total a double.
double total = 0;
int count = 0;
Step 20 of 20 · Recap
Recap
- A method has a return type, a name and parameters.
returngives a value back and ends it. - Each call gets its own frame on the stack. The frame goes when the method ends.
- A parameter gets a copy of the argument. Changing it does not change the caller's box.
- A
voidmethod gives nothing back. Scannerreads input:hasNextInt()asks,nextInt()reads.
Next: lesson 7 makes objects: things that hold values and have methods of their own.
Review
3 questions from this lesson, in a new order each time. Answer from memory: 2 of 3 right on the first try passes. On a day after you finish the lesson, a pass earns 15 XP.
The review needs JavaScript.
public class Squares {
static int square(int n) {
return n * n;
}
public static void main(String[] args) {
for (int i = 1; i <= 4; i++) {
System.out.println(i + " squared is " + square(i));
}
}
}
public class Max {
// write the method max here
public static void main(String[] args) {
System.out.println("max(3, 8) is " + max(3, 8));
System.out.println("max(10, 2) is " + max(10, 2));
}
}
public class Banner {
static String repeat(String s, int n) {
String result = "";
// add s to result, n times
return result;
}
public static void main(String[] args) {
System.out.println(repeat("=", 12));
System.out.println("| " + repeat("ab", 4) + " |");
System.out.println(repeat("=", 12));
}
}
import java.util.Scanner;
public class Sum {
static int sum(Scanner in) {
int total = 0;
// read every number with a while loop
return total;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Sum: " + sum(in));
}
}
public class Main {
public static void main(String[] args) {
System.out.println(Greeter.greet("Ada"));
System.out.println(Greeter.greet("Grace"));
}
}
import java.util.Scanner;
public class Stats {
// write stats(in): read every number,
// then print the count and the largest
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
stats(in);
}
}
import java.util.Scanner;
public class Mean {
static double mean(Scanner in) {
// return the average of every number
return 0;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Mean: " + mean(in));
}
}