blog banner
 

1. What if we call run() directly without start() ?

When we call the start() method on a thread object, the start() method starts a new thread of execution by creating a new call stack for the thread .The start() causes this thread to begin execution and the Java Virtual Machine calls the run() method of this thread.

What if we call run() instead of start() : Though this is legal, but the run() method goes into the current call stack instead of creating a new call stack.

The start method makes sure the code runs in a new thread context. If you called run directly, then it would be like an ordinary method call and it would run in the context of the current thread instead of the new one. The start method contains the special code to trigger the new thread; run obviously doesn't have that ability because you didn't include it when you wrote the run method.

So if we dont declare start() and call run() directly then multi threading will not be acchieved as run() will always be called from same thread.
 

2. What is the difference between start() and run() in java ?

The run() method comes form the Runnable interface but the start() method is only declared in the Thread class. Since java.lang.Thread class implements Runnable interface, you can access the run() method from an instance of Thread class. I have create following Java program to demonstrate you the difference of calling start() method on thread and calling the run() method directly from the main thread.

In both the cases the run() method will be called but when you call the start() method than it will be called by a new thread. On the other hand if you call the run() method directly than it will be called on the same thread i.e. main thread in our case. Don't believe? run the code and see by yourself. Let's see the example now.
 

3. Explain Java Thread control ? Or, What is Suspending, Resuming, and Stopping Threads in JAVA ?

suspend() : This method puts a thread in suspended state and can be resumed using resume() method. If you want to stop the thread execution and start it again when a certain event occurs. In this case, suspend() method allows a thread to temporarily cease execution.

stop() : This method stops a thread completely.This method terminates the thread execution. Once a thread is stopped, it cannot be restarted with the start() method, because stop() method terminates the execution of a thread.

Resume() : This method resumes a thread which was suspended using suspend() method. resume() method works with suspend() method. Resume() method allows the suspended thread to start again.
 

4. What’s the order of call of constructors in inheritiance?

In case of inheritance, when a new object of a derived class is created, first the constructor of the super class is invoked and then the constructor of the derived class is invoked.
 

5. What’s the base class of all exception classes?

In Java, Java.Lang.throwable is the super class of all exception classes and all exception classes are derived from this base class.
 

6. Can we cast any other type to Boolean Type with type casting?

No, we can neither cast any other primitive type to Boolean data type nor can cast Boolean data type to any other primitive data type.
 

7. What is a Local class in Java? Or, What is local inner Class in Java ?

In Java, 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.

A local class is declared locally within a block of Java code, rather than as a member of a class. Typically, a local class is defined within a method, but it can also be defined within a static initializer or instance initializer of a class. Because all blocks of Java code appear within class definitions, all local classes are nested within containing classes. For this reason, local classes share many of the features of member classes. It is usually more appropriate, however, to think of them as an entirely separate kind of inner class. A local class has approximately the same relationship to a member class as a local variable has to an instance variable of a class.

The defining characteristic of a local class is that it is local to a block of code. Like a local variable, a local class is valid only within the scope defined by its enclosing block.

Example :

public class localInner1{

private int data=30;
void display(){

class Local{

void msg(){

System.out.println(data);

}

}

Local l=new Local();
l.msg();

}
public static void main(String args[]){

localInner1 obj=new localInner1();
obj.display();

}

}

Output :

30
 

8. I have multiple constructors defined in a class. Is it possible to call a constructor from another constructor’s body?

If a class has multiple constructors, it’s possible to call one constructor from the body of another one using this().
 

9. How objects are stored in Java?

In java, each object when created gets a memory space from a heap. When an object is destroyed by a garbage collector, the space allocated to it from the heap is re-allocated to the heap and becomes available for any new objects.
 

10. How can we find the actual size of an object on the heap?

In java, there is no way to find out the exact size of an object on the heap.
 

11. I want my class to be developed in such a way that no other class (even derived class) can create its objects. How can I do so?

If we declare the constructor of a class as private, it will not be accessible by any other class and hence, no other class will be able to instantiate it and formation of its object will be limited to itself only.
 

12. How can an exception be thrown manually by a programmer?

In order to throw an exception in a block of code manually, throw keyword is used. Then this exception is caught and handled in the catch block.
 

