/** * Created by PhpStorm. * User: Rahul * Date: 12/8/2016 * Time: 8:09 PM */ Core Java Interview Question2

Core Java - Interview Question for fresher Level-1(begineer)

What is the difference between procedural and object-oriented programs?

a) In procedural program, programming logic follows certain procedures and the instructions are executed one after another. In OOP program, unit of program is object, which is nothing but combination of data and code.

b) In procedural program, data is exposed to the whole program whereas in OOPs program, it is accessible with in the object and which in turn assures the security of the code.

What are Class, Constructor and Primitive data types?

Class is a template for multiple objects with similar features and it is a blue print for objects. It defines a type of object according to the data the object can hold and the operations the object can perform.

Constructor is a special kind of method that determines how an object is initialized when created. Primitive data types are 8 types and they are: byte, short, int, long, float, double, boolean, char.

Read more on Classes and Object with Example :-

What is an Object and how do you allocate memory to it?

- Object is an instance of a class and it is a software unit that combines a structured set of data with a set of operations for inspecting and manipulating that data. When an object is created using new operator, memory is allocated to it.

Difference between Stack vs Heap in Java or explain java memory model

stack is also a data structure which is used to store elements in LIFO(Last In First out) order and available in Java API as java.util.Stack. Java uses both stack and heap memory for different needs.

differences between stack and heap memory in Java :-

What is the difference between constructor and method?

- constructor is a special type of method,Constructor will be automatically invoked when an object is created whereas method has to be called explicitly.

Constructors and methods differ in three aspects of the signature: modifiers, return type, and name.

What is OOPs?

Object oriented programming organizes a program around its data, i. e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

Read more on OOP

What are Encapsulation, Inheritance and Polymorphism?

Encapsulation is the mechanism that binds together code and data it manipulates and keeps both safe from outside interference and misuse.

Inheritance is the process by which one object acquires the properties of another object.

Polymorphism is the feature that allows one interface to be used for general class actions.

What are methods and how are they defined?

- Methods are functions that operate on instances of classes in which they are defined.

Objects can communicate with each other using methods and can call methods in other classes. Method definition has four parts.

They are name of the method, type of object or primitive type the method returns, a list of parameters and the body of the method.

A method’s signature is a combination of the first three parts mentioned above.

What is the use of bin and lib in JDK?

- Bin contains all tools such as javac, appletviewer, awt tool, etc.,

whereas lib contains API and all packages.

What is Type casting?

Casting is used to convert the value of one type to another.

In Java, you will get a compilation error if you try to assign a double value of to an int variable. This is because the fractional part would be lost. The compiler issues an error "possible loss in precision".

Explicit Type-Casting (narrowing conversion) :-
A data type of higher size (occupying more memory) cannot be assigned to a data type of lower size. This is not done implicitly by the JVM and requires explicit casting.
a casting operation to be performed by the programmer. The higher size is narrowed to lower size.

Implicit Type-Casting in Assignment (widening conversion) :-
A data type of lower size (occupying less memory) is assigned to a data type of higher size. This is done implicitly by the JVM.
The lower size is widened to higher size. This is also named as automatic type conversion.

Read more about type-casting with Example

What is the difference between an argument and a parameter?

- While defining method, variables passed in the method are called parameters.

While using those methods, values passed to those variables are called arguments.

What are different types of access modifiers?

- public: Any thing declared as public can be accessed from anywhere. private: Any thing declared as private can’t be seen outside of its class. protected: Any thing declared as protected can be accessed by classes in the same package and subclasses in the other packages. default modifier : Can be accessed only to classes in the same package.

What is final, finalize() and finally?

final : final keyword can be used for class, method and variables.

finalize() : finalize() method is used just before an object is destroyed and can be called just prior to garbage collection.

finally : finally, a key word used in exception handling, creates a block of code that will be executed after a try/catch block has completed and before the code following the try/catch block.
The finally block will execute whether or not an exception is thrown.

For example, if a method opens a file upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism.
This finally keyword is designed to address this contingency.

What is UNICODE?

- Unicode is used for internal representation of characters and strings and it uses 16 bits to represent each other.

Read more on Internal Data representation

What is Garbage Collection and how to call it explicitly?

- When an object is no longer referred to by any variable, java automatically reclaims memory used by that object.

