Home » Core Java » Java Exercises

About Bhagvan Kommadi

Bhagvan Kommadi
Bhagvan Kommadi is the Founder of Architect Corner & has around 19 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript.

Java Exercises

In this post, we feature an article with Java Exercises. In this tutorial, we will see the Java features in detail through code examples.

1. Overview

We look at the features of Java in this article. Java is used for developing software and executing the code. The exercises help to demonstrate the java language concepts.

 

2. Java Exercises

Java language is an object-oriented language. It is platform-independent and architectural neutral. Java exercises are useful for programmers who are preparing for interviews and certification. They help in understanding the java language concepts from the code samples.

2.1 Prerequisites

Java 8 is required on the linux, windows or mac operating system. Eclipse Oxygen can be used for this example.

2.2 Download

You can download Java 8 from the Oracle web site . Eclipse Oxygen can be downloaded from the eclipse web site.

2.3 Setup

Below is the setup commands required for the Java Environment.

Setup
JAVA_HOME="/desktop/jdk1.8.0_73"
export JAVA_HOME
PATH=$JAVA_HOME/bin:$PATH
export PATH

2.4 IDE

The ‘eclipse-java-oxygen-2-macosx-cocoa-x86_64.tar’ can be downloaded from the eclipse website. The tar file is opened by double click. The tar file is unzipped by using the archive utility. After unzipping, you will find the eclipse icon in the folder. You can move the eclipse icon from the folder to applications by dragging the icon.

2.5 Launching IDE

Eclipse has features related to language support, customization, and extension. You can click on the eclipse icon to launch eclipse. You can select the workspace from the screen which pops up. You can see the eclipse workbench on the screen.

Java Exercises - Eclipse Workspace
Eclipse Workspace

2.6 Hello World Program

Java Hello World program code is presented below. The class has main method which prints out the greetings message. System.out.println is used for printing the messages.Hello World

Java Exercises - HelloWorld
Java HelloWorld

2.7 Data Types

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code ?

Data Types Exercise
class DataTypesExercise {   
   public static void main(String args[]) {      
         int integervariable;      
         System.out.println(integervariable); 
    }   
}
  1. NaN
  2. 0
  3. runtime error
  4. compilation error

The answer is 4. The integer variable is not initialized. When you compile the code, you will get an error message.

2.8 Primitive Data Types

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Primitive Data Types Exercise
class PrimitiveExercise
{
	public static void main(String[] args)
	{
		Double doubleInstance = new Double("4.4");
		int integervar = doubleInstance.intValue();
	

		System.out.println(integervar);

	}
}
  1. 0
  2. 4
  3. 0.4
  4. 3

The answer is 2. The output will be 4. The integer value of the double instance is 4.

2.9 Operators

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Operators Exercise
class OperatorExercise {
    public static void main(String args[])  {
       int negativeInteger = -2;
       System.out.println(negativeInteger >>1);  
       int positiveInteger = 2;
       System.out.println(positiveInteger>>1);  
    }   
}
  1. 1, -1
  2. -1, 1
  3. 0,0
  4. compilation error

The answer is 2. The output will be -1 and 1. Right shift operator takes two numbers as input. It right shifts the bits of the first operand. The next operand is used for shifting the number of places.

2.10 If else

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

If Else Exercise
class IfElseExercise { 
public static void main(String[] args) 
	{ 
		boolean boolvar = false; 
		if (boolvar = false) { 
			System.out.println("FALSE"); 
		} else { 
			System.out.println("TRUE"); 
		} 
	} 
} 

  1. FALSE
  2. TRUE
  3. Compilation Error
  4. Runtime Error

The answer is 2. The output value is TRUE. In the condition of if statement, we are assigning false to boolvar. The assignment returns false. Hence the control goes to the else section. The output is TRUE.

2.11 Loops

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code ?

