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 for 'Code' - 166 question(s) found - Order By Newest

next 30
Very frequently asked. Among first few questions in almost all interviews. Among Top 5 frequently asked questions. Frequently asked in Indian service companies (HCL,TCS,Infosys,Capgemini etc based on multiple feedback ) and Epam Systems
  Q1. Difference between == and .equals() ?Core Java
Ans. "equals" is the method of object class which is supposed to be overridden to check object equality, whereas "==" operator evaluate to see if the object handlers on the left and right are pointing to the same object in memory.

x.equals(y) means the references x and y are holding objects that are equal. x==y means that the references x and y have same object.

Sample code:

String x = new String("str");
String y = new String("str");

System.out.println(x == y); // prints false
System.out.println(x.equals(y)); // prints true

  Sample Code for equals

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

   Like         Discuss         Correct / Improve     java   string comparison   string   object class   ==    equals   object equality  operator   == vs equals   equals vs ==     Asked in 294 Companies      basic        frequent

Try 6 Question(s) Test


Advanced level question. Frequently asked in High end product companies. Frequently asked in Google , Cognizant and Deloitte ( Based on 2 feedback )
  Q2. Why is String immutable in Java ?Core Java
Ans. 1. String Pool - When a string is created and if it exists in the pool, the reference of the existing string will be returned instead of creating a new object. If string is not immutable, changing the string with one reference will lead to the wrong value for the other references.

Example -

String str1 = "String1";
String str2 = "String1"; // It doesn't create a new String and rather reuses the string literal from pool

// Now both str1 and str2 pointing to same string object in pool, changing str1 will change it for str2 too

2. To Cache its Hashcode - If string is not immutable, One can change its hashcode and hence it's not fit to be cached.

3. Security - String is widely used as parameter for many java classes, e.g. network connection, opening files, etc. Making it mutable might possess threats due to interception by the other code segment.

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

   Like         Discuss         Correct / Improve     java   oops   string   string class   immutable  immutability   advanced     Asked in 39 Companies      expert        frequent

Try 4 Question(s) Test


  Q3. Explain OOPs

or

Explain OOPs Principles

or

Explain OOPs Concepts

or

Explain OOPs features

or

Tell me something about OOPs
Core Java
Ans. OOPs or Object Oriented Programming is a Programming model which is organized around Objects instead of processes. Instead of a process calling series of processes, this model stresses on communication between objects. Objects that all self sustained, provide security by encapsulating it's members and providing abstracted interfaces over the functions it performs. OOP's facilitate the following features

1. Inheritance for Code Reuse
2. Abstraction for modularity, maintenance and agility
3. Encapsulation for security and protection
4. Polymorphism for flexibility and interfacing

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

   Like         Discuss         Correct / Improve     oops  oops features     Asked in 260 Companies      basic        frequent


  Q4. Which are the different segments of memory ?Core Java
Ans. 1. Stack Segment - Contains primitives, Class / Interface names and references.

2. Heap Segment - Contains all created objects in runtime, objects only plus their object attributes (instance variables), Static variables are also stored in heap.

3. Code Segment - The segment where the actual compiled Java bytecodes resides when loaded

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

   Like         Discuss         Correct / Improve     java   memory   memory management   stack memory   heap memory   code segment memory   advanced     Asked in 9 Companies      expert        frequent

Try 6 Question(s) Test


Frequently asked in all types of companies especially Indian Services companies. Frequently asked in CTS (Based on 2 feedback)
  Q5. What is the use of hashcode in Java ?Core Java
Ans. Hashcode is used for bucketing in Hash implementations like HashMap, HashTable, HashSet etc. The value received from hashcode() is used as bucket number for storing elements. This bucket number is the address of the element inside the set/map. when you do contains() then it will take the hashcode of the element, then look for the bucket where hashcode points to and if more than 1 element is found in the same bucket (multiple objects can have the same hashcode) then it uses the equals() method to evaluate if object are equal, and then decide if contain() is true or false, or decide if element could be added in the set or not.

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

   Like         Discuss         Correct / Improve     java   collections   hashcode   advanced  hashtable     Asked in 33 Companies      intermediate        frequent