This is known as garbage collection. System. gc() method may be used to call it explicitly.

What are Transient and Volatile Modifiers?

- Transient: The transient modifier applies to variables only and it is not stored as part of its object’s Persistent state.
Transient variables are not serialized.

Volatile: Volatile modifier applies to variables only and it tells the compiler that the variable modified by volatile can be changed unexpectedly by other parts of the program.

What is method overloading and method overriding?

- Method overloading: When a method in a class having the same method name with different arguments is said to be method overloading.

Method overriding : When a method in a class having the same method name with same arguments is said to be method overriding. difference between overloading and overriding

What is meant by Inheritance and what are its advantages?

- Inheritance is the process of inheriting all the features from a class.

The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

What is the difference between this() and super()?

this() can be used to invoke a constructor of the same class


super() can be used to invoke a super class constructor.

What is the difference between superclass and subclass?

- A super class is a class that is inherited whereas sub class is a class that does the inheriting.

What are inner class and anonymous class?

Inner class : classes defined in other classes, including those defined in methods are called inner classes. An inner class can have any accessibility including private.

Anonymous class : Anonymous class is a class defined inside a method without a name and is instantiated and declared in the same place and cannot have explicit constructors.

What is a package?

A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

What is interface and its use?

Interface is similar to a class which may contain method’s signature only but not bodies and it is a formal set of method and constant declarations that must be defined by the class that implements it.

Interfaces are useful for:

What is an abstract class?

An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

What is the difference between Integer and int?

- a) Integer is a class defined in the java. lang package, whereas int is a primitive data type defined in the Java language itself.

Java does not automatically convert from one to the other.

b) Integer can be used as an argument for a method that requires an object, whereas int can be used for calculations.

What is a cloneable interface and how many methods does it contain?

- It is not having any method because it is a TAGGED or MARKER interface.

What is the difference between abstract class and interface?

What is Marker interface? How is it used in Java?

The marker interface is a design pattern, used with languages that provide run-time type information about objects.

It provides a way to associate metadata with a class where the language does not have explicit support for such metadata. To use this pattern, a class implements a marker interface, and code that interact with instances of that class test for the existence of the interface. Whereas a typical interface specifies methods that an implementing class must support, a marker interface does not do so. The mere presence of such an interface indicates specific behavior on the part of the implementing class. There can be some hybrid interfaces, which both act as markers and specify required methods, are possible but may prove confusing if improperly used. Java utilizes this pattern very well and the example interfaces are

java.io.Serializable -
Serializability of a class is enabled by the class implementing the java.io.Serializable interface.
The Java Classes that do not implement Serializable interface will not be able to serialize or deserializ their state.
All subtypes of a serializable class are themselves serializable.
The serialization interface has no methods or fields and serves only to identify the semantics of being serializable.

java.rmi.Remote -
The Remote interface serves to identify interfaces whose methods may be invoked from a non-local virtual machine.
Any object that is a remote object must directly or indirectly implement this interface.
Only those methods specified in a "remote interface", an interface that extends java.rmi.Remote are available remotely.

java.lang.Cloneable -
A class implements the Cloneable interface to indicate to the Object.clone() method that it is legal for that method to make a field-for-field copy of instances of that class.
Invoking Object's clone method on an instance that does not implement the Cloneable interface results in the exception CloneNotSupportedException being thrown.

javax.servlet.SingleThreadModel -
Ensures that servlets handle only one request at a time. This interface has no methods.

java.util.EvenListener -
A tagging interface that all event listener interfaces must extend.

The "instanceof" keyword in java can be used to test if an object is of a specified type.
So this keyword in combination with Marker interface can be used to take different actions based on type of interface an object implements.

Can you have an inner class inside a method and what variables can you access?

Yes, we can have an inner class inside a method and final variables can be accessed.

What is immutable object in Java? Can you change values of a immutable object?

A Java object is considered immutable when its state cannot change after it is created. Use of immutable objects is widely accepted as a sound strategy for creating simple, reliable code. Immutable objects are particularly useful in concurrent applications. Since they cannot change state, they cannot be corrupted by thread interference or observed in an inconsistent state. java.lang.String and java.lang.Integer classes are the Examples of immutable objects from the Java Development Kit. Immutable objects simplify your program due to following characteristics :

