Tutorial Study Image

Java Interview Questions

Java Virtual Machine or the JVM is a virtual or abstract specification. When JVM is installed on a computer, it helps to run java byte codes regardless of the computer hardware intricacies.

Java Runtime Environment. JRE is just a container that synchronizes java class libraries and (JVM) Java virtual machine. The JVM runs the java byte codes using the class libraries the JRE provides an environment for this

1. Portable: Since java programs are compiled into platform independant byte codes, it can be run on any machine irrespective of the hardware. In short we can say java is platform-independant. Due to the same reason it is an architectural-neutral language.

2. Object Oriented : In Java everything is an object

3. High Performance : Due to its just-in-time compiler that compiles on the fly, the performance of java programs are quiet fast.

4. Secure : Java's public key encryption makes it a secure language

6. Robust : Java is lesser error prone due its compile time and run time error checking

Java Runtime Environment and Java Virtual Machine. The java virtual machine is a set of specifications and JRE is the actual environment of the specification. JVM converts the byte codes to machine languages and JRE has the binaries and class libraries for this.

Java Development Kit is a platform-based development package that can be used for java application development. It includes tools for the development, compilation and execution of java programs.

Yes, actually JDK, the Java development kit includes the tools for development and the java run time environment. The java run time environment houses the class libraries and the Java virtual machine specifications.

JIT is the short form for a high-performance compiler called Just in Time Compiler Just In Time compiler. Unlike traditional compilers which compiles the whole code together and then runs it, JIT compiles the code on the fly.

Due to this they can create faster executable machine codes.

Java is both an interpreted and compiled language. Java codes are first compiled into byte codes, the byte codes are then interpreted by java virtual machine.

Java has just in time compilers which rather than compiling code in bulk, compiles the code on the fly. The compiled codes are byte codes which is again a faster executing set of operations that can be quickly converted to machine dependant codes.

Also, java uses multi-threading, which means various threads are managed by the java virtual machine and each thread can do a task and multiple threads can co-exist.

Each part of the program is assigned to a thread, and the threads can coexist. This enables concurrent execution and also utilises the CPU well.

JDB expands to JAVA Debugger. It is a command-line tool that helps to step in to a java class and debug the code.

Keywords are reserved words in java. These are special texts used for special purposes of the programming language. These words cannot be used as identifiers

Identifiers are names for things in java. The things in java can be variables, classes, and functions.

Letters both capital and small, _, $ and numbers can be part of identifiers in java. Each identifier must have at least one character other than number. The identifiers cannot be started with numbers, rest can be any of numbers, _, $and letters or combination of them.

In java the scope of a variable is between {},  that is in a code block. Local variables are variables pertaining to method, constructor or a code blocks. In java generally there is no concept of global variables, but all member variables are considered global when they are declared outside a method or constructor. This is so, because they can be accessed inside any member functions.

Example :



class ExampleGlobalLocal

{

     static int ExGlobal; //This variable acts as a global variable

     static void ExMethod()

     {

          int Ex>0;

          System.out.println(ExOnelocal);

          System.out.println(ExGlobal);

 

     } 

}

Variables are containers whereas literals are their values. Variables have a type and a name and a value.

Example :

int a = 0

here 0 is the literal and a is the variable.

There are 8 primitive data types in java. They are

1. byte: Stores numbers from -128 to 127

2. short: Stores integers between -32768 to 32767

3. int:  Can store integers from -2^31 to (2^31)-1

4. long: The long data type can store numbers from -2^63 to (2^63)-1

5. float: This data type can store decimal numbers, single-precision 32-bit IEEE 754 floating point.

6. double: This data type can store bigger decimal values than float. Double-precision 64-bit IEEE 754 floating point can be stored.

7. boolean: Boolean data type has two possible values True and False

8. char : Stores charaters. They are stored as 16 bit unicode encode charaters

 

int : Stores integers

Scope means the areas of code where the variable is accessible. Scope is different for different types of variables. For instance variables scope is throughout the class except in static methods. For class variables scope is throughout the class and for local variables scope is inside the block.

In a java program, if a value is assigned to a variable of a different type, there are chances that the two types are not compatible.  If the data types are compatible, then Java will perform the conversion automatically known as Automatic Type Conversion, and if not then they need to be converted explicitly

