Saturday, 31 October 2015

The logical(non-bitwise) operators && and || are short-circuit operators. In other words, with && if the LHS(Left Hand Side) is false, the RHS(Right Hand Side) will never be evaluated. With || if the LHS is true, then the RHS will never be evaluated. On the other hand, the bitwise operators & and | are non short-circuit, will always evaluate both the LHS and RHS.
This is especially useful in guarding against nullness.

In the above example (bitwise & operator) ,it will check the all conditions in the if statements, so it will throw the NullPointerException.
One main difference between & and && is, bitwise & you can use with both integral and boolean but && you can use with only boolean operands.

In the above code it will print else part i.e "Inside else Statement". In if statement there are two conditions with && operator. In logical AND operator it will check the first condition if it is false then it won't check the 2nd condition and it will return false. In the above code first condition is false so it won't check the 2nd condition. In second condition it is exception but it won't check the condition at all.
In the above code,if we changed the first condition of if statement, then it will throw NullPointerException, See below.

Saturday, 24 October 2015

First to understand what is Loose coupling and Tight coupling and also to know the advantage of loose coupling.

In short Loose coupling means reducing dependencies of a class that use different class directly . Tight coupling means classes and objects are dependent on one another. In general tight coupling is usually not good because it reduces flexibility and re-usability of code and it makes changes much more difficult and not easy to test.

Tight Coupling:-

Tightly coupled object is an object that needs to know quite a bit about other objects and are usually highly dependent on each other's interfaces. Changing one object in a tightly coupled application often requires changes to a number of other objects. In a small application we can easily identify the changes and there is less chance to miss anything. But in large applications these inter-dependencies are not always known by every programmer and there is chance of overlooking changes.(Source- from StackOverflow).
See below code is for tight coupling.

In the above code the Journey class is dependents on Car class to provide service to the end user(main class to call this Journey class).

In the above case Journey class is tightly coupled with Car class it means if any change in the Car class requires Journey class to change. For example if Car class travel() method change to journey() method then you have to change the startJourney() method will call journey() method instead of calling travel() method.

The best example of tight coupling is RMI(Remote Method Invocation)(Now a days every where using web services and SOAP instead of using RMI, it has some disadvantages).

Loose Coupling:-

Loose coupling is a design goal that seeks to reduce the inter-dependencies between components of a system with the goal of reducing the risk that changes in one component will require changes in any other component. Loose coupling is much more generic concept intended to increase the flexibility of system, make it more maintainable and makes the entire framework more stable.
Below code is an example of loose coupling,

In the above example, Journey and Car objects are loosely coupled. It means Vehicle is an interface and we can inject any of the implemented classes at run time and we can provide service to the end user.

The examples of Loose coupling are Interface, JMS, Spring IOC(Dependency Injection, it can reduce the tight coupling).

Advantages Of Loose coupling:-

A loosely coupled will help you when your application need to change or grow. If you design with loosely coupled architecture, only a few parts of the application should be affected when requirements change. With too a tight coupled architecture, many parts will need to change and it will be difficult to identify exactly which parts will be affected. In short,

1) It improves the testability.
2) It helps you follow the GOF principle of program to interfaces, not implementations.
3) The benefit is that it's much easier to swap other pieces of code/modules/objects/components when the pieces are not dependent on one another.
4) It's highly changeable. One module doesn't break other modules in unpredictable ways.

Tuesday, 6 October 2015

The java.lang.OutOfMemoryError in Java is a subclass of java.lang.VirtualMachineError and JVM throws java.lang.OutOfMemoryError when it ran out of memory in heap. When you will try to create an object and there is not enough space in heap to allocate that object then you will get OutOfMemoryError.

Types of OutOfMemoryError in Java

1) Java.lang.OutOfMemoryError: Java heap space

2) Java.lang.OutOfMemoryError: PermGen space

Now we will discuss about PernGen space,

