Project Management Professional

Friday, August 14, 2020

Project related Java Interview Questions

Below are the interview questions asked by clients. Prepare on your resume and projects before going to client interviews.

1.Tell me about yourself?
2.Tell me about your experience and project details?
3.How you implemented agile in your project?
4.How does spring MVC work, Hibernate and Rest Service work?
5. Let me know the setup of your application?
6.Write a Rest Service?
7.How do you deploy process work?
8.How did you do production support and fixed performance issues?
9. How do you handle rest Security?
10. What is team size?
11.Take a page or login page and explain the end to end process?
12.Are you comfortable with DB?
13.Are you comfortable with the Agile process?
14.Do you have experience on Unix?
15. What is PS _EF?
16. What is GREP,KILL,TAIL,HEAD?

Will come up with top 10 questions....Stay tuned.

Tuesday, July 21, 2020

Core Java interview questions.

Core java Interview questions

Java Interview Questions!

40.

Define classes in Java 

Answer: A class is a collection of objects of similar data types. Classes are user-defined data types and behave like built-in types of a programming language. 

Syntax of a class: 

class Sample{

member variables

methods()

}


41.Please explain Local variables and Instance variables in Java.

Answer: Variables that are only accessible to the method or code block in which they are declared are known as local variables. Instance variables, on the other hand, are accessible to all methods in a class. While local variables are declared inside a method or a code block, instance variables are declared inside a class but outside a method. Even when not assigned, instance variables have a value that can be null, 0, 0.0, or false. This isn't the case with local variables that need to be assigned a value, where failing to assign a value will yield an error. Local variables are automatically created when a method is called and destroyed as soon as the method exits. For creating instance variables, the new keyword must be used.

42.What is an Object?

Answer: An instance of a Java class is known as an object. Two important properties of a Java object are behaviour and state. An object is created as soon as the JVM comes across the new keyword.


Core Java Interview Questions!

32.

Explain the scenerios to choose between String , StringBuilder and StringBuffer ?


or


What is the difference between String , StringBuilder and StringBuffer ? 

Core Java

If the Object value will not change, use String Class because a String object is immutable.


If the Object value can change and will only be modified from a single thread, use StringBuilder because StringBuilder is unsynchronized(means faster).


If the Object value may change, and can be modified by multiple threads, use a StringBuffer because StringBuffer is thread safe(synchronized).


33.Why don't we use pointers in Java?

Answer: Pointers are considered to be unsafe, and increase the complexity of the program, add

ing the concept of pointers can be contradicting. Also, JVM is responsible for implicit memory allocation; thus, to avoid direct access to memory by the user, pointers are discouraged in Java.

34.What is multiple inheritance? Does Java support multiple inheritance? If not, how can it be achieved?

Answer: If a subclass or child class has two parent classes, that means it inherits the properties from two base classes, it is multiple inheritances. Java does not multiple inheritances as in case if the parent classes have the same method names, then at runtime, it becomes ambiguous, and the compiler is unable to decide which method to execute from the child class.

35.Please explain what do you mean by an Abstract class and an Abstract method?

Answer: An abstract class in Java is a class that can't be instantiated. Such a class is typically used for providing a base for subclasses to extend as well as implementing the abstract methods and overriding or using the implemented methods defined in the abstract class. To create an abstract class, it needs to be followed by the abstract keyword. Any abstract class can have both abstract as well as non-abstract methods. A method in Java that only has the declaration and not implementation is known as an abstract method. Also, an abstract method name is followed by the abstract keyword. Any concrete subclass that extends the abstract class must provide an implementation for abstract methods.

36.What is String Pool in Java?

Answer: The collection of strings stored in the heap memory refers to the String pool. Whenever a new object is created, it is checked if it is already present in the String pool or not. If it is already present, then the same reference is returned to the variable else new object is created in the String pool, and the respective reference is returned.

37.Could you draw a comparison between Array and ArrayList?

Answer: An array necessitates for giving the size during the time of declaration, while an array list doesn't necessarily require size as it changes size dynamically. To put an object into an array, there is the need to specify the index. However, no such requirement is in place for an array list. While an array list is parameterized, an array is not parameterized.

