Java Exercises
Jakob Jenkov |
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:
- Create a Java package called
exercises. - Inside the
exercisespackage, create another package (subpackage) calledjava - Create a Java class called
Exercise1inside thejavapackage. - Insert a
main()method inside theExcercise1class. - Inside the
main()method, insert this statement:System.out.println("Exercise1 executed"); - Compile and run the
main()method of theExcercises1class.
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:
- Create a package called
exercisesif you do not already have one. - Create a package called
javainside theexercisespackage if you do not already have one. - Create a class called
Exercise2in theexercisespackage. - Insert a
main()method. - Inside the
main()method insert two variables of typeint. Call the variablesnum1andnum2. Set an initial value on both variables. -
Create a third
intvariable, call itresultand set its value equal to the sum ofnum1andnum2. -
Print the value of
resultto the console output usingSystem.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:
- Create a package called
exercisesand inside that a subpackage calledjava. - In the
javapackage create a class calledExercise3. - In the
Exercise3class insert amain()method. - In the
main()method, create an array variable namednumbersof type int. Set 5 initial values in the array. - Create another variabled named
sumof typeintand set its initial value to 0 . - Loop through the
numbersarray and add all elements tosum. - Insert a
System.out.println()statement that prints out the value ofsumafter 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:
- Create a package called
exercisesand inside that a subpackage calledjava. - In the
javapackage create a class calledDataObject. - Inside the
DataObjectclass create apublicmember variable calledcountof typeint. - In the
javapackage create a class called Exercise3. - In the
Exercise3class insert amain()method. - Inside the
main()method create an array ofDataObject. - Create 3
DataObjectinstances and assign a reference to them to element 0,1 and 2 in the array. - Inside the
main()method create asumvariable of typeint. - Loop through the array and add all
countmember variable values of theDataObjectinstances to thesumvariable. - Inside the
main()method, insert aSystem.out.println()statement that prints out the value of thesumvariable.
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:
- Start with all the steps from exercise 4 with two exceptions:
- If you already have a
DataObjectclass in packageexercises.javayou can modify that class instead of creating it again. -
The exercise class with the
main()method in should be calledExercise5instead ofExcercise4. You can copy theExercise4class. Actually, you can also modifyExercise4but then you lose the solution for exercise 4.
- If you already have a
-
In the
DataObjectclass insert a public member variable namedcodeof typeString -
Expand the number of
DataObjectinstances created in the beginning of themain()method inExercise 5to 5 instances. -
Two of the
DataObjectinstances should have theircodemember variable set tofridayand the other three instances should have theircodemember variable set tosaturday. -
Inside the
forloop, insert anif-statement so that it only adds thecountmember variable ofDataObjectswhere thecodevariable isfridayto thesumvariable.
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:
- Start with the class from exercise 5 called
Exercise5. - Remove the
sumvariable. You will not use it in this exercise. - To hold the sums for each code, create a
HashMap<String, Integer>variable namedsumsForCodesand set it equal tonew HashMap<String, Integer>(); - Inside the
forloop, lookup the sum for thecodeof that object in thesumsForCodesMap. If no sum is yet found for that code, set the sum to 0. - Add the
countof the current object to the sum for the code. - Store the new sum for the code in the
sumsForCodesMap. - After the
forloop, create a newforloop that loops through all keys of thesumsForCodesMap. - Inside this new
forloop 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));
}
}
}
| Tweet | |
Jakob Jenkov | |











