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
exercises
package, create another package (subpackage) calledjava
- Create a Java class called
Exercise1
inside thejava
package. - Insert a
main()
method inside theExcercise1
class. - Inside the
main()
method, insert this statement:System.out.println("Exercise1 executed");
- Compile and run the
main()
method of theExcercises1
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:
- Create a package called
exercises
if you do not already have one. - Create a package called
java
inside theexercises
package if you do not already have one. - Create a class called
Exercise2
in theexercises
package. - Insert a
main()
method. - Inside the
main()
method insert two variables of typeint
. Call the variablesnum1
andnum2
. Set an initial value on both variables. -
Create a third
int
variable, call itresult
and set its value equal to the sum ofnum1
andnum2
. -
Print the value of
result
to 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
exercises
and inside that a subpackage calledjava
. - In the
java
package create a class calledExercise3
. - In the
Exercise3
class insert amain()
method. - In the
main()
method, create an array variable namednumbers
of type int. Set 5 initial values in the array. - Create another variabled named
sum
of typeint
and set its initial value to 0 . - Loop through the
numbers
array and add all elements tosum
. - Insert a
System.out.println()
statement that prints out the value ofsum
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:
- Create a package called
exercises
and inside that a subpackage calledjava
. - In the
java
package create a class calledDataObject
. - Inside the
DataObject
class create apublic
member variable calledcount
of typeint
. - In the
java
package create a class called Exercise3. - In the
Exercise3
class insert amain()
method. - Inside the
main()
method create an array ofDataObject
. - Create 3
DataObject
instances and assign a reference to them to element 0,1 and 2 in the array. - Inside the
main()
method create asum
variable of typeint
. - Loop through the array and add all
count
member variable values of theDataObject
instances to thesum
variable. - Inside the
main()
method, insert aSystem.out.println()
statement that prints out the value of thesum
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:
- Start with all the steps from exercise 4 with two exceptions:
- If you already have a
DataObject
class in packageexercises.java
you can modify that class instead of creating it again. -
The exercise class with the
main()
method in should be calledExercise5
instead ofExcercise4
. You can copy theExercise4
class. Actually, you can also modifyExercise4
but then you lose the solution for exercise 4.
- If you already have a
-
In the
DataObject
class insert a public member variable namedcode
of typeString
-
Expand the number of
DataObject
instances created in the beginning of themain()
method inExercise 5
to 5 instances. -
Two of the
DataObject
instances should have theircode
member variable set tofriday
and the other three instances should have theircode
member variable set tosaturday
. -
Inside the
for
loop, insert anif
-statement so that it only adds thecount
member variable ofDataObjects
where thecode
variable isfriday
to thesum
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:
- Start with the class from exercise 5 called
Exercise5
. - Remove the
sum
variable. You will not use it in this exercise. - To hold the sums for each code, create a
HashMap<String, Integer>
variable namedsumsForCodes
and set it equal tonew HashMap<String, Integer>()
; - Inside the
for
loop, lookup the sum for thecode
of that object in thesumsForCodes
Map
. If no sum is yet found for that code, set the sum to 0. - Add the
count
of the current object to the sum for the code. - Store the new sum for the code in the
sumsForCodes
Map
. - After the
for
loop, create a newfor
loop that loops through all keys of thesumsForCodes
Map
. - 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; HashMapmap = 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 |