Skip to main content

JAVA Interview Questions 2021

Inner Class vs Sub-Class

Inner class is a class which is nested within another class. It can access all variables and methods in the outer class.

A sub-class inherits from another class and can access all public and protected methods and fields in the super class.

 

Protected vs Default

Protected - allow access within the package and any subclass from outside the package.

Default - allow access within the package only

Default access specifier for variables and method is package protected i.e variables and class is available to any other class but in the same package,not outside the package.  


Static

To share a method or variable for all objects. cannot override static methods. Even if we try to override static method,we will not get an complitaion error,nor the impact of overriding when running the code. Static methods belong to a class and not to individual objects and are resolved at the time of compilation (not at runtime)

 

Encapsulation

Combining properties and methods in a single unit. and hides it.

 

Singleton

Limits one instance. Good for managing such as database connections. 

 

Continue and break 

continue - current iteration is broken and loop continues

break -loop is broken instantly 


*double and float

 

Final classes

final classes cannot be subclassed. Ex String,Integer and other wrapper classes.

 

Ternary operator

        status = (rank == 1) ? "Done" : "Pending";

Abstract vs Interface

A class can implement multiple interfaces but it can extend only one abstract class. class must implement all the methods of the interface while for a abstract class it doesn't. Interfaces are slower in performance

Class with a abstract keyword, it can have zero or more abstract  methods. Classes with abstract methods must define as abstract class.

Vartiables defined in the interface are public static final.

 

Sub-packages  

In java, when a package is imported, its sub-packages aren't imported

Ex: university.* vs university.department.*

 

Reference vs value

We can pass argument to a function only by value and not by reference.   

 

Serialization

Convert an object into byte stream. All objects of a class implementing serializable interface get serialized and their state is saved in byte stream. 

If we want certain variables of a class not to be serialized, we can use the keyword transient while declaring them. 


Constructor

Invoked every time an object is created with new keyword. if an explicit constructor has been defined, default constructor can't be invoked.

Can't create objects if we make constructor private.

 

Array and Vector

Array groups data of same primitive type and is static in nature

Vectors are dynamic in nature and can hold data of different data types. 


Vector vs arraylist

Vector is synchronized, only one thread at a time can access the code, while arrayList is not synchronized, multiple threads can work on arrayList at the same time.


Multi-threading

Run multiple tasks in a concurrent manner within a single program. Threads share same process stack and running in parallel.

Can be implemented using Runnable interface or extending Thread class. 

Access to the resources which are shared among multiple threads can be controlled by using the concept of synchronization

A thread can be in either of the following states:

  • Ready: When a thread is created
  • Running: currently being executed
  • Waiting: waiting for another thread to free certain resources
  • Dead: A thread which has gone dead after execution

There is no way to restart a dead thread. 

Volatile is an instruction that the variables can be accessed by multiple threads and hence shouldn't be cached. 

 

String or StringBuffer vs StringBuilder

Strings are immutable - once value has been assigned to a string, it can't be changed and if changed, a new object is created.

StringBuffers are dynamic in nature and can change the values of StringBuffer objects

String is immutable whereas StringBuffer and StringBuider are mutable classes. StringBuffer is thread safe and synchronized whereas StringBuilder is not


*How to compare string object and a string buffer object



Garbage collection

When an object is not referenced any more, garbage collection takes place and the object is destroyed automatically. For automatic garbage collection java calls either System.gc() or Runtime.gc(). So no destructors required.


How we can execute any code even before main method

Static block of code will get executed once at the time of loading the class even before creation of objects in the main method.  

Main method can only use void as return type. can use System.exit(int status) to notify completion of method.


Java

No pointers in Java.

When objects are created gets memory from heap. there is no way to find out the exact size of an object on the heap. no memory is allocated on heap for any class.

Java 8 - New - Lambda Expressions , Interface Default and Static Methods , Method Reference , Parameters Name , Optional , Streams, Concurrency.

If you change the value in properties file, you don't need to recompile the java class. So, it makes the application easy to manage.


Wrapper classes

Use primitive data types as objects. Integer is a wrapper class for primitive data type int


Exceptions

Checked exceptions can be caught at the time of program compilation. and must be handled by using try catch.

Java.lang.Throwable is the super class of all exception classes


Comparison

equals() method is used to compare the contents of two string objects

== operator compares the references 


Native methods

Define a method in Java class but provide it's implementation in the code of another language like C.

 

This

Can be used to call self methods.


Anonymous class

Is a class defined without class name using new keyword.

 

Serialization

Persist data of objects for later use

 

Local class

If we define a new class inside a particular block, it's called a local class. Such a class has local scope and isn't usable outside the block where its defined.

 

Collection API  

For operations on set of objects. ArrayList, HashMap, TreeSet and TreeMap are some important classes.

 

Overridding

Overridden method should have same name, and parameters.But a method can be overridden with a different return type as long as the new return type extends the original.

 