How to create a immutable object in Java? Does all property of immutable object needs to be final?

To create a object immutable You need to make the class final and all its member final so that once objects gets crated no one can modify its state.

You can achieve same functionality by making member as non final but private and not modifying them except in constructor. Also its NOT necessary to have all the properties final since you can achieve same functionality by making member as non final but private and not modifying them except in constructor.

What is difference between String, StringBuffer and StringBuilder? When to use them?

The main difference between the three most commonly used String classes as follows.

Criteria to choose among String, StringBuffer and StringBuilder

Why String class is final or immutable?

It is very useful to have strings implemented as final or immutable objects. Below are some advantages of String Immutability in Java

Is Java Pass by Reference or Pass by Value?

When calling a method, you need to provide arguments, which must be given in the same order as their respective parameters in the method specification. This is known as parameter order association.

Please refer these article - here we explain both Pass by Reference and Pass by Value with example

Please Refer this article for Example - pass by value Please Refer this article for Example - pass by reference

What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?

Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred.

Finally block is NOT called in following conditions

Why main() in java is declared as public static void main? What if the main method is declared as private?

Public - main method is called by JVM to run the method which is outside the scope of project therefore the access specifier has to be public to permit call from anywhere outside the application

static - When the JVM makes are call to the main method there is not object existing for the class being called therefore it has to have static method to allow invocation from class.

void - Java is platform independent language therefore if it will return some value then the value may mean different to different platforms so unlike C it can not assume a behavior of returning value to the operating system.

If main method is declared as private then - Program will compile properly but at run-time it will give "Main method not public." error.

What is the difference between ArrayList and vector?

Array is a set of related data type and static whereas vector is a growable array of objects and dynamic.

1) Synchronization - ArrayList is not thread-safe whereas Vector is thread-safe.
In Vector class each method like add(), get(int i) is surrounded with a synchronized block and thus making Vector class thread-safe.

2) Data growth - Internally, both the ArrayList and Vector hold onto their contents using an Array. When an element is inserted into an ArrayList or a Vector, the object will need to expand its internal array if it runs out of room.
A Vector defaults to doubling the size of its array, while the ArrayList increases its array size by 50 percent.

What is the difference between exception and error?

The exception class defines mild error conditions that your program encounters. Exceptions can occur when trying to open the file, which does not exist, the network connection is disrupted, operands being manipulated are out of prescribed ranges, the class file you are interested in loading is missing. The error class defines serious error conditions that you should not attempt to recover from. In most cases it is advisable to let the program terminate when such an error is encountered.

What is the difference between process and thread?

A process is an execution of a program but a thread is a single execution sequence within the process.
A process can contain multiple threads. A thread is sometimes called a lightweight process.
A JVM runs in a single process and threads in a JVM share the heap belonging to that process. That is why several threads may access the same object. Threads share the heap and have their own stack space.

This is how one thread’s invocation of a method and its local variables are kept thread safe from other threads. But the heap is not thread-safe and must be synchronized for thread safety.
When you execute something synchronously, you wait for it to finish before moving on to another task.
When you execute something asynchronously, you can move on to another task before it finishes.

What is multithreading and what are the methods for inter-thread communication and what is the class in which these methods are defined?

Multithreading is the mechanism in which more than one thread run independent of each other within the process.

wait (), notify () and notifyAll() methods can be used for inter-thread communication and these methods are in Object class.

wait() : When a thread executes a call to wait() method, it surrenders the object lock and enters into a waiting state.

notify() or notifyAll() : To remove a thread from the waiting state, some other thread must make a call to notify() or notifyAll() method on the same object.

What is the class and interface in java to create thread and which is the most advantageous method?

Thread class and Runnable interface can be used to create threads and using Runnable interface is the most advantageous method to create threads because we need not extend thread class here.

What are the states associated in the thread?

Thread contains ready, running, waiting and dead states.

What is synchronization?

Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.

When you will synchronize a piece of your code?

When you expect your code will be accessed by different threads and these threads may change a particular data causing data corruption.

What is deadlock?

When two threads are waiting each other and can’t precede the program is said to be deadlock.

What is daemon thread and which method is used to create the daemon thread?

Daemon thread is a low priority thread which runs intermittently in the back ground doing the garbage collection operation for the java runtime system. setDaemon method is used to create a daemon thread.

/** *