Java - Coding - Interview Questions and Answers

Q1. What will this code print ?

String a = new String ("TEST");
String b = new String ("TEST");

if(a == b) {
System.out.println ("TRUE");
} else {
System.out.println ("FALSE");
}show Answer

Ans. FALSE.

== operator compares object references, a and b are references to two different objects, hence the FALSE. .equals method is used to compare string object content.

Q2. Write a method to check if input String is Palindrome?


show Answer

Ans. private static boolean isPalindrome(String str) {
if (str == null)
return false;
StringBuilder strBuilder = new StringBuilder(str);
strBuilder.reverse();
return strBuilder.toString().equals(str);
}

Q3. Write a method that will remove given character from the String?show Answer

Ans. private static String removeChar(String str, char c) {
if (str == null)
return null;
return str.replaceAll(Character.toString(c), "");
}


Q4. Will the following program display "Buggy Bread" ?

class Test{
static void display(){
System.out.println("Buggy Bread");
}
}

class Demo{
public static void main(String... args){
Test t = null;
t.display();
}
}show Answer

Ans. Yes. static method is not accessed by the instance of class. Either you call it by the class name or the reference.

Q5. Write a program to reverse a string iteratively and recursively ?show Answer

Ans. Using String method -

new StringBuffer(str).reverse().toString();

Iterative -

public static String getReverseString(String str){
StringBuffer strBuffer = new StringBuffer(str.length);
for(int counter=str.length -1 ; counter>=0;counter--){
strBuffer.append(str.charAt(counter));
}
return strBuffer;
}

Recursive -

public static String getReverseString(String str){
if(str.length <= 1){
return str;
}
return (getReverseString(str.subString(1)) + str.charAt(0);
}

Q6. Write a method to convert binary to a number ?show Answer

Ans. convert(int binaryInt) {
int sumValue=0;
int multiple = 1;
while(binaryInt > 0){
binaryDigit = binaryInt%10;
binaryInt = binaryInt /10;
sumValue = sumValue + (binaryDigit * multiple);
multiple = multiple * 2;
}
return sumValue;
}

Q7. What will the following code print ?

String s1 = "Buggy Bread";
String s2 = "Buggy Bread";
if(s1 == s2)
System.out.println("equal 1");
String n1 = new String("Buggy Bread");
String n2 = new String("Buggy Bread");
if(n1 == n2)
System.out.println("equal 2"); show Answer

Ans. equal 1

Q8. How to find whether a given integer is odd or even without use of modules operator in java?show Answer

Ans. public static void main(String ar[])
{
int n=5;
if((n/2)*2==n)
{
System.out.println("Even Number ");
}
else
{
System.out.println("Odd Number ");
}
}
}

Q9. What will be the output of following code ?

public static void main(String[] args)
{
int x = 10;
int y;
if (x < 100) y = x / 0;
if (x >= 100) y = x * 0;
System.out.println("The value of y is: " + y);
}show Answer

Ans. The code will not compile raising an error that the local variable y might not have been initialized. Unlike member variables, local variables are not automatically initialized to the default values for their declared type.

Q10. What will be the output of following Code ?

class BuggyBread {
public static void main(String[] args)
{
String s2 = "I am unique!";
String s5 = "I am unique!";

System.out.println(s2 == s5);
}
}show Answer

Ans. true, due to String Pool, both will point to a same String object.

Q11. What will be the output of following code ?

class BuggyBread2 {

private static int counter = 0;

void BuggyBread2() {
counter = 5;
}

BuggyBread2(int x){
counter = x;
}

public static void main(String[] args) {
BuggyBread2 bg = new BuggyBread2();
System.out.println(counter);
}
}show Answer

Ans. Compile time error as it won't find the constructor matching BuggyBread2(). Compiler won't provide default no argument constructor as programmer has already defined one constructor. Compiler will treat user defined BuggyBread2() as a method, as return type ( void ) has been specified for that.

Q12. What will be the output of following code ?

class BuggyBread1 {
public String method() {
return "Base Class - BuggyBread1";
}
}