Types Of Memory Used By Jvm

Class , Heap , Stack , Register , Native Method Stack.


Types Of Class Loaders Used By Jvm

Bootstrap - Loads JDK internal classes, java.* packages.

Extensions - Loads jar files from JDK extensions directory

System  - Loads classes from system classpath.

 

What Is Permgen Or Permanent Generation

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.

PermGen is kind of replaced by a new space called Metaspace.

 

Configuration Files

settings.xml must be specific to the current user and that pom.xml configurations are specific to the project.

 

Implementation Of A Dictionary Having Large Number Of Words

In a List we can place ordered words and can perform Binary Search.

For better search performance can use HashMap with key as first character of the word and value as a LinkedList.

Further level up, we can have linked Hashmaps.

 

Hibernate

First level cache is enabled by default whereas Second level cache needs to be enabled explicitly. First level Cache is Session specific whereas Second level cache is shared by sessions that is why First level cache is considered local and second level cache is considered global,

To Avoid Lazyinitializationexception Make sure that we are accessing the dependent objects before closing the session.

To Improve Db Communication - Query Optimization ( Query Rewriting , Prepared Statements ), Restructuring Indexes, DB Caching Tuning,

 

Insert Into The Db Table. If Exception Occurs, Update The Existing Record approach

There would be 2 DB calls in worst case and 1 in best case. Good If calls to DB are costly.


Uml Diagrams

Use Case Diagram, Component Diagram for High level Design

Class Diagram , Sequence Diagram for low level design.

 

Design Patterns  

Adapter object has a different input than the real subject whereas Proxy object has the same input as the real subject. Proxy object is such that it should be placed as it is in place of the real subject.

Adapter is used because the objects in current form cannot communicate where as in Facade , though the objects can communicate , A Facade object is placed between the client and subject to simplify the interface.

Composite creates Parent Child relations between your objects while Builder is used to create group of objects of predefined types.

Factory revolves around the creation of object at runtime whereas Strategy or Policy revolves around the decision at runtime.

Strategy Design Pattern deals only with decision making at runtime so Interfaces should be used.



 -------

The hashCode() method returns a hash code value (an integer number). The hashCode() method returns the same integer number, if two keys (by calling equals() method) are same. But, it is possible that two hash code numbers can have different or same keys.

The equals method is used to check whether two objects are same or not. It needs to be overridden if we want to check the objects based on property. 

https://www.wisdomjobs.com/e-university/java-j2ee-architect-interview-questions.html

Comments

Popular posts from this blog

Oracle Database 12c installation on Ubuntu 16.04

This article describes how to install Oracle 12c 64bit database on Ubuntu 16.04 64bit. Download software  Download the Oracle software from OTN or MOS or get a downloaded zip file. OTN: Oracle Database 12c Release 1 (12.1.0.2) Software (64-bit). edelivery: Oracle Database 12c Release 1 (12.1.0.2) Software (64-bit)   Unpacking  You should have following two files downloaded now. linuxamd64_12102_database_1of2.zip linuxamd64_12102_database_2of2.zip Unzip and copy them to \tmp\databases NOTE: you might have to merge two unzipped folders to create a single folder. Create new groups and users Open a terminal and execute following commands. you might need root permission. groupadd -g 502 oinstall groupadd -g 503 dba groupadd -g 504 oper groupadd -g 505 asmadmin Now create the oracle user useradd -u 502 -g oinstall -G dba,asmadmin,oper -s /bin/bash -m oracle You will prompt to set to password. set a momorable password and write it down. (mine is orac

DBCA : No Protocol specified

when trying to execute dbca from linux terminal got this error message. now execute the command xhost, you probably receiving No protocol specified xhost:  unable to open display ":0" issue is your user is not allowed to access the x server. You can use xhost to limit access for X server for security reasons. probably you are logged in as oracle user. switch back to default user and execute xhost again. you should see something like SI:localuser:nuwan solution is adding the oracle to access control list xhost +SI:localuser:oracle now go back to oracle user and try dbca it should be working

Java Head Dump Vs Thread Dump

JVM head dump is a snapshot of a JVM heap memory in a given time. So its simply a heap representation of JVM. That is the state of the objects. JVM thread dump is a snapshot of a JVM threads at a given time. So thats what were threads doing at any given time. This is the state of threads. This helps understanding such as locked threads, hanged threads and running threads. Head dump has more information of java class level information than a thread dump. For example Head dump is good to analyse JVM heap memory issues and OutOfMemoryError errors. JVM head dump is generated automatically when there is something like OutOfMemoryError has taken place.  Heap dump can be created manually by killing the process using kill -3 . Generating a heap dump is a intensive computing task, which will probably hang your jvm. so itsn't a methond to use offetenly. Heap can be analysed using tools such as eclipse memory analyser. Core dump is a os level memory usage of objects. It has more informaiton t