Common Jobs

Most tricky Java Interview Questions are given below :

1. Which two methods you need to implement for key Object in HashMap?

Youtube Channel Subscribe Now

In order to use any object as Key in HashMap, it must implements equals and hashcode method in Java. 

hashCode(): This method returns a hash code value for the object. It is used by hash-based data structures such as HashMap to determine the bucket location for storing the key-value pair. The general contract of hashCode() is that equal objects must produce the same hash code. However, it’s important to note that different objects can produce the same hash code (known as hash collisions), so it’s crucial to implement hashCode() effectively to minimize collisions.equals(Object obj): This method compares the current object with the specified object for equality. In the context of HashMap, it is used to determine if two keys are equal. The equals() method should be overridden to provide custom equality comparison based on the key’s attributes. The general contract of equals() specifies that it must be reflexive, symmetric, transitive, and consistent.

Most tricky Java Interview Questions

 

Most tricky Java Interview Questions

2. What is immutable object? Can you write immutable object?

Immutable classes are Java classes whose objects can not be modified once created. Any modification in Immutable object result in new object. For example is String is immutable in Java. Mostly Immutable are also final in Java, in order to prevent sub class from overriding methods in Java which can compromise Immutability. You can achieve same functionality by making member as non final but private and not modifying them except in constructor.

3. What is the difference between creating String as new() and literal?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String(“Test”);

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = “Test” Java automatically put that into String pool.

4. What is difference between StringBuffer and StringBuilder in Java?

StringBuffer StringBuilder
This class is thread-safe, meaning it is designed to be safely used by multiple threads concurrently. All of its public methods are synchronized, ensuring that only one thread can access the StringBuffer object at a time. While this thread safety guarantees consistency in a multi-threaded environment, it comes with a performance cost. Unlike StringBuffer, StringBuilder is not thread-safe. Its methods are not synchronized, making it more efficient for single-threaded scenarios. However, if multiple threads access a StringBuilder concurrently without proper synchronization, it can lead to unexpected behavior and data corruption.
Due to its thread safety, StringBuffer tends to be slower in single-threaded scenarios compared to StringBuilder. The synchronization overhead incurred by StringBuffer’s methods can impact performance, especially in high-throughput applications. Because it is not thread-safe, StringBuilder does not incur the synchronization overhead of StringBuffer. As a result, StringBuilder generally offers better performance than StringBuffer, especially in single-threaded environments where thread safety is not a concern.
It is recommended to use StringBuffer when working in a multi-threaded environment where thread safety is required. For example, in scenarios involving concurrent access to shared data structures across multiple threads. StringBuilder is preferred in single-threaded scenarios where performance is a priority and thread safety is not a concern. It is commonly used for string manipulation in situations where only one thread accesses the object.

Most tricky Java Interview Questions

 

Most tricky Java Interview Questions

5.  Write code to find the First non-repeated character in the String.

import java.util.HashMap;

import java.util.Map;

public class FirstNonRepeatedCharacter {

    public static char findFirstNonRepeatedCharacter(String str) {

        // Create a map to store the frequency of each character

        Map<Character, Integer> charFrequency = new HashMap<>();

        // Populate the map with character frequencies

        for (char ch : str.toCharArray()) {

            charFrequency.put(ch, charFrequency.getOrDefault(ch, 0) + 1);

        }

        // Iterate through the string to find the first non-repeated character

        for (char ch : str.toCharArray()) {

            if (charFrequency.get(ch) == 1) {

                return ch; // Return the first non-repeated character

            }

        }

        // If no non-repeated character found, return a placeholder character

        return ‘\0’; // ‘\0’ represents null character

    }

    public static void main(String[] args) {

        String str = “hello”;

        char firstNonRepeatedChar = findFirstNonRepeatedCharacter(str);

        if (firstNonRepeatedChar != ‘\0’) {

            System.out.println(“First non-repeated character in \”” + str + “\” is: ” + firstNonRepeatedChar);

        } else {

            System.out.println(“No non-repeated character found in \”” + str + “\””);

        }

    }

}

6. In how many ways you can create a string objects in Java?

There are two ways to create string objects in java. One is using new operator and another one is using string literals. The objects created using new operator are stored in the heap memory and objects created using string literals are stored in string constant pool.

String s1 = new String(“hello”);         

//Creating string object using

new operator

String s2 = “hello”;   

//Creating string object using

string literal

Most tricky Java Interview Questions

 

Most tricky Java Interview Questions

7. What is String Pool ?

String pool is the memory space in heap memory specially allocated to store the string objects created using string literals. In String pool, there will be no two string objects having the same content.

