Posts
Showing posts from December, 2015
First 100 prime numbers - Java
- Get link
- X
- Other Apps
public class First100Prime { public void printFirst100Prime(){ for(int i=1; i<=100; i++){ boolean isPrime = true; for(int j=2; j<i; j++){ if(i%j == 0){ isPrime = false; break; } } if(isPrime) System.out.println(i); } } } ----------------------------------- package ds.numbers; import org.junit.Test; import static org.junit.Assert.*; public class First100PrimeTest { ...
Builder pattern - Java
- Get link
- X
- Other Apps
Guidelines for Builder design pattern in Java 1) Make a static nested class called Builder inside the class whose object will be build by Builder . In this example its Cake . 2) Builder class will have exactly same set of fields as original class. 3) Builder class will expose method for adding ingredients e.g. sugar() in this example. each method will return same Builder object. Builder will be enriched with each method call. 4) Builder.build() method will copy all builder field values into actual class and return object of Item class. 5) Item class (class for which we are creating Builder) should have private constructor to create its object from build() method and prevent outsider to access its constructor. public class BuilderPatternExample { public static void main ( String args []) { ...
If a class is Serializable but its super class in not, what will be the state of the instance variables inherited from super class after deserialization?
- Get link
- X
- Other Apps
Java serialization process only continues in object hierarchy till the class is Serializable i.e. implements Serializable interface in Java and values of the instance variables inherited from super class will be initialized by calling constructor of Non-Serializable Super class during deserialization process. Once the constructor chaining will started it wouldn't be possible to stop that , hence even if classes higher in hierarchy implements Serializable interface , there constructor will be executed. As you see from the statement this Serialization interview question looks very tricky and tough but if you are familiar with key concepts its not that difficult. Read more: http://javarevisited.blogspot.com/2011/04/top-10-java-serialization-interview.html#ixzz3uyZyfZFC
If one of the members in the class doesn't implement Serializable interface?
- Get link
- X
- Other Apps
One of the easy question about Serialization process in Java. If you try to serialize an object of a class which implements Serializable, but the object includes a reference to an non- Serializable class then a ‘NotSerializableException ’ will be thrown at runtime and this is why I always put a SerializableAlert (comment section in my code) , one of the code comment best practices , to instruct developer to remember this fact while adding a new field in a Serializable class. Read more: http://javarevisited.blogspot.com/2011/04/top-10-java-serialization-interview.html#ixzz3uyZjnIV7