Java Exercises

Jakob Jenkov
Last update: 2015-02-13

This page contains a list of Java exercises you can work with, both to check and deepen your understanding of the Java programming language. The exercises start out very simple, and then gradually involves more and more of the Java language. Each exercise tells a bit about what Java knowledge the exercise requires, and when possible / relevant provide links to where you can learn it.

Since the exercises gradually evolve, you may need to revisit earlier exercises to find links to how some action is done. The links are mostly shown the first time you have to perform some specific action, and may not be repeated in later exercises, even if those exercises requires you to perform the same action.

Java Exercise 1: Run a Java Application

The purpose of this exercise is to verify that you know how to run a basic Java application.

Exercise steps:

  1. Create a Java package called exercises .
  2. Inside the exercises package, create another package (subpackage) called java
  3. Create a Java class called Exercise1 inside the java package.
  4. Insert a main() method inside the Excercise1 class.
  5. Inside the main() method, insert this statement:
    System.out.println("Exercise1 executed");
  6. Compile and run the main() method of the Excercises1 class.

Check that you see the text "Exercise1 executed" in the console output (command line or console in the IDE).

Related resources:

Solution:

package exercises.java;

public class Exercise1 {

    public static void main(String[] args) {
        System.out.println("Exercise1 executed");
    }

}

Java Exercise 2: Add Numbers

The purpose of this exercise is to verify that you know how to create a primitive number variable of type int, long etc. and knows how to add one variable to another.

Exercise steps:

  1. Create a package called exercises if you do not already have one.
  2. Create a package called java inside the exercises package if you do not already have one.
  3. Create a class called Exercise2 in the exercises package.
  4. Insert a main() method.
  5. Inside the main() method insert two variables of type int. Call the variables num1 and num2. Set an initial value on both variables.
  6. Create a third int variable, call it result and set its value equal to the sum of num1 and num2.
  7. Print the value of result to the console output using System.out.println()

Related resources:

Solution:

package exercises.java;

public class Exercise2 {

    public static void main(String[] args) {
        int num1 = 19;
        int num2 = 23;

        int result = num1 + num2;

        System.out.println("result: " + result);
    }
}

Java Exercise 3: Add All Elements in Array

The purpose of this exercise is to verify that you know how to create and iterate arrays in Java.

Exercise steps:

  1. Create a package called exercises and inside that a subpackage called java .
  2. In the java package create a class called Exercise3 .
  3. In the Exercise3 class insert a main() method.
  4. In the main() method, create an array variable named numbers of type int. Set 5 initial values in the array.
  5. Create another variabled named sum of type int and set its initial value to 0 .
  6. Loop through the numbers array and add all elements to sum .
  7. Insert a System.out.println() statement that prints out the value of sum after loop.

Related resources:

Solution:

package exercises.java;

public class Exercise3 {
    public static void main(String[] args) {
        int[] numbers = { 1,2,3,4,5 };
        int   sum     = 0;

        for(int i=0; i < numbers.length; i++) {
            sum = sum + numbers[i];
        }

        System.out.println("Sum: " + sum);
    }
}

Java Exercise 4: Sum Numbers From Array of Data Objects

The purpose of this exercise is to verify that you know how to create classes, how to create instance variables inside the classes, how to create an array of objects and how to iterate that array while referencing the objects in it.

Exercise steps:

  1. Create a package called exercises and inside that a subpackage called java .
  2. In the java package create a class called DataObject .
  3. Inside the DataObject class create a public member variable called count of type int .
  4. In the java package create a class called Exercise3.
  5. In the Exercise3 class insert a main() method.
  6. Inside the main() method create an array of DataObject.
  7. Create 3 DataObject instances and assign a reference to them to element 0,1 and 2 in the array.
  8. Inside the main() method create a sum variable of type int .
  9. Loop through the array and add all count member variable values of the DataObject instances to the sum variable.
  10. Inside the main() method, insert a System.out.println() statement that prints out the value of the sum variable.

Related resources:

Solution:

The DataObject class:

package exercises.java;

public class DataObject {
    public int    count = 0;
}

The Exercise4 class:

package exercises.java;

public class Exercise4 {
    public static void main(String[] args) {
        DataObject[] dataObjects = new DataObject[3];

        DataObject dataObject = new DataObject();
        dataObject.count = 5;
        dataObjects[0] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 7;
        dataObjects[1] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 9;
        dataObjects[2] = dataObject;

        int sum = 0;

        for(int i=0; i < dataObjects.length; i++){
            sum = sum + dataObjects[i].count;
        }

        System.out.println("Sum: " + sum);

    }
}

