Move from “this program runs” to “this method keeps a promise.” A contract describes accepted inputs, a result, and effects on existing objects. Intermediate Java starts with tools you already used in Java beginner: methods, loops, lists, constructors, private fields, exceptions and small checks. No maps, interfaces or lambdas are assumed yet.
If the first example feels unfamiliar, revisit methods, lists and tests. Use the beginner navigation if you need another topic. You are ready when you can explain a loop and write a check that fails on purpose. This week introduces every new language feature before the project relies on it.
Bring your beginner skills with you
Before starting, try three small tasks without opening a solution: write a loop that totals an array; construct two independent objects with private fields; and write a check that fails when an invalid value is accepted. If one feels uncertain, revisit array loops, encapsulation, or exceptions. You do not need JavaScript, TypeScript, frameworks or a local Java installation.
The daily times are guides, not deadlines. Split a day into two sittings if its checkpoint still needs work. Try the exercise before opening its hints, then change one input and explain the result. A printed success message only proves the checks that actually ran.
Unless a lesson explicitly handles missing inputs, supply nonnull arrays and collections. An empty array such as new int[0] is a real array with zero entries; null means no array at all. The methods on this page accept empty arrays, but do not promise to handle null. Small totals are used here; handling integer overflow is outside these exercises.
Work through the example
totalPositive returns the sum of positive durations. Zero and negative entries do not contribute. It reads the supplied array without changing it. The accumulator starts at zero, so an empty array has a defined answer. These are decisions about behavior, not details of indentation.
check throws AssertionError when an expectation is false. Unlike Java's assert keyword, it does not need a special command-line flag. Name a check after the behavior it guards. A program that prints a plausible number is weaker evidence than one that checks several deliberately chosen cases.
Before Run, write the output and identify the exact line responsible for each result. Each editor is a separate program; names and edits in one box do not carry into the next.
public class Main {
public static void main(String[] args) {
int[] minutes = {25, -5, 10};
check("mixed durations", totalPositive(minutes) == 35);
check("empty input", totalPositive(new int[0]) == 0);
check("input unchanged", minutes[1] == -5);
System.out.println("Contract checks passed");
}
static int totalPositive(int[] values) {
int total = 0;
for (int value : values) {
if (value > 0) {
total += value;
}
}
return total;
}
static void check(String name, boolean condition) {
if (!condition) {
throw new AssertionError(name);
}
}
}Check your prediction
Contract checks passedCompare the behavior
Changing a contract changes the tests you need. Here the method counts entries meeting a threshold rather than summing durations. Equality belongs in >=: a value at the boundary must count. The empty input and “nothing matches” cases both return zero, but exercise different paths. Do not silently switch to > because the first example happens to pass.
public class Main {
public static void main(String[] args) {
System.out.println(countAtLeast(new int[] {10, 25, 40}, 25));
System.out.println(countAtLeast(new int[] {10}, 25));
}
static int countAtLeast(int[] values, int minimum) {
int count = 0;
for (int value : values) {
if (value >= minimum) {
count++;
}
}
return count;
}
}Check your prediction
2
0A contract is more than a sample answer
Beginner checks often started with one small calculation. Here add two questions: what must be true before the call, and what must remain true after it? For totalPositive, values is a real array, each int can be read, the returned total includes only positive entries, and the input entries are unchanged. Empty input is allowed; a missing array is outside this contract.
Make a three-column case table: input, expected result and reason. Mixed signs checks selection, empty input checks initialization, and a saved negative entry checks the no-mutation promise. These are separate behaviors, even if one implementation satisfies all of them with a short loop.
A method that silently changes negative inputs to zero could return the right total while violating the ownership promise. This is why a correct number alone is insufficient. Read the whole contract before choosing what to check, and keep the actual expected results independent of the method you are testing.
Practice independently
Methods & Contracts: practice
Implement countPositive without changing its array. Check [0, 25, -1, 10] gives 2 and an empty array gives 0. Include a check that an input entry is unchanged. Print only Checks passed after all checks pass.
Spend a few minutes on your own first. Compile after one small change, read the first error, and check the result against the requirements rather than matching the solution's layout.
public class Main {
public static void main(String[] args) {
// Add calls that verify the contract.
System.out.println(countPositive(new int[] {0, 25, -1, 10}));
}
static int countPositive(int[] values) {
// Count values greater than zero.
return 0;
}
}Hint 1: the idea
A count changes by one for a matching entry; it does not add the entry itself.
Hint 2: a first step
Start with a zero accumulator and an enhanced for loop. Decide which comparison excludes zero.
Show one solution
One possible implementation follows. Compare its decisions with yours: which values can change, what inputs are accepted, and what would expose a mistake?
public class Main {
public static void main(String[] args) {
int[] values = {0, 25, -1, 10};
check(countPositive(values) == 2);
check(countPositive(new int[0]) == 0);
check(values[2] == -1);
System.out.println("Checks passed");
}
static int countPositive(int[] values) {
int count = 0;
for (int value : values) {
if (value > 0) {
count++;
}
}
return count;
}
static void check(boolean condition) {
if (!condition) {
throw new AssertionError("positive-count contract");
}
}
}Expected output:
Checks passedChange it and test again
Change > 0 to >= 0 temporarily. Which check fails? Restore it. Add an all-negative case and an all-positive case. A deliberate broken version is a mutation: if your checks still pass, they do not yet prove the disputed behavior.
Explain before moving on
Write the contract in three sentences: what the method accepts, what it returns, and what it leaves unchanged. Why does checking an empty array matter even when the loop looks obvious? Keep this habit for every method you write this week.
Completion is saved in this browser only. It does not measure mastery.