C++ is platform dependant and Java is platform independent.

C++ supports operator overloading and java doesnot.

In C++ programs can be written using pointers but in Java, pointers can't be used in programs.

 

Heap for runtime data management, Stack for stroing local variables and results, Class Area for storing per class data, Program Counter for current execution address and Native Method Stack for stroing native methods for the reunning the program

For a programming language to be fully object-oriented all "things" to be objects. But in java non-object, primitive data types like boolean, byte char etc are used in Java.

The constructor is a method which initialises an object. This method has the same name as the class. It will be called automatically when an object is created.

Default constructors do not take any arguments. Whereas parameterized constructors can initialize an object with values passed as arguments.

Copy constructors are methods which takes an object as parameter and copies its characteristics to create a new object

Singleton class is a class whose constructor is private. The name is so because only one instance of the class can be created at a a  time

Overriding means changing an existing method whereas overloading is the use of same-named methods for different functions

Type safety in java means programs are not allowed to access memory locations that are not safe. In other words, each object will be assigned a particular memory chunk and each object can only access memory chunks that are valid for them

Enumerated data type or the enum is a special class in java, that represents a group of constants.

Example :

enum Languages {
  English,
  Dutch,
  Latin
}

 

float into int truncating off decimals

Differentiate between BigDecimal and float?

Constructor chaining is the process of calling a constructor from another constructor. This can be achieved in two ways using this(), for constructor chaining from the same class and using super() to achieve constructor chaining from child class to parent class

The final keyword can be used over classes to create the final classes. These classes cannot be inherited further. If another class tries to extend a final class, java throws error.

1. Final variables: When the final keyword is used over variables. The value of the variable cannot be changed once assigned

2. Final Methods: Final keyword when applied on a method, the method can never be overridden

3. Final Classes : Final keyword applied over classes, makes the them non-inheritable

The public is the access specifier for the function. The public means this method can be accessed by any other class.

static is a keyword which means that an instance of the class need not be created before referring to this method

void means this method will return nothing

main is the name of the method

The string is the type of the argument passed

arg[] the arguments that will takes the value passed through the command line while running the code

 

To convert the primitive data types like int, bool, char, etc to their respective classes like Integer, Boolean, Character, etc we can use wrapper classes. Where we can say that Integer is the wrapper class for type int.

In simple terms, collections are any group of objects in the java. Whereas Java Collections Framework is a special is a collection of interfaces and classes which helps in storing and processing the data efficiently. This framework has several useful classes that have useful functions which aids in programming.

When a value is assigned to  a variable initially. And later another value is assigned and the latter is not of the same type as the former, then to make them compatible we can convert the data type.

For example:

float num0 = 100.99;
long num1 = (long)num;

The linking of method calls to the procedure body is called binding. If this linking is done at the time of compilation then it is static binding and when the linking is done during run time it is called dynamic binding

Overloading enables a class to have same named methods performing different functions. The compiler differentiates between the two class by looking at the arguments. That means to make overloading work we have to make changes in either number or type of arguments

Whereas overiding enables the subclasses to have a method with same name as the parent class and to give its own implementation

Interfaces are class-like concepts in java, which helps in achieving full abstraction. Interfaces are defined like the class but it will not have method definitions but just signatures, also variables will be static, final and public by default.

Abstract classes are those classes which cannot have an object of its own. Rather this class can be extended. The subclass will have a general template from its parent abstract class and sub class can make their own specialisations.

The this keyword or the this pointer points to the current object of a class

The super keyword or the super pointer points to the parent object of the current instance

Lifetime of a variable indicates how long the variable resides in memory. For different types of variables, the lifetime will be different. For instance variables, the lifetime or the variable resides in memory until the corresponding object stays in memory. For class variables, the lifetime is until the program ends, and for local variables until the control leaves the corresponding block.

In java, there are three types of variables based on the scope and lifetime of variables. They are

1. Instance Varibles : A variable which is declared inside a class, but outside any methods is called instance variable.

2. Class variables :   A variable which is declared inside a class, but outside any methods and is static is called class variables

3. Local Variables :  Variables declared inside a method or a block.

Example :