38.What are the default values for local variables?

Answer: The local variables are not initialized to any default value, neither primitives nor object references.


39.Explain different types of typecasting?

The concept of assigning a variable of one data type to a variable of another data type. It is not possible for the boolean data type.


Different types of typecasting are:

  • Implicit/Widening Casting: Storing values from a smaller data type to the larger data type. It is automatically done by the compiler.

  • Explicit/Narrowing Casting: Storing the value of a larger data type into a smaller data type. This results in information loss:

  1. Truncation

  2. Out of Range

Let us see code samples to further understand this:

int i = 10;

long l = i;

long l = 10,000;

int i = (int) l;

float f = 3.14f

int i = (int) f;

i=3;

long l = 123456789;

byte b = (byte) l;








Core Java Interview Questions!

29.Why Java provides default constructor ?

Ans. At the beginning of an object's life, the Java virtual machine (JVM) allocates memory on the heap to accommodate the object's instance variables. When that memory is first allocated, however, the data it contains is unpredictable. If the memory were used as is, the behavior of the object would also be unpredictable. To guard against such a scenario, Java makes certain that memory is initialized, at least to predictable default values before it is used by any code.

30.Why String is popular HashMap key in 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.

31.Write a Program to check if 2 strings are Anagrams ?

{a word, phrase, or sentence formed from another by rearranging its letters: “Angel” is an anagram of “glean.” }

Check by sorting/equals method:

   

    public class CheckAnagram {

//a word, phrase, or sentence formed from another by rearranging its letters: “Angel” is an anagram of “glean.” 

public static void main (String[] args) throws java.lang.Exception

    {

        boolean result = isAnagram("now","own");

        System.out.println(result);

    }

    public static boolean isAnagram(String first, String second)

    {

        // remove all whitespaces and convert strings to lowercase

        first  = first.replaceAll("\\s", "").toLowerCase();

        second = second.replaceAll("\\s", "").toLowerCase();


        /* check whether string lengths are equal or not,

        if unequal then not anagram */

        if (first.length() != second.length())

        return false;


        // convert string to char array

        char[] firstArray = first.toCharArray();

        char[] secondArray = second.toCharArray();


        // sort both the arrays

        Arrays.sort(firstArray);

        Arrays.sort(secondArray);


        // checking whether both strings are equal or not

        return Arrays.equals(firstArray,secondArray);

    }

}

Core Java Interview Questions!


28.Will this code give error if i try to add two heterogeneous elements in the arraylist. ? and Why ?

List list1 = new ArrayList<>();

list1.add(5);

list1.add("5");

Heterogeneous:having widely dissimilar elements

*ArrayList is one of the most flexible data structure from Java Collections. Arraylist is a class which implements List interface . It is one of the widely used because of the functionality and flexibility it offers. It is designed to hold heterogeneous collections of objects

Ans.No, If we don't declare the list to be of specific type, it treats it as list of objects.

int 1 is auto boxed to Integer and "1" is String and hence both are objects.


Example below:


