Wednesday 21 February 2018

Ways to create objects in Java

Different ways to create objects in java


1. Using the new keyword

It is the most common and regular way to create an object and actually very simple one also. By using this method we can call whichever constructor we want to call (no-arg constructor as well as parametrised).

 Employee emp1 = new Employee(); 

2. Using Class.newInstance() method

We can also use the newInstance() method of the Class class to create objects, This newInstance() method calls the no-arg constructor to create the object.
We can create objects by newInstance() in following way.

Employee emp2 = (Employee) Class.forName("com.Employee").newInstance();

Or

Employee emp2 = Employee.class.newInstance();

3. Using newInstance() method of Constructor class

Similar to the newInstance() method of Class class, There is one newInstance() method in the java.lang.reflect.Constructor class which we can use to create objects. We can also call a parameterized constructor, and private constructor by using this newInstance() method.

Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class class internally uses newInstance() method of Constructor class. That's why the later one is preferred and also used by different frameworks like Spring, Hibernate, Struts etc. 

Constructor<Employee> constructor = Employee.class.getConstructor();
Employee emp3 = constructor.newInstance();

4. Using clone() method

Whenever we call clone() on any object JVM actually creates a new object for us and copy all content of the previous object into it. Creating an object using clone method does not invoke any constructor.

To use clone() method on an object we need to implements Cloneable and define clone() method in it.

Employee emp4 = (Employee) emp3.clone();

Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the most popular and easy way of creating a copy of any object until that object is full filling mandatory conditions of Java cloning.

5. Using deserialization

Whenever we serialize and then deserialize an object JVM creates a separate object for us. In deserialization, JVM doesn’t use any constructor to create the object.
To deserialize an object we need to implement the Serializable interface in our class.

ObjectInputStream in = new ObjectInputStream(new FileInputStream("data.obj"));
Employee emp5 = (Employee) in.readObject();





Saturday 17 February 2018

Does ArrayList in Java have default size?

Surprised ? Many developers might not aware of the fact that arraylist have some default size. Normally we consider arraylist with "0" size. Lets have a dig at the concept : 
ArrayList uses an array to store the elements. Arrays have a fixed size. The array that ArrayList uses has to have a default size, obviously. 10 is probably a more or less arbitrary number for the default number of elements. When you create a new ArrayList with nothing in it, then ArrayList will have made an array of 0 element, and when you add first element then it create array of 10 elements behind the scenes. Ofcourse those 9 elements are all null.
Using This line ...! 
List list=new ArrayList<String>();
Made an array of 0 element
list.add("FirstValue");
It create array of 10 elements behind the scenes with "FirstValue" at its 0 index.
Every time the array is full, ArrayList creates a new, larger array and copies the elements from the old array to the new array.

Note :- (copying the array time so better to think about its first)
if list.size == 9 and we do list.add("EleventhString")

It will create new array and copy all the data in newly created array.
The size of new arary depends on the current size of array and the algorithm is 
(CurrentSize of Array * 3/2) + 1

Wednesday 14 February 2018

Why Java declared String as immutable?

The Strings in java are immutable because they are stored in the "String Pool". The basic property of String pool is not to allow the "duplicate strings". 

i.e. if we declare,

String s1="abc"; 
String s2= "abc";

instead of 2 String objects only one String object will be created in String pool as content of both the Strings are equal. Ofcourse, this saves lot of memory at runtime. 

But because of this, there might be possibility that client1 changes the object referred by abc and client2, would get the modified String. So, to avoid this String objects are immutable in Java.

Another reason of why String class is immutable could die due to HashMap.

Since Strings are very popular as HashMap key, it's important for them to be immutable so that they can retrieve the value object which was stored in HashMap. Mutable String would produce two different hashcodes at the time of insertion and retrieval if contents of String was modified after insertion, potentially losing the value object in the map.

At the same time, String was made final so that no one can compromise invariant of String class e.g. Immutability, Caching, hashcode calculation etc by extending and overriding behaviors. 


Friday 7 April 2017

Convert Char to String in Java

Sometimes we have to convert char to String in java program. Here we will look into different methods you can convert character to string in java. We will also learn how to convert char array to String using different methods.

public class CharToStringJava {

