What is the purpose of JAVA_HOME and PATH variables in Java ?
Why wait(), notify() and notifyAll() methods are present in Object class rather than in java.lang.Thread class?
A wait can be "woken up" by another process calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not:
(On the same obj object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll if more than one thread is waiting on the monitor - this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the waitis in a synchronized block) and carry on - the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait on Object itself (i.e. you wait on an object's monitor) whereas you call sleep on Thread.
The JAVA_HOME variable is used to know where the JDK exist in your system.
The PATH variable is used by system command prompt. When we execute a program, our system will look for its location. It will scan all directories included in the PATH, and look for the program we are executing.
This means that when we type "java", or "javac" at the command prompt, our system will look into %JAVA_HOME%\bin", find the command and execute it. If we don't set your PATH properly, we'll end up with an error message like "Command not found".
How to check, whether JDK configured properly or not in local system?
Open command prompt, and run the command "java -version". It should display the java version as below image. If an error like "Command not found" is displayed, check your PATH variables.
What is final in Java?
final Makes it impossible to extend a class, override a method, or reinitialize a variable. More details
What is DaemonThread in java?
A daemon thread is a thread that is considered doing some tasks in the background like handling requests or various chronjobs that can exist in an application.
When your program only have daemon threads remaining it will exit. That's because usually these threads work together with normal threads and provide background handling of events.
You can specify that a Thread is a daemon one by using setDaemon method, they usually don't exit, neither they are interrupted.. they just stop when application stops. More details
What is mutable object and immutable object?
Immutable : Immutable objects can be used to define values or attributes that you don't want to be changed.we can consider the string object as immutable objects, because we can't alter the content of the string object.
Mutable : We can change/alter the value of the object. ( Ex. StringBuffer). More details
Is Java use Pass-by-value or Pass-by-reference?Mutable : We can change/alter the value of the object. ( Ex. StringBuffer). More details
There is no Pass-by-reference concept in java, everything pass-by-value.
Java only supports pass by value. More details..
What is the Use of Heap in java ?Java only supports pass by value. More details..
The Java virtual machine has a heap that is shared among all Java virtual machine threads.The heap is the runtime data area from which memory for all class instances and arrays is allocated.
The heap is created on virtual machine start-up and objects are created on heap irrespective of there scope e.g. local or member variable.
If a computation requires more heap than actual heap available on storage management, the JVM throws an OutOfMemoryError.
What is the finalize method do?The heap is created on virtual machine start-up and objects are created on heap irrespective of there scope e.g. local or member variable.
If a computation requires more heap than actual heap available on storage management, the JVM throws an OutOfMemoryError.
Before removing an object from memory Garbage collection thread invokes finalize () method of that object and gives an opportunity to perform any sort of cleanup required.
Why wait(), notify() and notifyAll() methods are present in Object class rather than in java.lang.Thread class?
Every object in Java is automatically extended from the Java class hierarchy root (Object class) and has single lock. If multiple threads are synchronized on any single object’s lock, then these threads need to be coordinated on that object’s lock and this is the situation when the wait(), notify() and notifyAll() methods are come into the scenes.
Thus, every object in Java need to be equipped with three thread related methods: wait(), notify(), notifyAll(). To solve this problem, Object class is the only one place to define these three methods.
What is 'super' and 'this' keywords in java?.Thus, every object in Java need to be equipped with three thread related methods: wait(), notify(), notifyAll(). To solve this problem, Object class is the only one place to define these three methods.
'super' refers to the parent(super class) of the current class, used to invoke super class constructor or method.
'this' refers to a reference of the current class. used to invoke current class constructor or method. More details..
Does Java supports Operator Overloading?
'this' refers to a reference of the current class. used to invoke current class constructor or method. More details..
There is no operator overloading in Java, means the programmer cann't implement operator overloading, but it is in built available in Java language.
Have a look at the following example
2 + 5
"ram" + "babu"
These two expressions can be processed by java language. The same + symbol is used to add two integral numbers as well as to add two strings. The + operator is overloaded to operate on integrals and strings. This applies to java language as well. Hence, operator overloading is there in Java, but in built. It cannot be extended by the programmer as you can do in C++.
Does Java supports multiple inheritance?Have a look at the following example
2 + 5
"ram" + "babu"
These two expressions can be processed by java language. The same + symbol is used to add two integral numbers as well as to add two strings. The + operator is overloaded to operate on integrals and strings. This applies to java language as well. Hence, operator overloading is there in Java, but in built. It cannot be extended by the programmer as you can do in C++.
No, Java doesn't support multiple inheritance because to avoid ambiguity problem and complexity of multiple inheritance. More details
Why the main method in Java should be as public static void main(String[] args) ?
The signature of the main method is specified in the Java Language Specifications section 12.1.4 and clearly states:
The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
The method signature can therefore be:
public static void main(String[] args)
public static void main(String... args)
note that the varargs version (...) is only valid from Java 5. More details
What is the difference between a static and an instance variable in java?The method main must be declared public, static, and void. It must specify a formal parameter (§8.4.1) whose declared type is array of String.
The method signature can therefore be:
public static void main(String[] args)
public static void main(String... args)
note that the varargs version (...) is only valid from Java 5. More details
Static members are those which are at the class or type level. And there will be only one copy of it is available to the all instances of that class type.
And for non Static (instance) members will have different copies for different instances. More details
Difference between ClassNotFoundException and NoClassDefFoundError?And for non Static (instance) members will have different copies for different instances. More details
The difference between the two is that one is an Error and the other is an Exception. With NoClassDefFoundError is an Error and it arises from the Java Virtual Machine having problems finding a class it expected to find. A program that was expected to work at compile-time can't run because of class files not being found, or is not the same as was produced or encountered at compile-time. This is a pretty critical error, as the program cannot be initiated by the JVM.
On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime. More details.
Is it possible to override static Method?.On the other hand, the ClassNotFoundException is an Exception, so it is somewhat expected, and is something that is recoverable. Using reflection is can be error-prone (as there is some expectations that things may not go as expected. There is no compile-time check to see that all the required classes exist, so any problems with finding the desired classes will appear at runtime. More details.
No, You can not override the static method because as per the nature of static method it belongs to specific class, but you can redeclare it in to the subclass and the subclass doesn't know anything about the parent class static methods, because static specific to only that class in which it has been declared. More details..
Is Null Keyword?
No. As per java specification Null is literal and A null literal is always of the null type.
Are true and false keywords?.
No. As per java specification The boolean type has two values, represented by the boolean literals true and false.
What exception is thrown if you try to serialize an object that doesn't implement the "serializable" interface?.
java.io.NotSerializableException.
If the object members are not of basic java datatypes(ex Some Class object variables) which doesn't implements Serializable interface it will through an exception (java.io.NotSerializableException)
How can you tell the compiler to not serialize an object?.
By using keyword transient or static.
When the object is serialized the jvm looks for all the variables which can be serialized , it means jvm will ommit all transient and static variables from the object.
Explain the usage of the keyword transient?.
If you marked variable as transient means, the variable is not part of the persisten state of an object. i.e Prevents fields from even being serialized. transient fields are always skipped when objects are serialized, telling the JVM to skip(ignore) this variable when you attempt to serialize the object declaring it.More Details..
What is a serialVersionUID and why should we use it?.
The best and good explanation in java doc as below
The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.
When do you use Java's @Override annotation and why? The serialization runtime associates with each serializable class a version number, called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization. If the receiver has loaded a class for the object that has a different serialVersionUID than that of the corresponding sender's class, then deserialization will result in an InvalidClassException. A serializable class can declare its own serialVersionUID explicitly by declaring a field named "serialVersionUID" that must be static, final, and of type long:
ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization. Therefore, to guarantee a consistent serialVersionUID value across different java compiler implementations, a serializable class must declare an explicit serialVersionUID value. It is also strongly advised that explicit serialVersionUID declarations use the private modifier where possible, since such declarations apply only to the immediately declaring class--serialVersionUID fields are not useful as inherited members.
Use it every time you override a method for two benefits.
Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are.
This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does.
Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
Differences between HashMap and Hashtable?Do it so that you can take advantage of the compiler checking to make sure you actually are overriding a method when you think you are.
This way, if you make a common mistake of misspelling a method name or not correctly matching the parameters, you will be warned that you method does not actually override as you think it does.
Secondly, it makes your code easier to understand because it is more obvious when methods are overwritten.
There are several differences between HashMap and Hashtable in Java:
Hashtable is synchronized, whereas HashMap is not.
This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap.
This wouldn't be as easy if you were using Hashtable.
How to synchronize the Hashmap?Hashtable is synchronized, whereas HashMap is not.
This makes HashMap better for non-threaded applications, as unsynchronized Objects typically perform better than synchronized ones.
Hashtable does not allow null keys or values. HashMap allows one null key and any number of null values. One of HashMap's subclasses is LinkedHashMap, so in the event that you'd want predictable iteration order (which is insertion order by default), you could easily swap out the HashMap for a LinkedHashMap.
This wouldn't be as easy if you were using Hashtable.
HashMap can be synchronized by
Map m = Collections.synchronizedMap(hashMap);
When to use LinkedList<> over ArrayList<>?
LinkedList and ArrayList are two different implementations of the List interface.
LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array. LinkedList allows for constant-time insertions or removals, but only sequential access of elements.
In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list.
ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
Also, if you add more elements than the capacity of the underlying array, a new array (twice the size) is allocated, and the old array is copied to the new one. So depending on the operations you intend to do, you should choose the implementations accordingly. Iterating over either kind of List is practically equally cheap. (Iterating over an ArrayList is technically faster, but unless you're doing something really performance-sensitive, you shouldn't worry about this -- they're both constants.)
Also, if you have large lists, keep in mind that memory usage is also different. Each element of a LinkedList has more overhead since pointers to the next and previous elements are also stored. ArrayLists don't have this overhead. However, ArrayLists take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added.
Difference between wait() and sleep()?LinkedList implements it with a doubly-linked list. ArrayList implements it with a dynamically resizing array. LinkedList allows for constant-time insertions or removals, but only sequential access of elements.
In other words, you can walk the list forwards or backwards, but grabbing an element in the middle takes time proportional to the size of the list.
ArrayLists, on the other hand, allow random access, so you can grab any element in constant time. But adding or removing from anywhere but the end requires shifting all the latter elements over, either to make an opening or fill the gap.
Also, if you add more elements than the capacity of the underlying array, a new array (twice the size) is allocated, and the old array is copied to the new one. So depending on the operations you intend to do, you should choose the implementations accordingly. Iterating over either kind of List is practically equally cheap. (Iterating over an ArrayList is technically faster, but unless you're doing something really performance-sensitive, you shouldn't worry about this -- they're both constants.)
Also, if you have large lists, keep in mind that memory usage is also different. Each element of a LinkedList has more overhead since pointers to the next and previous elements are also stored. ArrayLists don't have this overhead. However, ArrayLists take up as much memory as is allocated for the capacity, regardless of whether elements have actually been added.
A wait can be "woken up" by another process calling notify on the monitor which is being waited on whereas a sleep cannot. Also a wait (and notify) must happen in a block synchronized on the monitor object whereas sleep does not:
Object obj = ...; synchronized (obj) { obj.wait(); }At this point the currently executing thread waits and releases the monitor. Another thread may do
synchronized (obj) { obj.notify(); }
(On the same obj object) and the first thread (assuming it is the only thread waiting on the monitor) will wake up.
You can also call notifyAll if more than one thread is waiting on the monitor - this will wake all of them up. However, only one of the threads will be able to grab the monitor (remember that the waitis in a synchronized block) and carry on - the others will then be blocked until they can acquire the monitor's lock.
Another point is that you call wait on Object itself (i.e. you wait on an object's monitor) whereas you call sleep on Thread.
No comments:
Post a Comment