PermGen stands for PermanentGeneration.

Java applications are only allowed to use a limited amount of memory.
The exact amount of memory your particular application can use is
specified during application startup. To make things more complex, Java
memory is separated into Young, Tenured and PermGen regions.

The size of all these is set during the JVM launch. If you didn't set the sizes of these regions then platform specific default will be used(The default PermGen Space allocated is 64 MB for server mode and 32 MB for client mode).

Causes:

The mainly the permanent generation consists of class declarations loaded and stored into PermGen. This includes the name and fields of the class, methods with the method bytecode, constant pool information, object arrays and type arrays associated with a class and Just In Time compiler optimizations.

From the above paragraph, we can say that the main cause for the java.lang.OutOfMemoryError: PermGen space is that either too many classes or too big classes are loaded to the permanent generation.

Solution:--

As explained in above, this OutOfMemory error in java comes when Permanent generation of heap filled up.
To fix this OutOfMemoryError in Java you need to increase heap size of Perm space by using JVM option "-XX:MaxPermSize".
You can also specify initial size of Perm space by using "-XX:PermSize" and keeping both initial and maximum Perm Space you can prevent some full garbage collection which may occur when Perm Space gets re-sized. Here is how you can specify initial and maximum Perm size in Java:

export JVM_ARGS="-XX:PermSize=64M -XX:MaxPermSize=256m"

Note:-
In Java 8, PermGen area has been replaced by MetaSpace area, which is
more efficient and is unlimited by default (or more precisely - limited
by amount of native memory, depending on 32 or 64 bit jvm and OS
virtual memory availability) .

Monday, 20 July 2015

Factory pattern is one of most used design pattern in Java. This type
of design pattern comes under Creational Design Pattern as this pattern
provides one of the best ways to create an object.

In Factory pattern, we create object without exposing the creation
logic to the client and refer to newly created object using a common
interface. & this pattern provides loose coupling.

In this post, we will look at complete example of the Factory Design Pattern implemented in Java. In the below example, w'll learn how to use the Factory pattern in different message types(There are three message types in the example, SMS, Email and Notification). This is one simple example.

First we can create one abstract class or an interface. MessageBuilder is an abstract class having one abstract method build.

publicabstractclassMessageBuilder {
publicabstractvoidbuild () ;
}

In the above class build is not fully implemented so next we can create particular message type builder so that can extends the Messagebuilder and you can implement the build method according to that message type. In the below codes, there are three mesage type builder ,SMSMessageBuilder,EMAILMessageBuilder and NotificationMessageBuilder. and each can extends MessageBuilder abstract class and to implements the build methods. Each MessageBuilder of build method is implemented differently according to their requirement.

Next step is to define the Factory class, in this case which is a MessageBuilderFactory. As you can see in the below code, the static getBuilder method will return particular "MessageBuilder" object based on the parameter messageType.

If you want to add new message type in the above existing code then you have to create one Implemented MessageBuilder class that can extends abstract MessageBuilder class. In the MessageBuilderFactory you can add one else if condition and to pass messageType as parameter.

1) code is flexible, loosely coupled and reusable by moving the object creation from the client code to the Factory class and it's subclasses. It is easier to maintain such code since the object creation is centralized.2) The client code deals with only the product interface or abstract and hence any concrete products can be added without modifying client code logic.3) It encourages a consistency in the code as object is created through a Factory which forces a definite set of rules which everybody must follow(other developer can easily understand the code). This avoids using different constructor at different client.

Saturday, 25 April 2015

Java Serialization allows us to convert an Object to byte stream that
we can send over the network or save it as file or store in DB for
later usage.
Deserialization is the process of converting Object stream to actual Java Object to be used in our program.

Image: Serialization & Deserialization Process