 public static void main(String[] args) {

  // char to string
  char c = 'a';
  String str = String.valueOf(c);

  // using Character class
  str = Character.toString(c);

  // another way
  str = new Character(c).toString();
  // string concatenation - worst performance
  str = "" + c;
  
  // char array to string
  char[] ca = { 'a', 'b', 'c' };
  str = String.valueOf(ca);
  // recommended way
  str = new String(ca);

 }

}

String.valueOf(char c)

This is the most efficient method to convert char to string. You should always use this method and this is the recommended way to convert character to string in java program.

Character.toString(c)



This method internally calls String.valueOf(c), so there is no difference between this one. You can use this too if you are already using Character class in your code.

new Character(c).toString();

This is another way, however not recommended because we are creating a Character unnecessarily.

String concatenation

str = "" + c; is the worst way to convert char to string because internally it’s done by new StringBuilder().append("").append(c).toString() that is slow in performance.
Let’s look at the two methods to convert char array to string in java program.

String constructor

You can use String(char[] value) constructor to convert char array to string. This is the recommended way.

String.valueOf(char[] data)

String valueOf method is overloaded and there is one that accepts character array. Internally this method calls the String constructor, so it’s same as above method.
That’s all for converting char to string and char array to string in java.

Thursday 6 April 2017

What are the important features of Java 8 release ??

Java 8 has been one of the biggest release after Java 5 annotations and generics. Some of the important features of Java 8 are:

1. Interface changes with default and static methods

Java 8 interface changes include static methods and default methods in interfaces. Prior to Java 8, we could have only method declarations in the interfaces. But from Java 8, we can have default methods and static methods in the interfaces.
For creating a default method in java interface, we need to use “default” keyword with the method signature. For example,
package com.seed;
public interface Interface1 {
              void method1(String str);
              default void log(String str){
                             System.out.println("I1 logging::"+str);
              }
}
Notice that log(String str) is the default method in the Interface1. Now when a class will implement Interface1, it is not mandatory to provide implementation for default methods of interface. This feature will help us in extending interfaces with additional methods, all we need is to provide a default implementation.
Java Interface Static Method
Java interface static method is similar to default method except that we can’t override them in the implementation classes. This feature helps us in avoiding undesired results incase of poor implementation in implementation classes. Let’s look into this with a simple example.
package com.seed
public interface MyData {
              default void print(String str) {
                             if (!isNull(str))
                                             System.out.println("MyData Print::" + str);
              }
               static boolean isNull(String str) {
                             System.out.println("Interface Null Check");
                              return str == null ? true : "".equals(str) ? true : false;
              }
}
Now let’s see an implementation class that is having isNull() method with poor implementation.
package com.seed;
public class MyDataImpl implements MyData {
              public boolean isNull(String str) {
                             System.out.println("Impl Null Check");
                             return str == null ? true : false;
              }
              public static void main(String args[]){
                             MyDataImpl obj = new MyDataImpl();
                             obj.print("");
                             obj.isNull("abc");
              }
}
Note that isNull(String str) is a simple class method, it’s not overriding the interface method. For example, if we will add @Override annotation to the isNull() method, it will result in compiler error.
Now when we will run the application, we get following output.
Interface Null Check
Impl Null Check
If we make the interface method from static to default, we will get following output.
Impl Null Check
MyData Print::
Impl Null Check
Java interface static method is visible to interface methods only, if we remove the isNull() method from the MyDataImpl class, we won’t be able to use it for the MyDataImpl object.


2. Functional interfaces and Lambda Expressions

An interface with exactly one abstract method is known as Functional Interface.
A new annotation @FunctionalInterface has been introduced to mark an interface as Functional Interface. @FunctionalInterface annotation is a facility to avoid accidental addition of abstract methods in the functional interfaces. It’s optional but good practice to use it.
Functional interfaces are long awaited and much sought out feature of Java 8 because it enables us to use lambda expressions to instantiate them. A new package java.util.function with bunch of functional interfaces are added to provide target types for lambda expressions and method references.


3. Java Stream API for collection classes