Java Exercise 5: Sum Numbers From Array of Data Objects Conditionally

The purpose of this exercise is to verify that you can execute blocks of code conditionally, meaning depending of whether some condition is met or not.

Exercise steps:

  1. Start with all the steps from exercise 4 with two exceptions:
    • If you already have a DataObject class in package exercises.java you can modify that class instead of creating it again.
    • The exercise class with the main() method in should be called Exercise5 instead of Excercise4. You can copy the Exercise4 class. Actually, you can also modify Exercise4 but then you lose the solution for exercise 4.
  2. In the DataObject class insert a public member variable named code of type String
  3. Expand the number of DataObject instances created in the beginning of the main() method in Exercise 5 to 5 instances.
  4. Two of the DataObject instances should have their code member variable set to friday and the other three instances should have their code member variable set to saturday.
  5. Inside the for loop, insert an if-statement so that it only adds the count member variable of DataObjects where the code variable is friday to the sum variable.

Related resources:

Solution:

The DataObject class:

package exercises.java;

public class DataObject {
    public String code  = null;
    public int    count = 0;
}

The Exercise5 class:

package exercises.java;

public class Exercise5 {
    public static void main(String[] args) {
        DataObject[] dataObjects = new DataObject[5];

        DataObject dataObject = new DataObject();
        dataObject.count = 5;
        dataObject.code  = "friday";
        dataObjects[0] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 7;
        dataObject.code  = "friday";
        dataObjects[1] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 9;
        dataObject.code  = "saturday";
        dataObjects[2] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 11;
        dataObject.code  = "saturday";
        dataObjects[3] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 13;
        dataObject.code  = "saturday";
        dataObjects[4] = dataObject;

        int sum = 0;

        for(int i=0; i < dataObjects.length; i++){
            if("friday".equals(dataObjects[i].code)){
                sum = sum + dataObjects[i].count;
            }
        }

        System.out.println("Sum: " + sum);

    }
}

Java Exercise 6: Sum Numbers From Array of Data Objects by Code

The purpose of this exercise is to verify that you can use a Map. A Map is a very central type of object in the Java platform. The Map interface is part of the Java Collections API . The exercise will loop through an array of objects sum up all count values for objects which have the same code value.

Exercise steps:

  1. Start with the class from exercise 5 called Exercise5 .
  2. Remove the sum variable. You will not use it in this exercise.
  3. To hold the sums for each code, create a HashMap<String, Integer> variable named sumsForCodes and set it equal to new HashMap<String, Integer>() ;
  4. Inside the for loop, lookup the sum for the code of that object in the sumsForCodes Map. If no sum is yet found for that code, set the sum to 0.
  5. Add the count of the current object to the sum for the code.
  6. Store the new sum for the code in the sumsForCodes Map .
  7. After the for loop, create a new for loop that loops through all keys of the sumsForCodes Map.
  8. Inside this new for loop print out the code and the sum for the code.

Related resources:

Solution:

package exercises.java;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Exercise6 {
    public static void main(String[] args) {
        DataObject[] dataObjects = new DataObject[5];

        DataObject dataObject = new DataObject();
        dataObject.count = 5;
        dataObject.code  = "friday";
        dataObjects[0] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 7;
        dataObject.code  = "friday";
        dataObjects[1] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 9;
        dataObject.code  = "saturday";
        dataObjects[2] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 11;
        dataObject.code  = "saturday";
        dataObjects[3] = dataObject;

        dataObject = new DataObject();
        dataObject.count = 13;
        dataObject.code  = "saturday";
        dataObjects[4] = dataObject;


        HashMap map = new HashMap();

        for(int i=0; i < dataObjects.length; i++){
            //read sum for code
            Integer sumForCode = map.get(dataObjects[i].code);

            //if no sum is in the map for that code yet start with sum of 0
            if(sumForCode == null){
                sumForCode = new Integer(0);
            }

            //add count to sum
            sumForCode = sumForCode.intValue() + dataObjects[i].count;

            //store new sum in map
            map.put(dataObjects[i].code, sumForCode);
        }

        //iterate all keys (codes) in map
        for(String code : map.keySet()){
            //print out the sum for that key (code).
            System.out.println(code + " " + map.get(code));
        }
    }
}

Jakob Jenkov

Featured Videos

Java Generics

Java ForkJoinPool

P2P Networks Introduction



















Close TOC
All Tutorial Trails
All Trails
Table of contents (TOC) for this tutorial trail
Trail TOC
Table of contents (TOC) for this tutorial
Page TOC
Previous tutorial in this tutorial trail
Previous
Next tutorial in this tutorial trail
Next