13. How destructors are defined in Java?

In Java, there are no destructors defined in the class as there is no need to do so. Java has its own garbage collection mechanism which does the job automatically by destroying the objects when no longer referenced.
 

14. What are the two environment variables that must be set in order to run any Java programs?

Java programs can be executed in a machine only once following two environment variables have been properly set:

  • PATH variable
  • CLASSPATH variable

 

15. Can we use a default constructor of a class even if an explicit constructor is defined?

Java provides a default no argument constructor if no explicit constructor is defined in a Java class. But if an explicit constructor has been defined, default constructor can’t be invoked and developer can use only those constructors which are defined in the class.
 

16. How can we use primitive data types as objects?

Primitive data types like int can be handled as objects by the use of their respective wrapper classes. For example, Integer is a wrapper class for primitive data type int. We can apply different methods to a wrapper class, just like any other object.
 

17. Which types of exceptions are caught at compile time?

Checked exceptions can be caught at the time of program compilation. Checked exceptions must be handled by using try catch block in the code in order to successfully compile the code
 

18. Does Java has pointers ? Justify the statement " Java does not use the concept of pointer"

The truth is : Java has references, but not pointers.

Java uses referencing in the sense of variables that store references to data in memory. All variables of Object types in Java are pointers in this sense. However, the Java language does not allow arithmetic operations on the values of pointers, like you'd be able to do in a language like C. We can perform additional operations like arithmetic operation on reference which is possible with pointers. This makes java simpler, neat & less error prone programming language.

Java does not have pointers. This was an intentional decision by the creators of Java. Pointers support pointer arithmetic and this makes them a kind of unsafe. Because they provide the programmer with an access level that is much more than needed. However, references provide an handle to the object through a much more abstract hided implementation.We can do many additional operations on pointers which make the program crtical, confusing & error prone. Creators of java wanted to make this language easy to build, neat & simple. Usage of reference instead of pointer helped java to achieve its' goals.
 

19. What is the difference between reference & pointers in Java ?

1. A pointer is a variable which stores the address of another variable. A reference is a variable which refers to another variable.

2. References store an address. That address is the address in memory of the object. So, when a class is declared like so: "PersonClass y = new PersonClass();", the "y" variable actually stores an address in memory. If you were to look at that address in memory you would see the details of the PersonClass object. Pointers in c / C++, however, point directly to the object.

3. Pointers support pointer arithmetic and this makes them a kind of unsafe. Because they provide the programmer with an access level that is much more than needed. However, references provide an handle to the object through a much more abstract hided implementation.

4. Pointers are less strongly typed and references are more strongly typed. By this I mean the code is much simple in case of references and slightly less formal in case of pointers. You need to make use of reinterpret_cast kind of things to use pointers casts and on the other hand, references support easy casts of the kind of primitive kind of casts in "C".

5. Pointers are unsafe and references are safe. If you have an option between the two select references. In languages like C#, you have this freedom.

6. Pointers exists in C/C++ and references exist in Java. Do not confuse references in C/C++ with references in Java. References in C/C++ is a kind of synonym used for the rvalue of a pointer in C/C++.
 

20. What is ClassLoader in Java?

All class files in application are not loaded into memory at startup, but are loaded on demand as needed by the program, this loading of class is done by ClassLoader. ClassLoader is a part of JVM that loads classes into memory. ClassLoader is an abstract class which is the part of java.lang package.

When a Java program is converted into .class file by Java compiler which is collection of byte code class loader is responsible to load that class file from file system,network or any other location. This class loader is nothing but also a class from which location they are loading the class according to the type of  class loaders 
 

21. What are the types of classloader ?

1.Bootstrap
2.Extension
3.System class loader .

Bootstrap Class Loader

It is the Super Class Loader. It doesn’t have any parent ClassLoader. It loads the Core classes of Java like class in java.lang, java.util package.

Extension Class Loader

Extension ClassLoader will load the classes in JAR files in the lib/ext directory of the JRE, and in the system-wide, platform-specific extension directory. Bootstrap ClassLoader will be the parent of Extension ClassLoader. Developer can manually add jars in ext folder to get it loaded by Extension ClassLoader.

System Class Loader