Before we look into Java 8 Stream API Examples, let’s see why it was required. Suppose we want to iterate over a list of integers and find out sum of all the integers greater than 10.
Prior to Java 8, the approach to do it would be:
private static int sumIterator(List<Integer> list) {
              Iterator<Integer> it = list.iterator();
              int sum = 0;
              while (it.hasNext()) {
                             int num = it.next();
                             if (num > 10) {
                                             sum += num;
                             }
              }
              return sum;
}
There are three major problems with the above approach:
1.      We just want to know the sum of integers but we would also have to provide how the iteration will take place, this is also called external iteration because client program is handling the algorithm to iterate over the list.
2.      The program is sequential in nature, there is no way we can do this in parallel easily.
3.      There is a lot of code to do even a simple task.
To overcome all the above shortcomings, Java 8 Stream API was introduced. We can use Java Stream API to implement internal iteration, that is better because java framework is in control of the iteration.
Internal iteration provides several features such as sequential and parallel execution, filtering based on the given criteria, mapping etc.
Most of the Java 8 Stream API method arguments are functional interfaces, so lambda expressions work very well with them. Let’s see how can we write above logic in a single line statement using Java Streams.
private static int sumStream(List<Integer> list) {
              return list.stream().filter(i -> i > 10).mapToInt(i -> i).sum();
}
Notice that above program utilizes java framework iteration strategy, filtering and mapping methods and would increase efficiency.


4.     Java Date Time API

Why do we need new Java Date Time API?

Before we start looking at the Java 8 Date Time API, let’s see why do we need a new API for this. There have been several problems with the existing date and time related classes in java, some of them are:
1.   Java Date Time classes are not defined consistently, we have Date Class in both java.util as well as java.sql packages. Again formatting and parsing classes are defined in java.text package.
2.   java.util.Date contains both date and time, whereas java.sql.Datecontains only date. Having this in java.sql package doesn’t make sense. Also both the classes have same name, that is a very bad design itself.
3. There are no clearly defined classes for time, timestamp, formatting and parsing. We have java.text.DateFormat abstract class for parsing and formatting need. Usually SimpleDateFormat class is used for parsing and formatting.
4.   All the Date classes are mutable, so they are not thread safe. It’s one of the biggest problem with Java Date and Calendar classes.
5. Date class doesn’t provide internationalization, there is no timezone support. So java.util.Calendar and java.util.TimeZone classes were introduced, but they also have all the problems listed above.

There are some other issues with the methods defined in Date and Calendar classes but above problems make it clear that a robust Date Time API was needed in Java.

Java 8 Date

Java 8 Date Time API is JSR-310 implementation. It is designed to overcome all the flaws in the legacy date time implementations. Some of the design principles of new Date Time API are:
1.    Immutability: All the classes in the new Date Time API are immutable and good for multithreaded environments.
2.     Separation of Concerns: The new API separates clearly between human readable date time and machine time (unix timestamp). It defines separate classes for Date, Time, DateTime, Timestamp, Timezone etc.
3.    Clarity: The methods are clearly defined and perform the same action in all the classes. For example, to get the current instance we have now()method. There are format() and parse() methods defined in all these classes rather than having a separate class for them.
All the classes use Factory Pattern and Strategy Pattern for better handling. Once you have used the methods in one of the class, working with other classes won’t be hard.
4.    Utility operations: All the new Date Time API classes comes with methods to perform common tasks, such as plus, minus, format, parsing, getting separate part in date/time etc.
5.     Extendable: The new Date Time API works on ISO-8601 calendar system but we can use it with other non ISO calendars as well.

Java 8 Date Time API Packages

Java 8 Date Time API consists of following packages.
1.      java.time Package: This is the base package of new Java Date Time API. All the major base classes are part of this package, such as LocalDateLocalTimeLocalDateTimeInstantPeriodDuration etc. All of these classes are immutable and thread safe. Most of the times, these classes will be sufficient for handling common requirements.
2.      java.time.chrono Package: This package defines generic APIs for non ISO calendar systems. We can extend AbstractChronology class to create our own calendar system.
3.      java.time.format Package: This package contains classes used for formatting and parsing date time objects. Most of the times, we would not be directly using them because principle classes in java.time package provide formatting and parsing methods.
4.      java.time.temporal Package: This package contains temporal objects and we can use it for find out specific date or time related to date/time object. For example, we can use these to find out the first or last day of the month. You can identify these methods easily because they always have format “withXXX”.
5.      java.time.zone Package: This package contains classes for supporting different time zones and their rules.




Attend Online Java Certification Training and excel your career

Hello Java Developer,  Are you staying at home and worried about your future? Do not waste the time in worrying. International certifi...