Try 1 Question(s) Test


Very frequently asked. Favorite question in Walk in Drive of many Indian service companies.
  Q6. What is a final method ?Core Java
Ans. Its a method which cannot be overridden. Compiler throws an error if we try to override a method which has been declared final in the parent class.

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

   Like         Discuss         Correct / Improve     java   oops   final   final method     Asked in 30 Companies      basic        frequent

Try 1 Question(s) Test


Almost sure to be asked in every company using any Dependency Injection framework ( Spring, Guice etc )
  Q7. What is Dependency Injection or IOC ( Inversion of Control ) ?Design
Ans. It is a Design Pattern that facilitates loose coupling by sending the dependency information ( object references of dependent object ) while building the state of the object. Objects are designed in a manner where they receive instances of the objects from other pieces of code, instead of constructing them internally and hence provide better flexibility.

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

   Like         Discuss         Correct / Improve     design patterns   ioc ( Inversion of Control )  dependency injection     Asked in 83 Companies      intermediate        frequent


 Q8. How to find whether a given integer is odd or even without use of modulus operator in java?Core Java
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 ");
}
}

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

   Like         Discuss         Correct / Improve     java   code   coding   tricky questions   interesting questions   modulus operator     Asked in 4 Companies        frequent


 Q9. 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());
}
Core Java
Ans. NullPointerException

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

 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


 Q10. What do you look for when you do code review ?Core Java
Ans. Modularity - First sign of good code is whether it has been segregated into methods and classes appropriately. I dont mind it in excess because I believe that is forward looking strategy as applications tends to expand and eventually become hard to read.

Self Explanatory - Variables and methods should be named in a way that the code should be self explanatory even without comments. Use of Constant variables to explain use of literal.

Proper Code Reuse - If there is anything being reused , it should be moved to parent classes / methods.

Proper composition calls - Composed hierarchy should not be access in just single line. One or two levels is ok but having multiple levels make it hard to read and debug.

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

   Like         Discuss         Correct / Improve     code review  clean code     Asked in 1 Companies      intermediate        frequent


 Q11. There are two objects a and b with same hashcode. I am inserting these two objects inside a hashmap.

hMap.put(a,a);
hMap.put(b,b);

where a.hashCode()==b.hashCode()

Now tell me how many objects will be there inside the hashmap?
Core Java
Ans. There can be two different elements with the same hashcode. When two elements have the same hashcode then Java uses the equals to further differentation. So there can be one or two objects depending on the content of the objects.

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

   Like         Discuss         Correct / Improve     java   hashcode   map   hashmap   object reference   advanced     Asked in 1 Companies


 Q12. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Ans. Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

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

   Like         Discuss         Correct / Improve     character coding   ascii   unicode   utf

Try 1 Question(s) Test


 Q13. How Java provide high Performance ?Core Java
Ans. Java uses Just-In-Time compiler to enable high performance. Just-In-Time compiler is a program that turns Java bytecode into instructions that can be sent directly to the processor.

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

   Like         Discuss         Correct / Improve     java   compiler   jvm   bytecode   justintime compiler   architecture


 Q14. 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) {
e.printStackTrace();
}
}
Core Java
Ans. It will create the file myfile.txt in the current directory.

 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


 Q15. Which of the following Java feature promotes Code Re usability ?

a. Abstraction
b. Encapsulation
c. Inheritance
d. Polymorphism
Core Java
Ans. Inheritance

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

   Like         Discuss         Correct / Improve     java   java concepts   java features   code reusability


This question can be asked in different variants like performace improvement of an application, improving performance for DB communication etc.
 Q16. What are the ways in which execution time of the code can be improved ?Solution
Ans. This depends on entirely upon the code type. For example

1.If its just logic, we can try it to short circuit or put the if / switch case with maximum probability in the beginning.

2. Can use faster data structures, for eg - random retrieval instead of sequence / iterator

3. Working with primitive types or even bytes instead of Objects, even though it may result in marginal improvement.

4. If its service call, then service call with bulk load can help