public class ExVarTypes{

           int n1, n2; //Instance Varibles

           static int sum; //Class Variables

           int sum(int a, int b) //a and b are local variables

                {

                 n1 =a;

                 n2=b;

                 return a+b;

                }

}

 

All objects are stored in heaps. Whenever a new object is created using the new keyword, the object is allocated to a heap. When a new variable is declared only reference is created and when using the new keyword a heap is allocated.

Serialization is a mechanism of converting an object into a byte stream. Whereas deserialization is the reverse process where the byte stream is used to recreate the corresponding object in memory.

When a class defined inside another class, such a class is called a nested class.

Syntax :

class ClassA

{

            Class TheNestedClass

             {

              }

}

 

 

Removing objects from memory which are no more in use is called garbage collection. In java, it is done automatically. The garbage collector thread periodically checks the run-time heap and if abandoned objects (objects do not have live references) are found, the garbage collector threads first call the finalize() methods to clean up the object and then sweeps the objects out of memory.

The heap structure in java is classified as

1.Younger Generation: The younger generation is further classified as Eden space and survivor spaces. Once an object is stored it is stored in the Eden space. When younger space fills minor garbage collection runs, the survived objects are moved to survivor spaces.

2. Older Geneation: The objects in the younger spaces, as time passes get older and after a threshold is moved to the older generation. When the older generation gets filled a major garbage collection is done.

3.Permananant Generation contains meta data required by the java virtual machine

3.

When an object of a class is created, we say that the class is instantiated.

1.Single Inheritance: Subclasses inherit the features of one superclass

2.Multilevel Inheritance: A derived class will be inheriting a base class and as well as the derived class also act as the base class to other class

3.Hierarchial Inheritance: A class serves as a base class for more than one subclass

4.Mutiple Inheritance: A class can have more than one superclass and inherit features from all parent classes

5.Hybrid Inheritance:  It is a combination of two or more of the above types of inheritance

Encapsulation is the process of binding together data and operations to a single unit called class. The advantages are,

  • Data Hiding: The user will have no idea about the inner implementation of the class.
  • Increased Flexibility: The access of the variables can be tuned as needed
  • Reusability: Encapsulation also improves the re-usability and easy to change with new requirements.
  • Testing code is easy: Encapsulated code is easy to unit test.

Polymorphism is the concept of the same entity or name existing in different forms.

In Java, two types of polymorphism are there,

1. Compile time polymorphism : Also called static polymorphism. The method overloading and operator overloading comes under this category.

2, Runtime polymorphism: The overriding comes in this category because the function call to the overriden method is only resolved during run time.

It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding.

Data abstraction is a concept where only the essential details are displayed to the user. The trivial details are not displayed to the user. In java abstraction is achieved by interfaces and abstract classes

An abstract method is declared without an implementation. An abstract method should be redefined or overridden in the subclass

Java’s access modifiers are public, private, and protected. public: When a member of a class is modified by the public modifier, then that member can be accessed by any other code.

private: When a member of a class is specified as private, then that member can only be accessed by other members of the same class.
protected:The members declared as protected are accessible within the same package or subclasses in other packages.

When no access modifier is specified for a class, the members are having the default access modifier. They are only accessible within the same package.

The non-access modifiers are markers used to provide information about entities. These entities can be classes, methods, variables or constructors. There are 7 non- access modifiers in Java, they are

1. Static :can be accessed before any objects of its class are created.

2. Final : When applied to variables creates constant variables, when applied to methods prevents method overiding and when applied to class prevent inheritance.

3.Abstract : Used to create abstract classes and methods

4. Synchronised : To make sure only one thread can access a resource at a given point of time.

5. Transient : Is used when we dont want to  save value of a particular variable in a file

6. Volatile : Used to make class thread safe.

7. Native : to indicate that the method is implemented in native code using (Java Native Interface.

 

Widening is nothing but Automatic Type Conversion itself. When two types are compatible and the value assigned is from a lower data type to a higher data type java converts the java converts the type from lower to higher automatically and hence the name widening.

When in a java program a value of higher data type is assigned to a variable of lower data type, the conversion won't happen automatically. In such cases explicit type conversion to be applied. It is also called narrowing.