If you want a class object to be serializable, all you need to do it implement the java.io.Serializable interface. Serializable is a marker interface and has no fields or methods to implement.
Serialization process is implemented by ObjectInputStream and ObjectOutputStream, so all we need is a wrapper over them to either save it to file or send it over the network. Let’s see a simple Serialization example.

Notice that for a class to be serialized successfully, two conditions must be met:
1)The class must implement the java.io.Serializable interface.
2)All of the fields in the class must be serializable. If a field is not serializable, it must be marked as transient. In the above Student class address is non-serializable field.

Now, once a class is serializable, we can write the object to any OutputStream, such as to disk or a socket connection. To achieve this, we must first create an instance of java.io.ObjectOutputStream, and pass the constructor an existing OutputStream instance.

Deserialization is the process of converting Object stream to actual Java Object to be used in our program. Below is code for deserialization of java objects, here we just need to get an FileInputStream object from the file that contains object's bytes and pass this to ObjectInputStream's object's constructor. Method readObject() returns an object whose bytes are being read from the file.

package com.adnblog;

import java.io.FileInputStream;

import java.io.ObjectInputStream;

public class DeserializeObject {

public static void main(String[] args) {

String filename = "Serialize.ser";

Student st = null;

// read the object from file

FileInputStream fis = null;

ObjectInputStream ois = null;

try {

fis = new FileInputStream(filename);

ois = new ObjectInputStream(fis);

st = (Student) ois.readObject();

} catch (Exception ex) {

ex.printStackTrace();

}

finally {

if(ois != null) { ois.close();

}

}

System.out.println(st);

}

}

Uses Of Serialization:-

1. Banking example:
When the account holder tries to withdraw money from the server through
ATM, the account holder information along with the withdrawl details
will be serialized (marshalled/flattened to bytes) and sent to server
where the details are deserialized (unmarshalled/rebuilt the bytes)and
used to perform operations. This will reduce the network calls as we are
serializing the whole object and sending to server and further request
for information from client is not needed by the server.

2. Stock example:
Lets say an user wants the stock updates immediately when he request
for it. To achieve this, everytime we have an update, we can serialize
it and save it in a file. When user requests the information,
deserialize it from file and provide the information. This way we dont
need to make the user wait for the information until we hit the
database, perform computations and get the result.

Here are some uses of serialization

1. Convert java object into byte stream and then it can be saved in database for persistence.

2. If two JVM want to communicate, then object serialization is one of the approaches.

3.
Send the java object in network as byte stream by serialization and at
the other end deserialize to get same object in same state.

4. Cache the object by serialization instead of keeping it in memory.

Serialization and Deserialization Related Questions:

1) What is a serialVersionUID and why should use it?

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;

2) Do we need to implement any method of Serializable interface to make an object serializable?No. Serializable is a Marker Interface. It does not have any methods.

3) How to make the field as Non Serializable?
Sometimes you don't want to serialize/store all the fields in the object. Say some fields you want to hide to preserve the privacy or some fields you may want to read only from master data, then you don't serialize them. To do this, you just need to declare a field as transient field.

transient private String address;

Also the static fields are not serialized. Actually there is no point in serializing static fields as static fields do not represent object state but represent class state and it can be modified by any other object. Lets assume that you have serialized a static field and its value and before deserialization of the object, the static field value is changed by some other object. Now the static field value that is serialized/stored is no more valid. Hence it make no point in serializing the static field.

Thursday, 12 March 2015

A file or a directory in the file system is represented by two abstract concept in java. These abstract concepts are java.io.File and java.nio.file.Path. The File class represents a file in the file system whereas the interface Path represents the path string of the file.
In this tutorial we look at various operations on File or Path.

Instantiating a java.io.File:

Before you can do anything with the file system or File class, you must obtain a File instance.

There are following constructors to create a File object:

1)Following syntax creates a new File instance from a parent abstract pathname and a child pathname string.

File(File parent, String child)

2)Following syntax creates a new File instance by converting the given pathname string into an abstract pathname.