5. If DB Operation, then with use of Indices , Views or using ORM , cache etc.


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

   Like         Discuss         Correct / Improve     performance improvement  code optimization     Asked in 1 Companies


 Q17. Trim a string without using String library methodCore Java
 This question was recently asked at 'Ariba'.This question is still unanswered. Can you please provide an answer.


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

   Like         Discuss         Correct / Improve     code  coding.string  trim a string     Asked in 1 Companies


Usually asked to entry level software developers.
  Q18. Write a program to swap two variables without using thirdCore Java
Ans. public static void main(String[] args) {
   int num1 = 1;   
   int num2 = 2;
   num1 = num1^num2;
   num2 = num1^num2;
   num1 = num1^num2;
   System.out.print("num1 = " + num1 +", num2 = "+num2);
}

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

   Like         Discuss         Correct / Improve     code  coding     Asked in 37 Companies      basic        frequent


Very frequently asked. Usually asked with questions related to String. Frequently asked at CTS / Cognizant
  Q19. What is an Immutable Object ?Core Java
Ans. Object that can't be changed after instantiation.

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

   Like         Discuss         Correct / Improve     java   oops   immutable  immutability     Asked in 27 Companies      basic        frequent

Try 2 Question(s) Test


  Q20. Write a method to check if input String is Palindrome?Core Java
Ans. private static boolean isPalindrome(String str) {

if (str == null)
return false;

StringBuilder strBuilder = new StringBuilder(str);

strBuilder.reverse();

return strBuilder.toString().equals(str);

}

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

   Like         Discuss         Correct / Improve     java   string   stringbuilder   stringbuilder   string class   code   palindrome     Asked in 38 Companies      Basic        frequent


 Q21. Write a method that will remove given character from the String?Core Java
Ans.
private static String removeChar(String str, char c) {    
if (str == null)
return null;

return str.replaceAll(Character.toString(c), "");
}


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

   Like         Discuss         Correct / Improve     java   string   string class   code   write code


 Q22. Why String is popular HashMap key in Java?Core Java
Ans. Since String is immutable, its hashcode is cached at the time of creation and it doesnt need to be calculated again. This makes it a great candidate for key in a Map and its processing is fast than other HashMap key objects. This is why String is mostly used Object as HashMap keys.

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

   Like         Discuss         Correct / Improve     java   string class   string   immutable  immutability   hashmap   immutable  immutability   hashcode   hash code   advanced     Asked in 2 Companies      expert        frequent


 Q23. 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();
   }
}
Core Java
Ans.  Yes. static method is not accessed by the instance of class. Either you call it by the class name or the reference.

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

   Like         Discuss         Correct / Improve     java   static   static method   code


Very frequently asked in HCL Tech ( Based of 4 inputs )
  Q24. Write a program to reverse a string iteratively and recursively ?Core Java
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);
}

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

   Like         Discuss         Correct / Improve     java   string   reverse   stringbuffer   string class   code     Asked in 6 Companies        frequent


 Q25. 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);
   }
}
Core Java
Ans. true, due to String Pool, both will point to a same String object.

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

   Like         Discuss         Correct / Improve     java   code   coding   tricky questions   interesting questions   string   string pool   .equal   ==      intermediate        frequent


 Q26. 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);    
   } 
}
Core Java
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. 

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

   Like         Discuss         Correct / Improve     java   code   coding   tricky questions   interesting questions   default constructor   constructor

Try 3 Question(s) Test


 Q27. Will this code compile fine ?

ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("newFile.txt")));
Core Java
Ans. Yes.

 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   objectoutputstream   fileoutputstream   yesno  file handling


 Q28. 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());
}
}
Core Java
Ans. matcher.find() should have been used instead of matcher.next() within while.

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

   Like         Discuss         Correct / Improve     java   regex   pattern.matcher   java.util   coding   code


 Q29. 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);
}
Ans. It will print 4567,5678 and 6789 but Order cannot be predicted.

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

   Like         Discuss         Correct / Improve     java   collections   set   hashset   coding   code

Try 1 Question(s) Test


 Q30. 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));
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.

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

   Like         Discuss         Correct / Improve     java   collections   set   hashset   coding   code

Try 1 Question(s) Test


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: