Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP C C++ C# AWS W3.CSS HOW TO BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS DSA TYPESCRIPT ANGULAR ANGULARJS GIT POSTGRESQL MONGODB ASP AI R GO KOTLIN SWIFT SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE INTRO TO PROGRAMMING INTRO TO HTML & CSS BASH RUST TOOLS

Java Tutorial

Java HOME Java Intro Java Get Started Java Syntax Java Output Java Comments Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Math Java Booleans Java If...Else Java Switch Java While Loop Java For Loop Java Break/Continue Java Arrays

Java Methods

Java Methods Java Method Challenge Java Method Parameters Java Method Overloading Java Scope Java Recursion

Java Classes

Java OOP Java Classes/Objects Java Class Attributes Java Class Methods Java Class Challenge Java Constructors Java this Keyword Java Modifiers Java Encapsulation Java Packages / API Java Inheritance Java Polymorphism Java super Keyword Java Inner Classes Java Abstraction Java Interface Java Anonymous Java OOP Visuals Java Enum Java User Input Java Date

Java Errors

Java Errors Java Debugging Java Exceptions Java Multiple Exceptions Java try-with-resources

Java Problem Solving

Java Problem Solving Java Build the Logic Java Test Cases

Java File Handling

Java Files Java Create Files Java Write Files Java Read Files Java Delete Files

Java I/O Streams

Java I/O Streams Java FileInputStream Java FileOutputStream Java BufferedReader Java BufferedWriter

Java Data Structures

Java Data Structures Java Collections Java List Java ArrayList Java LinkedList Java List Sorting Java Set Java HashSet Java TreeSet Java LinkedHashSet Java Map Java HashMap Java TreeMap Java LinkedHashMap Java Iterator Java Algorithms

Java Advanced

Java Wrapper Classes Java Generics Java Annotations Java RegEx Java Threads Java Lambda Java Optional Java Advanced Sorting

Java Projects

Java Projects

Java Cert

Java Certificate

Java How To's

Java How Tos

Java Examples

Java Examples Java Videos Java Compiler Java Exercises Java Quiz Java Code Challenges Java Practice Problems Java Server Java Syllabus Java Study Plan Java Interview Q&A

Java Reference

Java Reference Java Keywords ArrayList Methods Arrays Methods BufferedReader BufferedWriter Character Methods Collections Methods Comparator Methods Date and Time Enum Methods Errors & Exceptions File Methods FileInputStream FileOutputStream FileReader FileWriter HashMap Methods HashSet Methods Integer Methods Iterator Methods LinkedHashMap Methods LinkedHashSet Methods LinkedList Methods Math Methods Optional Methods Output Methods Random Methods RegEx Methods Scanner Methods String Methods StringBuilder Methods System Methods Thread Methods TreeMap Methods TreeSet Methods


Java Test Cases


Share

What is a Test Case?

In the Problem Solving chapter, you tested a program by running it with different temperatures, and checking the output. Each of these checks is called a test case.

A test case has two parts: an input, and the expected output (the output that a correct program prints).

Here are the test cases for the practice problem Even or Odd. Read a whole number, and print Even if it can be divided by 2, or Odd if it cannot:

Input Expected output
7 Odd
4 Even
0 Even
13 Odd

Check Even or Odd

How do you know if a number is even? Use the modulus operator % (see Arithmetic Operators). It gives the remainder of a division: what is left over.

  • 7 % 2 is 1: 7 divided by 2 is 3, and 1 is left over.
  • 4 % 2 is 0: 4 divided by 2 is 2, and nothing is left over.

So if n % 2 is 0, the number is even. If not, it is odd:

Example

public class Main {
  public static void main(String[] args) {
    int n = 7;
    if (n % 2 == 0) {
      System.out.println("Even");
    } else {
      System.out.println("Odd");
    }
  }
}

Result:

Odd
Try it Yourself »

Click "Try it Yourself", change n to 4, and run the code again. Now it prints Even.


The Output Must Match Exactly

When you submit a practice problem, your program runs once for each test case. Each time, it gets the input, and its output is compared with the expected output.

The output must be exactly the same, letter by letter. If the input is 7, only the first output passes:

Your output Result
Odd Passed
odd Failed: a lowercase o
Odd! Failed: an extra exclamation mark
The number is Odd Failed: extra words

So print exactly what the problem asks for, and nothing more.


Edge Cases

When you test a program, you should not only test normal values, like 5 or 42. You should also test unusual values, because many bugs hide there.

These unusual values are called edge cases.

Here are edge cases to try for common kinds of input:

Input Edge cases to try
A number 0, 1, a negative number, a very large number
An array No values at all, only one value, all values the same
A string An empty string (""), one letter, uppercase letters, spaces
A range, like 1 to 100 The first and last value (1 and 100), and the values just outside (0 and 101)

In Even or Odd, the input is a number. So test 0, and a negative number like -7:

  • 0: is 0 even? Yes. 0 divided by 2 is 0, and nothing is left over, so 0 % 2 is 0.
  • -7: it is odd, but in Java, -7 % 2 is -1, not 1. So if your code checks n % 2 == 1, it says that -7 is even! You will see this in the tests below.

Run the Tests

Here are three solutions to Even or Odd. Choose a solution, and click "Run tests" to check it with five test cases, just like the practice editor does:

Code


Test cases

Explanation



Test Your Own Code

You can also test your code yourself, before you submit it. Put the solution in a method, and write a small test() method. It compares the output with the expected output, and prints PASS or FAIL:

Example

public class Main {
  static String evenOrOdd(int n) {
    if (n % 2 == 0) {
      return "Even";
    } else {
      return "Odd";
    }
  }

  static void test(int input, String expected) {
    String output = evenOrOdd(input);
    if (output.equals(expected)) {
      System.out.println("PASS: " + input);
    } else {
      System.out.println("FAIL: " + input + " (expected " + expected + ", got " + output + ")");
    }
  }

  public static void main(String[] args) {
    test(7, "Odd");
    test(4, "Even");
    test(0, "Even");
    test(13, "Odd");
    test(-7, "Odd");
  }
}

Result:

PASS: 7
PASS: 4
PASS: 0
PASS: 13
PASS: -7
Try it Yourself »

Strings are compared with equals(), not with == (see Strings). Try to change "Odd" to "odd" in evenOrOdd(), and run the tests again. The FAIL lines tell you exactly which test cases broke.


Your Turn

Now solve Even or Odd in our practice editor. The starter code already reads the number from input. Remember the edge cases, and print exactly Even or Odd!


Summary

  • A test case is an input, together with the expected output.
  • Practice problems run your program once for each test case. Your output must be exactly the same as the expected output.
  • Edge cases, like 0 and negative numbers, are where bugs often hide.
  • A test() method lets you check your own code with many test cases at once.

You now know how to understand a problem, build the logic, and test your code. Use your new skills on our Java Practice Problems!




Free account

Track your progress

XP earned 0 Day streak 0 Spaces 0 League —

New

Learn in Adventure Mode W3Schools Adventure App

Coding fundamentals as bite-sized lessons and challenges.

×

Contact Sales

If you want to use W3Schools services as an educational institution, team or enterprise, send us an e-mail:
sales@w3schools.com

Report Error

If you want to report an error, or if you want to make a suggestion, send us an e-mail:
help@w3schools.com

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookies and privacy policy.

Copyright 1999-2026 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.