import java.util.List; import java.util.ArrayList; public class ListAdd { public static void main(String[] args) { /* List<String> langs = new ArrayList<>(); langs.add("Java"); langs.add("Python"); langs.add(1, "C#"); langs.add(0, "Ruby"); for (String lang : langs) { System.out.printf("%s ", lang);//PrintStream methods to format the output } System.out.println(); }*/ List list1 = new ArrayList<>(); list1.add(5); list1.add("5"); System.out.println(list1);



Core Java Interview Questions!

23.Why HashTable has been deprecated ?

 HashTable has been deprecated. As an alternative, ConcurrentHashMap has been provided. It uses multiple buckets to store data and hence much better performance than HashTable. Moreover, there is already a raw type HashMap.


24.Why do member variables have default values whereas local variables don't have any default value ?

member variable are loaded into heap, so they are initialized with default values when an instance of a class is created. In case of local variables, they are stored in stack until they are being used.

25.Difference between static vs. dynamic class loading?

static loading - Classes are statically loaded with Java new operator.


dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. 


26.Difference between static vs. dynamic class loading?


Ans. static loading - Classes are statically loaded with Java new operator.


dynamic class loading - Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time. 


Class.forName (Test className);


27.What is PermGen or Permanent Generation ?


The memory pool containing all the reflective data of the java virtual machine itself, such as class and method objects. With Java VMs that use class data sharing, this generation is divided into read-only and read-write areas. The Permanent generation contains metadata required by the JVM to describe the classes and methods used in the application. The permanent generation is populated by the JVM at runtime based on classes in use by the application. In addition, Java SE library classes and methods may be stored here.



Core Java Interview Questions!

19.What one should take care of, while serializing the object?

One should make sure that all the included objects are also serializable. If any of the objects is not serializable then it throws a NotSerializable Exception.

20.Are constructors inherited? Can a subclass call the parent's class constructor? When?

You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses. One of the main reasons is because you probably don't want to override the superclasses constructor, which would be possible if they were inherited. By giving the developer the ability to override a superclasses constructor you would erode the encapsulation abilities of the language.

21.Difference between Factory and Abstract Factory Design Pattern ?

Ans. Factory Pattern deals with creation of objects delegated to a separate factory class whereas Abstract Factory patterns works around a super-factory which creates other factories.


22.Can we override compareTo method for Enumerations ?

Ans. No. compareTo method is declared final for the Enumerations and hence cannot be overriden. This has been intentionally done so that one cannot temper with the sorting order on the Enumeration which is the order in which Enum constants are declared.



Core Java Interview Questions!


17.Tell me something about OOPs

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


18.Difference between Predicate, Supplier and Consumer ?


Ans. Predicate represents an anonymous function that accepts one argument and produces a result.


Supplier represents an anonymous function that accepts no argument and produces a result.


Consumer represents an anonymous function that accepts an argument and produces no result.


Core Java Interview Questions!

Sample code for equals() and == below:

public class Equals {

method equals()

public static void main(String[] args)

{

/* integer-type*/

System.out.println(10 == 20);

/* char-type*/

System.out.println('a' == 'b');

/* char and double type*/

System.out.println('a' == 97.0);

/* boolean type*/

System.out.println(true == true);

}

}


 equals method:


public class Equals{

public static void main(String[] args)

{

String s1 = new String("HELLO");

String s2 = new String("HELLO");

System.out.println(s1 == s2);

System.out.println(s1.equals(s2));

}

}


Core Java Interview Questions!

15.Why is String immutable in 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.


16.Difference between == and .equals() ? example in eclipse

"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:



Core Java Interview Questions!


12.What are different ways of object creation in Java ?

Ans. Using new operator - new xyzClass()


Using factory methods - xyzFactory.getInstance( )


Using newInstance( ) method - (Class.forName(xyzClass))emp.newInstance( )


By cloning an already available object - (xyzClass)obj1.clone( )


13.What is a Lambda Expression ? What's its use ?

Its an anonymous method without any declaration. 

Lambda Expression are useful to write shorthand Code and hence saves the effort of writing lengthy Code. 

It promotes Developer productivity, Better Readable and Reliable code.

14.Which are the different segments of memory ?

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



Core Java Interview Questions!


12.Difference between final and effectively final ? Why is effectively final even required ?

Ans. Final variable means a variable that has been declared final and hence cannot be de referenced after initialization. Effective final means a variable that has not been declared final but haven't been reassigned the value after initialization.


First is the regulation that restricts the reassignment and will raise a compilation error if we try to do so. Second is the outcome without the restriction.


Effective Final is the eventual treatment of the variable that is required for many features. For eq - Java 8 requires that local variables referenced from a lambda expression must be final or effectively final.It means all local referenced from lambda expressions must be such that their value shouldn't be changed after initialization whether declared final or not.

13.How does making string as immutable helps with securing information ? How does String Pool pose a security threat ?

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 or hacker over internet.


Once a String constant is created in Java , it stays in string constant pool until garbage collected and hence stays there much longer than what's needed. Any unauthorized access to string Pool pose a threat of exposing these values.