class BuggyBread2 extends BuggyBread1{

private static int counter = 0;

public String method(int x) {
return "Derived Class - BuggyBread2";
}

public static void main(String[] args) {
BuggyBread1 bg = new BuggyBread2();
System.out.println(bg.method());
}
}
show Answer

Ans. Base Class - BuggyBread1

Though Base Class handler is having the object of Derived Class but its not overriding as now with a definition having an argument ,derived class will have both method () and method (int) and hence its overloading.

Q13. what will be the output of this code ?

public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");

test(s1);

System.out.println(s1);

}

private static void test(StringBuffer s){
s.append("Bread");
}show Answer

Ans. BuggyBread

Q14. what will be the output of this code ?

public static void main(String[] args)
{
String s1=new String("Buggy");

test(s1);

System.out.println(s1);

}

private static void test(StringBuffer s){
s.append("Bread");
}show Answer

Ans. Buggy

Q15. what will be the output of this code ?

public static void main(String[] args)
{
StringBuffer s1=new StringBuffer("Buggy");

test(s1);

System.out.println(s1);

}

private static void test(StringBuffer s){
s=new StringBuffer("Bread");
}show Answer

Ans. Buggy

Q16. what will be the output ?

class Animal {
public void eat() throws Exception {
}
}

class Dog2 extends Animal {
public void eat(){}
public static void main(){
Animal an = new Dog2();
an.eat();
}
}
show Answer

Ans. Compile Time Error: Unhandled exception type Exception

Q17. What will the following code print when executed on Windows ?

public static void main(String[] args){
String parent = null;
File file = new File("/file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. \file.txt
C:\file.txt
C:\file.txt

Q18. What will be the output of following code ?

public static void main(String[] args){
String name = null;
File file = new File("/folder", name);
System.out.print(file.exists());
}show Answer

Ans. NullPointerException at line:

"File file = new File("/folder", name);"

Q19. What will be the output of following code ?

public static void main(String[] args){
String parent = null;
File file = new File(parent, "myfile.txt");
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. It will create the file myfile.txt in the current directory.

Q20. What will be the output of following code ?

public static void main(String[] args){
String child = null;
File file = new File("/folder", child);
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. NullPointerException at line:

File file = new File("/folder", child);

Q21. What will be the output of following code, assuming that currently we are in c:\Project ?

public static void main(String[] args){
String child = null;
File file = new File("../file.txt");
System.out.println(file.getPath());
System.out.println(file.getAbsolutePath());
try {
System.out.println(file.getCanonicalPath());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}show Answer

Ans. ..\file.txt
C:\Workspace\Project\..\file.txt
C:\Workspace\file.txt

Q22. Which of the following code is correct ?

a.


FileWriter fileWriter = new FileWriter("../file.txt");
File file = new File(fileWriter );
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);

b.

BufferedWriter bufferedOutputWriter = new BufferedWriter("../file.txt");
File file = new File(bufferedOutputWriter );
FileWriter fileWriter = new FileWriter(file);


c.

File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);

d.

File file = new File("../file.txt");
BufferedWriter bufferedOutputWriter = new BufferedWriter(file);
FileWriter fileWriter = new FileWriter(bufferedOutputWriter );show Answer

Ans. c.

File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
BufferedWriter bufferedOutputWriter = new BufferedWriter(fileWriter);

Q23. Which exception should be handled in the following code ?

File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);show Answer

Ans. IOException

Q24. Which exceptions should be handled with the following code ?

FileOutputStream fileOutputStream = new FileOutputStream(new File("newFile.txt"));show Answer

Ans. FileNotFoundException

Q25. Will this code compile fine ?

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));show Answer

Ans. Yes.

Q26. What is the problem with this code ?

class BuggyBread1 {

private BuggyBread2 buggybread2;

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}show Answer

Ans. Though we are trying to serialize BuggyBread1 object but we haven't declared the class to implement Serializable.

This will throw java.io.NotSerializableException upon execution.

Q27. Will this code run fine if BuggyBread2 doesn't implement Serializable interface ?

class BuggyBread1 implements Serializable{

private BuggyBread2 buggybread2 = new BuggyBread2();

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}show Answer

Ans. No, It will throw java.io.NotSerializableException.

