Interview Questions and Answers for 'Code' | Search Interview Question - javasearch.buggybread.com
Javasearch.buggybread.com

Search Interview Questions


 More than 3000 questions in repository.
 There are more than 900 unanswered questions.
Click here and help us by providing the answer.
 Have a video suggestion.
Click Correct / Improve and please let us know.
Label / Company      Label / Company / Text

   



Interview Questions and Answers - Order By Newest

   next 30
 Q31. 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 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);
}
}
}
Core Java
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   coding   enum   set   treeset   advanced

Try 3 Question(s) Test


 Q32. Implement the following method ?

int findMax(int[] items)
Core Java
Ans. int findMax(int[] items){
   int maxNumber = 0;
   for(int x:items){
      if(x > maxNumber){
         maxNumber = x;
      }
   }
      
   return maxNumber;
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     coding  code  find max number in an array     Asked in 1 Companies


 Q33. Write a program to print all even numbers first and then all odd numbers till 100. For example the output should be
2
4
6
8
...... 100
and then
1
3
5
7
...... 99

using only 1 for loop ? Is it possible with just one loop ?
Core Java
Ans. Yes , It can be done using single for loop

public class BuggyBread{
public static void main (String args[]) {
   int x = 50;
   for(int i=1;i <= 100;i++){
      if(i<=50){
         System.out.println(i*2);
      } else {
         System.out.println(i-x);
         x = x - 1;
      }
   }
}
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     code  coding     Asked in 1 Companies


 Q34. Given two files with list of words, write a program to show the common words in both filesCore Java
Ans. import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.io.*;
public class Common {
public static void main(String ar[])throws Exception
   {
      File f=new File("a.txt");
File f1=new File("x.java");
      System.out.println(f.exists());
FileInputStream fin = new FileInputStream(f);
      FileInputStream fin1 = new FileInputStream(f1);

      byte b[]=new byte[10000];
byte b1[]=new byte[10000];
fin.read(b);
fin1.read(b1);
String s1 = new String(b);
String s2 =new String(b1);

String words1[] = s1.trim().split(" ");
String words2[] = s2.trim().split(" ");
Listlist1 = new ArrayList<>(Arrays.asList(words1));
Listlist2 = new ArrayList<>(Arrays.asList(words2));
list1.retainAll(list2);
System.out.println(list1);
}
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     file handling  file io  code  coding     Asked in 1 Companies


 Q35. Write an algorithm / Java Program to show duplicates in an array of n elements?Algorithm
Ans. int duplicateArray[] = { 1, 2, 2, 3, 4, 5, 6, 8, 9}
Set unique = new HashSet();
for (int i = 0; i < duplicateArray.length; i) {
if (unique.contains(duplicateArray[i])) {
System.out.println(duplicateArray[i]);
} else {
unique.add(duplicateArray[i]);
}
}

Complexity O(n) = nHashSet contains and add has O(n) = 1

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     coding  code     Asked in 2 Companies


 Q36. Find different combination of given String and trace the output

Core Java
Ans. private void permutation(String prefix, String sufix)
{
int ln = sufix.length();
if(ln == 0) {
System.out.println(prefix);
} else {
IntStream.range(0, ln).forEach(i->permutation(prefix sufix.charAt(i), sufix.substring(0,i) sufix.substring(i 1, ln)));
}
}

call:permutation("", "abcdef");

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     String  code  coding     Asked in 1 Companies


 Q37. Write code to create a folder if it doesn't exist.Core Java
Ans. File folder = new File(path);
      
if(!folder.exists()){
try {
folder.mkdir();
            
} catch (Exception e) {}
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     code  coding  file handling      basic


 Q38. What is meant by "unreachable code" ? Can you write a code segment explaining this ?Core Java
Ans. Unreachable code is a code segment that can never be executed in any case. For example -

int x = 5;
return;
System.out.println(x);

In this code , 2nd line will return the control out of the method and hence 3rd line will never get executed and hence is unreachable code. This will be caught at compile time only.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     unreachable code


 Q39. Which memory segment loads the java code ?Core Java
Ans. Code segment.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     memory   java   memory management   code segment  code segment memory      expert        rare


 Q40. What is unicode ?Core Java
Ans. A way of encoding characters as binary numbers. The Unicode character set includes
characters used in many languages, not just English. Unicode is the character set that is
used internally by Java.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   character encoding   unicode   architecture


 Q41. Should good code be self-documenting, or is it the responsibility of the developer to document it?Process
Ans. Open ended Questions.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   open questions   code review   documentation   clean code


 Q42. Why is Java considered Portable Language ?Core Java
Ans. Java is a portable-language because without any modification we can use Java byte-code in any platform(which supports Java). So this byte-code is portable and we can use in any other major platforms.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   bytecode   jvm   compiler   portable   features of java   basic interview question


 Q43. Write a program to print the index of the first non repeated character in a java stringCore Java
Ans. public class BuggyBread1{
public static void main (String args[]) {
   String str = "hheello world";
   char[] charArray = str.toCharArray();
   char selectedChar = 'a';
   for(char char1: charArray){
      if(!str.contains(Character.toString(char1).concat(Character.toString(char1)))){
         selectedChar = char1;
         break;
      }
   }
   System.out.println(str.indexOf(Character.toString(selectedChar)));
}
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     string  code  coding     Asked in 9 Companies


 Q44. public class a {
   public static void main(String args[]){
      final String s1=""job"";
      final String s2=""seeker"";
      String s3=s1.concat(s2);
      String s4=""jobseeker"";
      System.out.println(s3==s4); // Output 1
      System.out.println(s3.hashCode()==s4.hashCode()); Output 2
   }
}

What will be the Output 1 and Output 2 ?
Core Java
Ans. S3 and S4 are pointing to different memory location and hence Output 1 will be false.

Hash code is generated to be used as hash key in some of the collections in Java and is calculated using string characters and its length. As they both are same string literals, and hence their hashcode is same.Output 2 will be true.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   hashcode   hash code   string comparison   string pool

Try 1 Question(s) Test


  Q45. What is the use of HashCode in objects ?Core Java
Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string   hashcode   hash code   string comparison  hashtable     Asked in 17 Companies      basic        frequent


 Q46. Write a Program to add 1-100, 101-200, 201-300 in different threads and then sum the numbers ?Core Java
Ans. public class TotalUsingThreads extends Thread{
   
   private static List<TotalUsingThreads> collector = new ArrayList<TotalUsingThreads>();
   
   private int startFrom = 0;
   
   private Integer threadTotal = null;
   
   Test(int startFrom){
      this.startFrom = startFrom;
   }
   
   
   public static void main(String[] args) throws InterruptedException{
      int totalSum = 0;
      
      // Create all the threads and set the count starting point for all of them
      for(int count=0;count<10;count++){
         TotalUsingThreads newThread = new TotalUsingThreads(count*100);
         newThread.start();
         collector.add(newThread);
      }
      
      boolean allCollected = false;
      
      
      // Make sure that all thread totals are collected and all threads have completed their tasks
      while(!allCollected){
         for(int count=0;count<10;count++){
            if(collector.get(count).threadTotal == null){
               Thread.sleep(100);
               break;
            }
         }
         allCollected = true;
      }
      
      // sum totals of all threads
      for(int count=0;count<10;count++){
         totalSum += collector.get(count).threadTotal;
      }
      
      System.out.println(totalSum);
      
      
   }
   
   public void run(){
      threadTotal = 0;
      for(int count=startFrom;count<startFrom+100;count++){
       threadTotal += count;   
      }
   }
}

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     coding  code  threads  multithreading     Asked in 1 Companies


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

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");
Core Java
Ans. equal 1

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   string class   string   string pool   code   coding      basic        frequent


 Q48. What is Byte Code ? Why Java's intermediary Code is called Byte Code ?
Ans. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system. Its called Byte Code because each instruction is of 1-2 bytes.

Sample instructions in Byte Code -

1: istore_1
2: iload_1
3: sipush 1000
6: if_icmpge 44
9: iconst_2
10: istore_2

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   jvm   interpreter   platform independent   byte code


 Q49. Difference between PATH and CLASSPATH ?Operating System
Ans. PATH is the variable that holds the directories for the OS to look for executables. CLASSPATH is the variable that holds the directories for JVM to look for .class files ( Byte Code ).

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   path   classpath   byte code   jvm   basic interview question     Asked in 3 Companies      intermediate        rare


 Q50. 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);
}
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.

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   default value


 Q51. 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");   
}
Core Java
Ans.  BuggyBread

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   coding   stringbuffer   string   method calling   pass by reference


 Q52. 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");   
}
Core Java
Ans.  Buggy

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   coding   stringbuffer   string   method calling   pass by reference


 Q53. 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");   
}
Core Java
Ans.  Buggy

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   coding   stringbuffer   string   method calling   pass by reference


 Q54. 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();
}
}
Core Java
Ans. Compile Time Error: Unhandled exception type Exception

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   code   coding   overridding   late binding   exception handling   abstract class   abstract methods


 Q55. 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) {
e.printStackTrace();
}
}
Core Java
Ans. file.txtC:file.txtC:file.txt

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   io   file   fileio   coding   code   file handling


 Q56. 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) {
e.printStackTrace();
}
}
Core Java
Ans. NullPointerException at line:File file = new File("/folder", child);

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   io   file   fileio   coding   code   file handling


 Q57. 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();
}
}
Core Java
Ans. ..file.txt
C:WorkspaceProject..file.txt
C:Workspacefile.txt

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   io   file   fileio   coding   code   file handling


 Q58. 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 );
Core Java
Ans. c.

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

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   io   file   fileio   coding   code   filewriter   bufferedwriter   scjp   ocjp  file handling


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

File file = new File("../file.txt");
FileWriter fileWriter = new FileWriter(file);
Core Java
Ans. IOException

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   io   file   fileio   coding   code   exception   ioexception  file handling


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

FileOutputStream fileOutputStream = new FileOutputStream(new File("newFile.txt"));
Ans. FileNotFoundException

 Help us improve. Please let us know the company, where you were asked this question :   

   Like         Discuss         Correct / Improve     java   io   file   fileio   coding   code   scjp   ocjp   filenotfoundexception   fileoutputstream  file handling


previous 30   next 30

Help us and Others Improve. Please let us know the questions asked in any of your previous interview.

Any input from you will be highly appreciated and It will unlock the application for 10 more requests.

Company Name:
Questions Asked: