Skip to main content


Showing posts from August, 2020

Java Externalizable Interface Example

When your class implements Serializable interface, object serialization is automatic where you just need to call writeObject() and readObject() methods for serialization and deserialization . If you want to customize the serialization process with you having more control then you can use Externalizable interface in Java. Table of contents Externalizable interface in Java Externalizable Java example Serialization order in Java Externalizable interface in Java interface extends Serializable interface and adds two methods of its own- writeExternal(ObjectOutput out) - To write object into a stream by calling writexxx methods for primitive types and writeObject method for objects. This flexibility to call write() methods for individual fields gives you control over the serialization process. readExternal(ObjectInput in) - To read object from stream by calling readxxx methods for primitive types and readObject method for objects. Any

Serialization in Java With Examples

Serialization in Java is the process of converting state of the object into a byte stream and the reverse process of deserialization converts that byte stream (serialized form of object) back into a copy of the object. Once the object is converted into byte stream you can save it. Because of this ability to persist an object, provided by serialization in Java, objects we create could exist beyond the lifetime of the JVM. Following image shows the process of serialization and deserialization in Java and what can you do with serialized object. Table of contents What is required for serialization ObjectOutputStream and ObjectInputStream classes Java object serialization example Points about Serialization Implementing writeObject() and readObject() methods Using writeObject() and readObject() to stop serialization What is required for serialization A Java object can be serialized if its class or any of its superclasses implements either the

Java Callable And Future With Examples

In this post we’ll see two of the interesting features of the concurrent API, Callable and Future in Java. Table of contents Callable in Java Callable interface Running a Callable task using ExecutorService Java Callable and Future example Future in Java Callable and Future example Callable in Java Consider a scenario where you have a big computation and you want to split it into multiple sub-tasks which are executed by multiple threads with each thread working on a part of the task. Once all the threads are finished with their tasks you can combine the partial results to get the result of the computation. Designing this scenario with Runnable makes it difficult as Runnable doesn’t return a result. That shortcoming is filled by Callable in Java as it can return a result and may throw an exception. Callable interface Callable interface in Java has a single method call() which computes a result and returns it or throws an exception if unable to d

NoClassDefFoundError in Java

In this post we’ll discuss about java.lang.NoClassDefFoundError and how to fix it. When is NoClassDefFoundError in Java thrown NoClassDefFoundError in Java is thrown when a class is present at compile time but at runtime when the JVM or a ClassLoader instance tries to load in the definition of a class it is not found. Note that NoClassDefFoundError is a descendant of java.lang.Error. Since it is of type Error so you can’t do any exception handling to recover from it. NoClassDefFoundError Java Example Let’s say I have a program to read a file into a byte array that uses for that commons-io—xxx.jar is included in the classpath. Program compiles and executes with out any problem. import; import; import; import; import; public class FileToByteArray { public static void main(String[] args) { File file = new File("F:\\knpcode\\link

ClassNotFoundException in Java

ClassNotFoundException in Java is thrown if an application tries to load a class but the class with the specified name is not found. java.lang.ClassNotFoundException ClassNotFoundException in Java is a checked exception which means it subclasses from Exception class (not from RuntimeException). This exception is thrown if you try to load a class at runtime through its String name using one of the following methods. The forName method in class Class. The findSystemClass method in class ClassLoader . The loadClass method in class ClassLoader. But the class with the passed name is not found. One scenario where you may encounter java.lang.ClassNotFoundException is when you try to load JDBC driver without having the require JAR in the class path. In the following example there is an attempt to load oracle driver though ojdbcXXX.jar is not in the classpath. public class ClassNotFoundExceptionExp { public static void main(String[] args) { try { Class.forNam

UnsupportedClassVersionError in Java and Resolution

In this post we’ll discuss about java.lang.UnsupportedClassVersionError and how to fix it. When is UnsupportedClassVersionError in Java thrown UnsupportedClassVersionError is thrown when the Java Virtual Machine attempts to read a class file whose major and minor version numbers are not supported by the current JVM version. To understand it better you need some background on class file format and what are major and minor versions. Java Virtual Machine class file format contains many sections, for UnsupportedClassVersionError the section of interest is the second section which tells the version of the class file format. This section is of 4 bytes, where 2 bytes are allotted to minor_version and 2 bytes to major_version. Together, a major and a minor version number determine the version of the class file format. If the class file version is greater than what JVM supports java.lang.UnsupportedClassVersionError is thrown. The release level of the Java SE platform to which a Ja

finalize() Method in Java

finalize() method in Java is a callback method which is called before any object is garbage collected. Table of contents What does finalize() method do finalize() method is part of Object class finalize() method is not reliable How to use finalize() method in Java finalize() method Java example Exception in finalize() method Important points about Finalize What does finalize() method do When there are no existing references to an object it is eligible for garbage collection. At the time of garbage collection the memory of an unreferenced object is reclaimed. But reclaiming the object memory does not guarantee that the resources it holds will be released . That’s what finalize() method in Java can do, you can provide code in finalize() method to free up system resources like I/O stream, open DB or socket connection or to perform other cleanup. It will be executed just before the object is garbage collected. finalize() method is part of Object c

Constructor Chaining in Java

Constructor chaining in Java is the process of calling one constructor from another constructor with in the same class or calling the parent class constructor from the child class. So constructor chaining in Java can be done in two ways- When calling one constructor from another with in the same class. In this case this Keyword can be used to call constructors in chain. In case of inheritance when calling the parent class’ constructor from the child class. In this case super keyword can be used to call constructors. Table of contents How does constructor chaining help Constructor chaining in Java with inheritance Rules regarding constructor chaining with super How does constructor chaining help Constructor chaining in Java helps with reducing the code redundancy by doing the task of initialization in one of the constructor. All the other constructors merely call that constructor in a chain for initialization. Consider the scenario where you have 3

Constructor Overloading in Java

Constructor overloading in Java is the process similar to method overloading which means with in a class you can have more than one constructor where the constructors differ in the number of parameters. What is the use of having overloaded constructor Constructor overloading in Java brings the flexibility of initializing the object as per your need. For example in ArrayList class there is a no-arg constructor which initializes the ArrayList with the default capacity and there is another constructor where initial capacity can be passed as a parameter to initialize ArrayList with the required initial capacity. Another scenario where constructor overloading in Java helps is to provide a no-arg constructor when there is already a parameterized constructor. Java implicitly inserts a default no-arg constructor if no constructor is provided in the class . If you provide a constructor yourself then this default no-arg constructor is not provided automatically. public class Co

Constructor in Java

Constructor in Java is a special method which is called automatically to initialize an object when the object is created. Table of contents Need for a constructor Java constructor example Rules for Constructors Types of constructors Private constructor in Java Private constructor example Need for a constructor When an object is created it is a very common requirement to initialize that object (provide values for its instance variables). To facilitate that a constructor is provided and Java automatically calls that constructor when an object is created to guarantee initialization. Java constructor example public class ConstructorDemo { int num; String name; public ConstructorDemo(int num, String name){ this.num = num; = name; } public static void main(String[] args) { ConstructorDemo cd = new ConstructorDemo(10, "Rodrigo"); System.out.println("Number is " + cd.num + " Name is " +

Initializer Block in Java

When you create an instance of a class, constructor is called to initialize the instance variables. An alternative to using a constructor to initialize instance variable is to use initializer block in Java . Initializer block is always executed when an instance of the class is created. General form of Initializer block in Java { // whatever code is needed for initialization // goes here } How to use initializer block in Java The Java compiler copies initializer blocks into every constructor. Therefore, this approach can be used to share a block of code if you have overloaded constructors in your class. Putting the common code in an initializer block ensures that that piece of code is always executed irrespective of the constructor called. Initializer block Java example public class MainClass { //instance initializer block { System.out.println("Instance initializer block, this block is always executed"); } MainClass(){ System.out.println(&

Object Class in Java

Object class in Java, residing in java.lang package is the root of the Java class hierarchy. Every class in Java inherits either directly or indirectly from the Object class . If a Java class doesn't extend any other class then it implicitly extends Object class making it a direct descendant of Object class, if a Java class extends other class then also it extends Object class as a multi-level hierarchy inheritance. Since Object class in Java is the root of the class hierarchy, you must take note of the following three points- Object class is the parent class of all the other classes. Since it is a parent class of all the classes so reference of type Object can refer to object of any class. Every class you use or write inherits the instance methods of Object class. Table of contents Object class methods hashCode() method finalize() method clone() method toString() method getClass() method wait() method notify() and notifyAll(