Q28. Will this code work fine if BuggyBread2 doesn't implement Serializable ?

class BuggyBread1 extends BuggyBread2 implements Serializable{

private int x = 5;

public static void main(String[] args){
try {
BuggyBread1 buggybread1 = new BuggyBread1();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
objectOutputStream.writeObject(buggybread1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}show Answer

Ans. Yes.

Q29. What will the following code print ?

java.util.Calendar c = java.util.Calendar.getInstance();
c.add(Calendar.MONTH, 5);
System.out.println(c.getTime());show Answer

Ans. Date and Time after 5 months from now.

Q30. What's wrong with this code ?

public static void main(String[] args) {
String regex = "(\\w+)*";
String s = "Java is a programming language.";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(s);
while (matcher.next()) {
System.out.println("The e-mail id is: " + matcher.group());
}
}show Answer

Ans. matcher.find() should have been used instead of matcher.next() within while.

Q31. Write a program to see if the number is prefect number or not ?show Answer

Ans. http://www.c4learn.com/c-programs/program-to-check-whether-number-is.html

Q32. What will be the output of this code ?

Set mySet = new HashSet();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
System.out.println(s);
}
show Answer

Ans. It will print 4567,5678 and 6789 but Order cannot be predicted.

Q33. What will be the output of this code ?

Set mySet = new TreeSet();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
for(String s: mySet){
System.out.println(s);
}show Answer

Ans. 4567
5678
6789

Q34. What will be the output of this code ?

Set mySet = new HashSet();
mySet.add("4567");
mySet.add("5678");
mySet.add("6789");
System.out.println(s.get(0));
show Answer

Ans. This will give compile time error as we cannot retrieve the element from a specified index using Set. Set doesn't maintain elements in any order.

Q35. public enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, SATURDAY
}

public class Test {
Set mySet = new HashSet();
mySet.add(Day.MONDAY);
mySet.add(Day.SUNDAY);
mySet.add(Day.SATURDAY);

for(Day d: mySet){
System.out.println(d);
}
}show Answer

Ans. SUNDAY
MONDAY
SATURDAY

Q36. What will be the output of the following code ?

enum Day {

MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}

public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new HashSet();
mySet.add(Day.SATURDAY);
mySet.add(Day.WEDNESDAY);
mySet.add(Day.FRIDAY);
mySet.add(Day.WEDNESDAY);
for(Day d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. FRIDAY, SATURDAY and WEDNESDAY will be printed but the order cannot be determined.

Only one FRIDAY will be printed as Set doesn't allow duplicates.

Order cannot be determined as HashSet doesn't maintain elements in any particular order.


Q37. enum Day {

MONDAY,TUESDAY,WEDNESDAY,THURSDAY,FRIDAY,SATURDAY,SUNDAY
}


public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new TreeSet();
mySet.add(Day.SATURDAY);
mySet.add(Day.WEDNESDAY);
mySet.add(Day.FRIDAY);
mySet.add(Day.WEDNESDAY);
for(Day d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. WEDNESDAY
FRIDAY
SATURDAY


Only one FRIDAY will be printed as Set doesn't allow duplicates.

Elements will be printed in the order in which constants are declared in the Enum. TreeSet maintains the elements in the ascending order which is identified by the defined compareTo method. compareTo method in Enum has been defined such that the constant declared later are greater than the constants declared prior.

Q38. public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new TreeSet();
mySet.add("1");
mySet.add("2");
mySet.add("111");
for(String d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. 1
111
2

TreeSet maintains the elements in the ascending order which is identified by the compareTo method. compareTo method in String has been defined such that it results in the natural alphabetic Order. Here the elements in the TreeSet are of String and not of Integer. In String Natural Order, 111 comes before 2 as ascii of 1st character first determines the order.


Q39. public class BuggyBread1{

public static void main (String args[]) {
Set mySet = new TreeSet();
mySet.add(1);
mySet.add(2);
mySet.add(111);
for(Integer d: mySet){
System.out.println(d);
}
}
}show Answer

Ans. 1
2
111

TreeSet maintains the elements in the ascending order which is identified by the compareTo method. compareTo method in Integer has been defined such that it results in the natural numerical Order.