File(String pathname)

3)Following syntax creates a new File instance from a parent pathname string and a child pathname string.

File(String parent, String child)

4)Following syntax creates a new File instance by converting the given file: URI into an abstract pathname.

File(URI uri)

Once you have File object in hand then there is a list of helper methods which can be used manipulate the files.

Once you have instantiated a File object you can check if the corresponding file actually exists already. The File class constructor will not fail if the file does not already exists. You might want to create it now.

To check if the file exists, call the exists() method. Here is a simple example:

Create New File: You can use the File class to create new Files if they don't already exists. The File class contains the method createNewFile() to create the new file. First to check the file is existed or not, if not then create new file.package com.adnblog; import java.io.File; public class fileExistance { public static void main(String[] args) { File file = new File("D:/ImpFiles/file.txt"); if(!file.exists()) { if(file.createNewFile()) { System.out.println("New File created!"); } else { System.out.println("Failed to create New File"); } } } }

File Length:-

To read the length of a file in bytes, call the length() method. Here is a simple example:

As briefly mentioned earlier, the renameTo() method can also be used to move a file to a different directory. The new file name passed to the renameTo() method does not have to be in the same directory as the file was already residing in.

The renameTo() method returns boolean (true or false), indicating whether the renaming was successful. Renaming of moving a file may fail for various reasons, like the file being open, wrong file permissions etc.

The delete() method returns boolean (true or false), indicating whether the deletion was successful. Deleting a file may fail for various reasons, like the file being open, wrong file permissions etc. Check if Path is File or Directory:--

A File object can point to both a file or a directory.

You can check if a File object points to a file or directory, by calling its isDirectory() method. This method returns true if the File points to a directory, and false if the File points to a file. Here is a simple example: package com.adnblog; import java.io.File; public class fileExistance { public static void main(String[] args) { File file = new File("D:/ImpFiles/file.txt"); if(file.isDirectory()) { System.out.println("This is Directory!"); } else { System.out.println("This is a File!"); } } }

Read List of Files in Directory:--

You can obtain a list of all the files in a directory by calling either the list() method or the listFiles() method. The list() method returns an array of String's with the file and / or directory names of directory the File object points to. The listFiles() returns an array of File objects representing the files and / or directories in the directory the File points to.Here is a simple example:package com.adnblog; import java.io.File; public class Practice { public static void main(String[] args) { File file = new File("/home/insta/anil/Desktop"); File[] filesList = file.listFiles(); for(File f : filesList){ System.out.println(f); } } }In the above program it will print the each file in whole path see output /home/insta/anil/Desktop/Resume.doc /home/insta/anil/Desktop/SalarySlip.pdf /home/insta/anil/Desktop/ImpNotes.csv

Saturday, 7 March 2015

First difference between them is, equals() is a method defined inside the java.lang.Object class
and == is one type of operator and you can compare both primitive and objects using equality operator in java.

Second difference between equals and == operator is that ,== is used to check reference or memory address of the objects whether they point to same location or not , and equals() method is used to compare the contents of the object e.g in case of comparing String its characters, in case of integer its numeric values etc.

Third difference between equals and == operator is that, you can not change the behavior of == operator but we can override equals() method and define the criteria for the objects equality.

Summary:--

1) Use == to compare primitive e.g boolean, int, char etc while use equals() to compare objects in
Java.

2) == return true if two reference are of same object . Results of equals() method depends on
overridden implementation.

3) For comparing String use equals() instead of == equality operator.

Some interview questions & answers based on equals() method and == operator :

1) Can two objects which are not equal have same hashCode?Yes, two objects which are not equal by equals() method can still returns the same hashCode. 2) What happens if you compare an object with null using equals() method?

When null object is passed as an argument to equals() method, it should return false, it must not throw NullPointerException , but if you call equals method on reference, which is null it will throw NullPointerException. That's why it's better to use == operator for comparing null.