System ClassLoader will load the classes in classpath(java.class.path property). Extension ClassLoader works as the parent of System ClassLoader. Default value of the classpath is current directory but this value can be changed in different way.

  • Setting the CLASSPATH enviornment variable.
  • Value providing by -classpath or -cp command-line options.

 

22. How Classloader works ?

An application might require different classes to function properly at runtime, Whenever an application requires a class at runtime, ClassLoader will look for the given class name and if found it will load it in memory. Once provided the name of class to load, ClassLoader will try to locate data that constitue the definition of class at different locations.

Location searched by the ClassLoader will be in given order.

  1. First look for the classes in JAR files in the lib/ext directory of the JRE, and in the system-wide, platform-specific extension directory.
  2. Second look for the class in classpath(java.class.path property). Default value of the classpath is current directory but this value can be changed in different way.

 

23. What is singleton in JAVA?

Sometimes it's appropriate to have exactly one instance of a class. The Singleton's purpose is to control object creation, limiting the number of obejcts to one only. Since there is only one Singleton instance, any instance fields of a Singleton will occur only once per class, just like static fields. Singletons often control access to resources such as database connections or sockets.

For example, if you have a license for only one connection for your database or your JDBC driver has trouble with multithreading, the Singleton makes sure that only one connection is made or that only one thread can access the connection at a time.

Example :