Loops Exercise
class LoopExercise { 
public static void main(String[] args) 
	{ 
		int firstvar = 0;
                int secondvar = 4;
		do { 
			firstvar++; 
			if (secondvar-- < firstvar++) { 
				break; 
			} 
		} while (firstvar < 3); 
		System.out.println(firstvar + "" + secondvar); 
	} 
} 

  1. 45
  2. 54
  3. 42
  4. 34

Answer is 3. The output is 42. firstvar keeps increasing till it reaches 3. Once it reaches the value 2. The secondvar will be 2 after decrement and break. The firstvar is incremented twice before break. The firstvar value will be 4 and secondvar will be 2.

2.12 Arrays

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code ?

Arrays Exercise
public class ArraysExercise {
    public static void main(String args[]) {
       int arrayInstance[] = {11, 27, 31, 84, 94};
       for(int j=0; j < arrayInstance.length; j++)
       {
             System.out.print( j+ " "+ arrayInstance[j]+ " ");              
       }
    }
}
  1. 1 11 2 27 3 31 4 84 5 94
  2. 0 11 1 27 2 31 3 84 4 94
  3. compilation error
  4. run time error

The Answer is 2. The output will be index starting from 0 and elements starting from 11. j starts from 0.

2.13 Objects

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code ?

Data Types Exercise
class Parallelogram
{
    int length, width;
     
    Parallelogram()
    {
        length = 25;
        width = 46;
    }
     
    public void draw()
    {
        System.out.println ("length = " + length + " width = " + width);
    }
}
 
class ObjectsExercise
{
 
    public static void main(String[] args)
    {
        Parallelogram shape1 = new Parallelogram();
        Parallelogram shape2 = shape1;
 
        shape1.length += 2;
        shape1.width += 2;
 
        System.out.println ("Parallelogram 1 length and width ");
        shape1.draw();
        System.out.println ("Parallelogram 2 length and width");
        shape2.draw();
 
    }
}

a) Parallelogram 1 length and width
length = 27 width = 48
Parallelogram 2 length and width
length = 25 width = 46
b) Parallelogram 1 length and width
length = 27 width = 48
Parallelogram 2 length and width
length = 27 width = 48
c) Runtime Error
d) Compilation Error

The answer is b. The output will be the same for Parallelolgram1 and Parallelolgram2. The length and width will be incremented by 2.

2.14 Inheritance

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Inheritance Exercise
class Shape {
    public void draw() {
       System.out.println("draw method invoked");
    }
}
  
class Rectangle extends Shape {
    public void draw() {
       System.out.println("Rectangle draw method invoked");
    }
}
  
public class InheritanceExercise {
    public static void main(String[] args) {
        Shape shape = new Rectangle();
        shape.draw();
    }
}
  1. draw method invoked
  2. Rectangle draw method invoked
  3. throws a compilation error
  4. throws a runtime error

The answer is 2. The output is “Rectangle draw method invoked”. shape object is created using the derived class Rectangle constructor. When the draw method is invoked, shape object picks the Rectangle draw method.

This is related to polymorphism. A java object can take multiple forms. When a parent class object refers to a child class, the object takes the form of child class. getClass method of the parent class object will return the child class.

Let us look at another exercise. You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Polymorphism Exercise
class Figure {
    public final void draw() {
       System.out.println("draw method invoked");
    }
}
   
class RectangleFigure extends Figure {
    public void draw() {
       System.out.println("Rectangle draw method invoked");
    }
}
   
public class PolymorphismExercise {
    public static void main(String[] args) {
        Figure figure = new RectangleFigure();
        figure.draw();
    }
}
  1. draw method invoked
  2. Rectangle draw method invoked
  3. throws a compilation error
  4. throws a runtime error

The Answer is 3. Compilation error is thrown as Shape has a final method that is overridden in Rectangle. Rectangle is the derived class of Shape.

2.15 Encapsulation

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Encapsulation Exercise
class Square {
int width;
} 
class EncapsulationExercise {
public static void main(String args[]) { 
	Square square; 
	System.out.println(square.width); 
} 

}
  1. 0
  2. Compilation error – width is not accessible
  3. Runtime error
  4. Compilation error – square is not initialized