Whenever you create a string object using string literal, JVM first checks the content of the object to be created. If there exist an object in the string pool with the same content, then it returns the reference of that object. It doesn’t create a new object. If the content is different from the existing objects then only it creates new object.

8. what are static blocks and static initializers in Java?

Static blocks or static initializers are used to initialize static fields in java. we declare static blocks when we want to intialize static fields in our class. Static blocks gets executed exactly once when the class is loaded . Static blocks are executed even before the constructors are executed.

9.  How to call one constructor from the other constructor ?

With in the same class if we want to call one constructor from other we use this() method. Based on the number of parameters we pass appropriate this() method is called. Restrictions for using this method :

 1) this must be the first statement in the constructor 

2)we cannot use two this() methods in the constructor

Interview questions for Tech mahindra for freshers new Joinee

10.  What is super keyword in java?

Variables and methods of super class can be overridden in subclass . In case of overriding , a subclass object call its own variables and methods. Subclass cannot access the variables and methods of superclass because the overridden variables or methods hides the methods and variables of super class. But still java provides a way to access super class members even if its members are overridden. Super is used to access superclass variables, methods, constructors. Super can be used in two forms :

 1) First form is for calling super class constructor. 

2) Second one is to call super class variables,methods. 

Super if present must be the first statement.

11. Difference between method overloading and method overriding in java ?

Method overloading Method overriding
Method Overloading occurs with in the same class Method Overriding occurs between two classes superclass and subclass 
Since it involves with only one class inheritance is not involved.  Since method overriding occurs between superclass and subclass inheritance is involved. 
In overloading return type need not be the same In overriding return type must be same. 
Parameters must be different when we do overloading  Parameters must be same. 
Static polymorphism can be acheived using method overloading  Dynamic polymorphism can be acheived using method overriding. 
In overloading one method can’t hide the another  In overriding subclass method hides that of the superclass method.  

Most tricky Java Interview Questions

 

Most tricky Java Interview Questions

12. Why java is platform independent?

The most unique feature of java is platform independent. In any programming language soruce code is compiled in to executable code . This cannot be run across all platforms. When javac compiles a java program it generates an executable file called .class file. class file contains byte codes. Byte codes are interpreted only by JVM’s . Since these JVM’s are made available across all platforms by Sun Microsystems, we can execute this byte code in any platform. Byte code generated in windows environment can also be executed in linux environment. This makes java platform independent.

13. What is bytecode in java ?

When a javac compiler compiler compiles a class it generates .class file. This .class file contains set of instructions called byte code. Byte code is a machine independent language and contains set of instructions which are to be executed only by JVM. JVM can understand this byte codes.

14. Difference between this() and super() in java ?

this() is used to access one constructor from another with in the same class while super() is used to access superclass constructor. Either this() or super() exists it must be the first statement in the constructor.

15. What is a class ?

Classes are fundamental or basic unit in Object Oriented Programming .A class is kind of blueprint or template for objects. Class defines variables, methods. A class tells what type of objects we are creating. For example take Department class tells us we can create department type objects. We can create any number of department objects. All programming constructs in java reside in class. When JVM starts running it first looks for the class when we compile. Every Java application must have atleast one class and one main method. Class starts with class keyword. A class definition must be saved in class file that has same as class name. File name must end with .java extension.

16. What is an object ?

An Object is instance of class. A class defines type of object. Each object belongs to some class.Every object contains state and behavior. State is determined by value of attributes and behavior is called method. Objects are alos called as an instance. To instantiate the class we declare with the class type.

17.  Why main() method is public, static and void in java?

public : “public” is an access specifier which can be used outside the class. When main method is declared public it means it can be used outside class.

static : To call a method we require object. Sometimes it may be required to call a method without the help of object. Then we declare that method as static. JVM calls the main() method without creating object by declaring keyword static.

void : void return type is used when a method does’nt return any value . main() method does’nt return any value, so main() is declared as void.

Most tricky Java Interview Questions

 

Most tricky Java Interview Questions

18.  What is constructor in java?

we use constructors to initialize all variables in the class when an object is created. As and when an object is created it is initialized automatically with the help of constructor in java. We have two types of constructors Default Constructor Parameterized Constructor 

19. What is ASCII Code?

ASCII stands for American Standard code for Information Interchange. ASCII character range is 0 to 255. We can’t add more characters to the ASCII Character set. ASCII character set supports only English. That 6 | Page is the reason, if we see C language we can write c language only in English we can’t write in other languages because it uses ASCII code.

20. What is Unicode?

Unicode is a character set developed by Unicode Consortium. To support all languages in the world Java supports Unicode values. Unicode characters were represented by 16 bits and its character range is 0- 65,535.