public class Singleton {

// Private constructor prevents instantiation from other classes
private Singleton() {}

/**
* SingletonHolder is loaded on the first execution of Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/

private static class SingletonHolder {

private static final Singleton INSTANCE = new Singleton();

}

public static Singleton getInstance() {

return SingletonHolder.INSTANCE;

}

}
 

24. What is classic Singleton design pattern ?

The ClassicSingleton class maintains a static reference to the lone singleton instance and returns that reference from the static getInstance() method.

Here ClassicSingleton class employs a technique known as lazy instantiation to create the singleton; as a result, the singleton instance is not created until the getInstance() method is called for the first time. This technique ensures that singleton instances are created only when needed.

Following implementation shows a classic Singleton design pattern: The above example will also work, here is another one

public class ClassicSingleton {

private static ClassicSingleton instance = null;
private ClassicSingleton() {

// Exists only to defeat instantiation.

}
public static ClassicSingleton getInstance() {

if(instance == null) {

instance = new ClassicSingleton();

}
return instance;

}

}
 

25. What is double checked locking in Singleton?

Singleton means we can create only one instance of that class,in term of singleton DCL(double checked locking) is the way to ensure that at any cost only one instance is created in multi-threaded environment its possible that simultaneously two thread trying to create instance of singleton class in that situation we cant sure that only one instance is created so avoid this situation using double checked locking by using synchronized block where we creating the object.

Example :

class SingletonClass {

private DCL dcl = null;
public DCL getDCL() {

if (dcl == null) {

synchronized {

if (dcl == null)
dcl = new DCL();

}

}
return dcl;

}

}
 

26. Why we need Singleton design pattern ?

The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:

  • Ensure that only one instance of a class is created
  • Provide a global point of access to the object
  • Allow multiple instances in the future without affecting a singleton class's clients

 

27. What is volatile keyword in java?

The Java volatile keyword is used to mark a Java variable as "being stored in main memory". More precisely that means, that every read of a volatile variable will be read from the computer's main memory, and not from the CPU cache, and that every write to a volatile variable will be written to main memory, and not just to the CPU cache. The Java volatile keyword guarantees visibility of changes to variables across threads.

Example :

class GoodExample {

private static volatile int temperature;

//Called by some other thread than main
public static void todaysTemperature(int temp){

// This operation is a single operation, so you
// do not need compound atomicity
temperature = temp;

}

public static void main(String[] args) throws Exception{

while(true){

Thread.sleep(2000);
System.out.println("Today's temperature is "+temperature);

}

}

}

Now, why can't you just use private static int temperature? In fact you can (in the sense that that your program won't blow up or something), but the change to temperature by the other thread may or may not be "visible" to the main thread.

Basically this means that it is even possible that your app. keeps writing Today's temperature is 0 forever if you don't use volatile (in practice, the value tends to become eventually visible. However, you should not risk not using volatile when necessary, since it can lead to nasty bugs (caused by in-completely constructed objects etc.).

If you put volatile keyword on something that doesn't need volatile, it won't affect your code's correctness (i.e. the behaviour will not change). In terms of performance, it will depend on the JVM implementation. In theory you might get a tiny performance degradation because the compiler can't do reordering optimisations, have to invalidate CPU cache etc., but then again the compiler could prove that your field cannot ever be accessed by multiple threads and remove the effect of volatile keyword completely and compile it to identical instructions.
 

28. Why dont we use synchronized keyword instead of using volatile ? What is the advantage of using volatile ?

You can and it will behave correctly. Anything that you can with volatile can be done with synchronized, but not vice versa. There are two reasons you might prefer volatile if you can:

Less bug prone: This depends on the context, but in many cases using volatile is less prone to concurrency bugs, like blocking while holding the lock, deadlocks etc.

More performant: In most JVM implementations, volatile can have significantly higher throughput and better latency. However in most applications the difference is too small to matter.
 

29. When to use volatile in JAVA ?

1) Any variable which is shared between multiple threads should be made variable, in order to ensure that all thread must see the latest value of the volatile variable.

2) A signal to compiler and JIT to ensure that compiler does not change ordering or volatile variable and moves them out of synchronized context.

3) You want to save the cost of synchronization as volatile variables are less expensive than synchronization.
 

30. What is transient variable in Java?

transient variables are never serialized in java.

It marks a member variable not to be serialized when it is persisted to streams of bytes. When an object is transferred through the network, the object needs to be 'serialized'. Serialization converts the object state to serial bytes. Those bytes are sent over the network and the object is recreated from those bytes. Member variables marked by the java transient keyword are not transferred, they are lost intentionally.

Example

public class Foo implements Serializable
{

private String saveMe;
private transient String dontSaveMe;
private transient String password;
...

}

In above example dontSaveMe & password are never get serialize as they are declare as a transient variables.
 

31. Difference between transient and volatile variable in Java?

    1. Transient variable : transient keyword is used with those instance variable which will not participate in serialization process.we cannot use static with transient variable as they are part of instance variable.
    2. Volatile variable : volatile keyword is used with only variable in Java and it guarantees that value of volatile variable will always be read from main memory and not from Thread's local cache, it can be static.
    3. transient keyword can not be used along with static keyword but volatile can be used along with stati
    4. transient variables are initialized with default value during de-serialization and there assignment or restoration of value has to be handled by application code.

 

32. Difference between Serializable and Externalizable in Java?

Serialization is a default process of serializing or persisting any object's state in Java. It's triggered by implementing Serializable interface which is a marker interface (an interface without any method). While Externalizable is used to customize and control default serialization process which is implemented by application. Main difference between these two is that Externalizable interface provides complete control to the class implementing the interface whereas Serializable interface normally uses default implementation to handle the object serialization process.

Externalizable interface has two method writeExternal(ObjectOutput) and readExternal(ObjectInput) method which are used to handle customized object serialize process and in terms of performance its good because everything is under control.
 

33. Difference between PATH and Classpath in Java?

PATH is a environment variable in Java which is used to help Java program to compile and run.To set the PATH variable we have to include JDK_HOME/bin directory in PATH environment variable and also we cannot override this variable. On the other hand, ClassPath variable is used by class loader to locate and load compiled Java codes stored in .class file. We can set classpath we need to include all those directory where we have put either our .class file or JAR file which is required by your Java application,also we can override this environment variable.
 

34. Difference between extends Thread and implements Runnable in Java ?

You cannot extend more than one class, but you can implement more than one interface. If you extend Thread class just to override run() method, you lose power of extending another class, while in case of Runnable, you can still implement another interface or another class. One more difference is that Thread is abstraction of independent path of execution, while Runnable is abstraction of independent task, which can be executed by any thread. That's why it's better to implement Runnable than extending Thread class in Java.
 

Admin Team


0 Respond



Written
Exam Questions
BLOG Posts
For study materials
Job Walk-In
Updates across India
Interview round
Questions
Interview or procedure
Experiences
Files
For study materials
Please LIKE our page to Get regular JOB WALK-IN UPDATES across India and STUDY MATERIALS on facebook news feed.