The answer is 4. Compilation Error is thrown because Square instance is not initialized.

2.16 Keywords

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

KeyWords Exercise
class KeyWordsExercise {
 public static void main(String args[]){
   final int integervar;
   integervar = 34;
   System.out.println(integervar);
 }
}
  1. 0
  2. 34
  3. compilation error
  4. runtime error

The answer is 2. The output will be 34. The final integervar is first time initialized to 34. Hence the output will be 34.

2.17 Classes

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Classes Exercise
abstract class Vehicle
{
    public int speed;
    Vehicle()
    {
        speed = 10;
    }
 
    abstract public void setSpeed();
     
    abstract final public void getSpeed();
 
}
 
class Truck extends Vehicle
{
 
    public void setSpeed(int speed)
    {
        this.speed = speed;
    }
 
    final public void getSpeed()
    {
        System.out.println("Speed = " + speed);
    }
 
    public static void main(String[] args)
    {
        Truck truck = new Truck();
        truck.setSpeed(30);
        truck.getSpeed();
    }
}
  1. Speed = 30
  2. Speed = 0
  3. Compilation error
  4. Runtime error

The answer is 3. A Compilation error occurs because abstract and final are used in the method getSpeed declaration.

2.18 Annotations

Select one of the following which is not a predefined java annotation :

  1.  @Deprecated
  2. @FunctionInterface
  3. @Overriden
  4. @SafeVarags

The answer is 3. @Overriden is not a pre-defined java annotation. @Deprecated, @Override, @SuppressWarnings, @SafeVarags and @FunctionInterface are the predefined java annotations.

2.19 Exceptions

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Exceptions Exercise
class CheckException extends Exception { }
  
class ExceptionExercise {
   public static void main(String args[]) { 
      try {
         throw new CheckException();
      }
      catch(CheckException exception) {
         System.out.println("Check Exception Occured");
      }
      finally {
         System.out.println("finally block executed");
      }
  }
}
  1. Compilation Error
  2. CheckException Occurred
  3. CheckException Occurred
    finally block executed
  4. finally block executed

The answer is 3. The output message will be “Check exception Occured” and “finally block executed”. In the try block, CheckException is thrown. Catch block catches and prints the output. The finally block gets executed to print the output from the finally block.

2.20 Methods

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Methods Exercise
class MethodExercise {
    public static void main(String args[]) {   
             System.out.println(method());
    }   
    static int method()
    {
      int intvar = 4; 
      return intvar;
    }
}
  1. NaN
  2. 4
  3. Runtime error
  4. Compilation error

The answer is 2. The output is 4. The static method is invoked and the intvar value is returned. The output printed is intvar value 4.

2.21 Packages

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Packages Exercise
import static java.lang.System.out;

class PackageExercise
{
public static void main(String args[])
{	 
		out.println("packages");
}
}
  1. Runtime error
  2. Compiler Error
  3. packages
  4. None of the above

The answer is 3. The output is packages. The static import has the package java.lang.System.out out can be used for invoking the method println. The output is printed.

2.22 Constructors

You can look at the code below before answering the multiple-choice. Which of the multiple-choice answers will be the output of the below code?

Constructors Exercise
class Coordinates {
  int xcoord, ycoord;
   
  
  public Coordinates() { 
    xcoord = 5;
    ycoord = 5;
  }
  public int getXCoord() { return xcoord; }
  public int getYCoord() { return ycoord; }
   
  public static void main(String args[]) {
    Coordinates coordinates = new Coordinates();
    System.out.println(coordinates.getYCoord());
  }
}
  1. 0
  2. 5
  3. Compilation error
  4. Runtime error

The answer is 2. The output is 5. The default constructor of the Coordinates class sets the xcoord and ycoord to value 5. The output will be the ycoord value.

3. Download the Source Code

Download
You can download the full source code of this example here: Java Exercises
(+4 rating, 4 votes)
Start the discussion Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

Leave a Reply

avatar

This site uses Akismet to reduce spam. Learn how your comment data is processed.

  Subscribe  
Notify of