Tricky Java Programs Examples

In  Java Objective type questions, lot of tricky questions are asked.  In this post, we will see many java tricky questions and answers with reason.

1) What will be the output of the following code?

class Min{

public static void main(String args [ ]) {

int min = 50;

min(min, 40, 20);

System.out.println(" Minimum of 20, 40 and 50 is " + min); }

static void min(int min, int a, int b) {

if (a > b) min = b;

else min = a; }


A) 10

B) 20

C) 30

D) Program will not compile.

Ans : 50

Why? Java passes objects by reference, and all object variables are references. In the above code , it passes by value.


 2)  What will be  the output of the below java program?

public static void main(String args [ ]) {



static void usingSDF(String dt, String inFormat, String outFormat)


SimpleDateFormat sdfIn=new SimpleDateFormat(inFormat);
SimpleDateFormat sdfOut=new SimpleDateFormat(outFormat);

Date dtTemp=null;
String output="";
try {
dtTemp = sdfIn.parse(dt);

} catch (ParseException e) {
// TODO Auto-generated catch block

System.out.println("output : "+ output);


a) Error

b) 31/08/2014

c) 01/09/2014

d) None

Ans : 01/09/2014. 

Why : SimpleDateFormat parse, automatically changes to next valid date.


3) Predict the output of the below java program

public class Test {

public static void main(String[] args) {

String o1 = new String("kumar");

String o2 = new String("kumar");

if(o1 == o2)



a)  TURE

b) None


d) Error

Ans :  FALSE

Explanation : As o1 and o2 are objects, o1==o2  compares the  memory location of o1 & o2 and not the content.  For comparing content, use o1.equals (o2).

4) What is the output of the below java program?

package com.javaonline;

public class Test5 {

	public static void main(String args[])
		MyClass mc=new MyClass();

class MyClass {

	int key=-1;
		int  key=0;
	public int getNext()
		return key;

a)  -1

b) 0

c) 1

d) Error


Ans:  b

key inside constructor is   a local variable. does not initialize the instance variable.



5) Output the of the below program

package com.javaonline;

public class Test6 {

	public static void main(String args[])
		ExampleClass ex=new ExampleClass();

class ExampleClass {

	int c=-2;
	private ExampleClass(){
	public int increase()
		return c;


a) 0

b) 1

c) -1

d) Error

Ans: d Error.

Compile Error occurs as “The constructor ExampleClass() is not visible” because object can not be created as constructor of ExampleClass is private.
will be updated more…


Leave a Reply