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...