Java / Object, Class and Package
1. Object Cloning.
Object cloning is one of the ways to create a exact copy of a object.
2. How to implement cloning?
The java.lang.Cloneable interface must be implemented by the class whose objects would be cloned. Implement the clone() method in the class protected Object clone() throws CloneNotSupportedException.
3. Can a Java source file have more than one class declaration?
Yes. However only one class can be declared as public and the java file name should be exactly same as the public class name along with .java extension.
4. Example of a final class in Java API.
java.lang.System
5. What is the data type of System.out?
out is of type PrintStream and it is a static member in the System class.
6. Can we have two classes with same name under the same package?
No.
7. Can we have class name same as the interface name under the same package?
8. What is the base class of all classes?
9. Could a Java class file exists even without filename and only extension(.java)?
Yes. The file is to be saved as .java without any file name. compile using javac .java and run using java
10. Anonymous class.
An anonymous class has no specified name declared and instantiated at the same time where it is declared. Because it has no name it can only be instantiated and used at the place of declaration. Anonymous classes either implement an interface or extend a class. Anonymous classes are given a name ...
11. Difference Between ClassNotFoundException & NoClassDefFoundError.
Both of these errors are related to missing classes in the classpath, however the main difference lies how it originate. ClassNotFoundException occurs when you try to load a class at runtime by using Class.forName() or loadClass() and requested class is not present in classpath. It is thrown when...
12. ClassNotFoundException Example.
package com.tutorials.classes; public class ExampleClassNotFoundException { private static final String CLASS_TO_LOAD = "com.tutorials.classes.NotCreatedClass" ; public static void main(String[] args) { try { Class loadedClass = Class.forName(CLASS_TO_LOAD); System.out.println( "Class " + loadedC...
13. Dynamic class loading.
A class can be loaded using one of the following methods: Class.forname, ClassLoader.findSystemClass, ClassLoader.loadClass.
14. Difference: Class.forName() vs ClassLoader.loadClass().
Class.forName() uses the caller's classloader and initializes the class (runs static intitializers, etc.). loadClass is a ClassLoader method, so it uses an explicitly-provided loader, and initializes the class lazily (on first use).
15. Which class implements clone method- Cloneable or Object in Java?
Java.lang.Object implements the clone() method. Clonable is a marker interface and it does not have any methods. Object.clone() is a native method implemented using C, C++ or any other native language.
16. Why Custom ClassLoader is required in Java?
Java default ClassLoader is sufficient to load files from local file system that helps most of the cases. In a scenario where we expect a class at the runtime or from FTP server or via third party web service at the time of loading the class then It may be required to create custom loader by exte...
17. How does Java ClassLoader Work?
When JVM requests a Java class, it invokes loadClass method of the ClassLoader by passing the fully classified name of the Class. loadClass method calls findLoadedClass() method to check that the class has been already loaded or not. If the Class is not already loaded then it will delegate the re...
18. When are class static variables loaded in memory in Java?
At runtime immediately after the class has been loaded.
19. Describe the principle of Java class loader.
Java ClassLoader is based on the following 3 principles. Delegation principle delegates the classloading request to parent class loader and loads the class only if parent is not able to find or load class. Visibility principle allows child class loader to access all the classes loaded by parent C...
20. When a class is loaded in Java?
Class loading is performed by ClassLoaders in Java which can be implemented to eagerly load a class as soon as another class references it or lazily load the class until a need of class initialization occurs. If a Java class is loaded before its actually being used it resided at JVM before being ...
21. When a class is initialized in Java?
After class loading, initialization of class takes place by initializing all static members of class. A Java class's static initialization usually happens immediately before the first time one of the following events occurs: an instance of the class is created, a static method of the class is inv...
22. What are the rules of class initialization in Java?
Classes are initialized from top to bottom fashion so that fields declared on top initialized before field declared in bottom. Super Class is initialized before Sub Class or derived class is initialized in Java. If Class initialization is triggered due to the access of a static field, only Class ...
23. What is a Local class in Java?
The class defined inside a particular block is called local class. Such a class has local scope and isn't usable outside the block where it is defined.
24. Different type of cloning in Java.
Java supports 2 type of cloning: - Deep and shallow cloning. By default shallow clone is used in Java. Object class has a method clone() which does shallow cloning.
25. Explain Shallow copy in Java.
Shallow clone is a copying the reference pointer to the object, which mean the new object is pointing to the same memory reference of the old object. The memory usage is less in case of shallow copy.
26. Explain deep copy in Java.
Deep copy of an object will have exact copy of all the fields of original object just like shallow copy. But in additional, if original object has any references to other objects as fields, then copy of those objects are also created by calling clone() method on them. That means clone object and ...
27. Difference between shallow and deep copy in Java.
Shallow copy. Deep copy. Cloned Object and the original object are not 100% disjoint. Cloned Object and original object are 100% disjoint. Any changes to the cloned object will be reflected in original object or vice versa. Changes made to cloned object won't be reflected to original object or vi...
28. What is Serialization in Java?
Serialization is a process of writing an Java Object into file along with its attributes and content. It internally converts the object in stream of bytes.
29. Explain De-serialization in Java.
De-Serialization is a process of reading the Java Object and its properties from a file along with the Object's content.
30. Difference between readObject and readResolve in Java serialization.
The readObject method is responsible for reading from the stream and restoring the classes fields. readResolve is used for replacing the object read from the stream. This helps enforcing singletons; when an object is read, replace it with the singleton instance. This ensures that nobody can creat...
31. Why is Class.newInstance() is discouraged to use?
This method propagates any exception thrown by the nullary constructor (parameter-less), including checked exceptions . Use of this method effectively bypasses the compile-time exception checking that would otherwise be performed by the compiler. The Constructor.newInstance method avoids this pro...
32. Difference between Static block and initializer block in Java.
The static initializer block will be called on loading of the class, and will have no access to instance variables or methods. It is often used to create static variables. The non-static initializer block is created on object construction only, will have access to instance variables and methods. ...
33. What is static class in Java?
Static class is a Java class, which only contains static methods. An example of static class is java.lang.Math,which contains utility static methods for various math features such as sqrt, random.
34. Role of Runtime and System class in Java.
Runtime class provides access to the Java runtime system to retrieve information like memory availability, invoking the garbage collector, etc. System class provides access to system resources. It enables access to standard input/output, error output streams, current time in millis, terminating t...
35. Can an anonymous class have constructor?
No.
36. What are the Object class methods?
protected Object clone() throws CloneNotSupportedException Creates and returns a copy of this object. public boolean equals(Object obj) Indicates whether some other object is "equal to" this one. protected void finalize() throws Throwable Called by the garbage collector on an object when garbage ...
37. Can you override Object class getClass method?
No. It is a final method.
38. When shallow object copy is preferred?
Shallow copy is preferred for cloning primitive types and immutable objects.
39. How to implement equals method correctly?
Consider that you are overriding equals method for Employee Class having empId, firstName and lastName. Check for reference equality, if equal then return true. Check for null check on the object argument being passed, if null return false. Compare getClass methods, if different return false. Alw...
40. Good implementation of hashCode method in Java.
As per the expert's recommendation, the below steps are listed. Create a int hashcodeResult and assign it a non-zero value. For every field f tested in the equals method,calculates its hash code value c using the following. If the field f is a boolean: calculate (f ? 0 : 1) ; If the field f is a ...
41. Java equals() vs. compareTo() contract.
It is not strictly required, however the contract is compareTo should return 0 if equals returns true. TreeSet uses compareTo for ordering, ArrayList for sorting, so it is better to override compareTo as well.
42. Can two objects which are not equal have the same hashCode?
Yes, possible. Two objects which are not equal to equals() method can still return same hashCode.
43. What happens when equals() is not consistent with compareTo() method?
java.util.Set implementations such as SortedSet, TreeSet uses compareTo method for comparing objects. When compareTo does not return 0 while equals is true, it breaks Set contract and may result in duplicates .
44. Difference between instanceof and getClass() method for checking type inside equals.
instanceof operator returns true, even if compared with subclass, for example, Subclass instanceof Superclass is true, but with getClass () its false. By using getClass() you ensure that your equals() implementation doesn't return true if compared with subclass object.