Wednesday, September 23, 2015

how to read file into string in java 8

Many times you want to read contents of a file into String, but, unfortunately, it was not a trivial job in Java, at least not until JDK 1.7. In Java 8, you can read a file into String in just one line of code. Prior to the release of new File IO API, you have to write lot of boilerplate code e.g. open an input stream, convert that input stream into a Reader, and then wrap that into a BufferedReader and so on.

Reading File to String in Java

In order to understand the beauty of Java 7 way of reading the file into String, first, let's see how we used to do it on Java 1.5 and 6.

InputStream is = new FileInputStream("manifest.mf");
BufferedReader buf = new BufferedReader(new InputStreamReader(is));
        
String line = buf.readLine();
StringBuilder sb = new StringBuilder();
        
while(line != null){
   sb.append(line).append("\n");
   line = buf.readLine();
}
String fileAsString = sb.toString();
System.out.println("Contents : " + fileAsString);

You can see that it's not easy, you need to write a lot of unnecessary boilerplate code. This is even when we are just writing for the demo, forget about production quality code when you have to handle exceptions properly. Worth noting is that, in this example we are using platform's default character encoding, which is fine because manifest.mf has not contained any character other than ASCII, but it's not a safe way, if you don't know the encoding, by default use "UTF-8". Now let's see how you can read a file as String in JDK 1.7
String contents = new String(Files.readAllBytes(Paths.get("manifest.mf")));
System.out.println("Contents (Java 7) : " + contents);
You can see there is no more wrapping around different class, no more loop, no more handling of special condition, just a method call to read whole file as byte array and then create String from it. Just like our previous example, this is also using platform's default character encoding. Let's see how can we provide a custom character encoding of our choice:
String fileString = new String(Files.readAllBytes(Paths.get("manifest.mf")), StandardCharsets.UTF_8);
System.out.println("Contents (Java 7 with character encoding ) : " + fileString);
Now does it get any simpler with Java 8 Streams and lambda expression, well it does, as we have seen on my earlier article about how to read file in Java 8, its same as Java 7, how can you go less than one line, but yes you can use Stream and its lazy evaluation for your benefit :
Files.lines(Paths.get("manifest.mf"), StandardCharsets.UTF_8).forEach(System.out::println);

You should get familiar with new File API, it's really helpful to do efficient file IO in Java, as shown below: How to read file into String in Java 8
package thinkwithjava;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;


/**
 * Java Program to demonstrate different ways to loop over collection in 
 * pre Java 8 and Java 8 world using Stream's forEach method.
 * @author RD
 */
public class FileToStringJava8 {

    public static void main(String args[]) throws IOException {

        // How to read file into String before Java 7
        InputStream is = new FileInputStream("manifest.mf");
        BufferedReader buf = new BufferedReader(new InputStreamReader(is));
        
        String line = buf.readLine();
        StringBuilder sb = new StringBuilder();
        
        while(line != null){
            sb.append(line).append("\n");
            line = buf.readLine();
        }
        
        String fileAsString = sb.toString();
        System.out.println("Contents (before Java 7) : " + fileAsString);
        
        
        // Reading file into Stirng in one line in JDK 7
        String contents = new String(Files.readAllBytes(Paths.get("manifest.mf")));
        System.out.println("Contents (Java 7) : " + contents);
        
        
        
        // Reading file into String using proper character encoding
        String fileString = new String(Files.readAllBytes(Paths.get("manifest.mf")), StandardCharsets.UTF_8);
        System.out.println("Contents (Java 7 with character encoding ) : " + fileString);
        

        // It's even easier in Java 8
        Files.lines(Paths.get("manifest.mf"), StandardCharsets.UTF_8).forEach(System.out::println);
        
    }


}

That's all about how to read the file into String in Java. Though this is good for the small tasks where you need contents of file as String in your program, don't read a large file of few Gigabytes like that, otherwise your Java program will run out of memory, instead use InputStream. Also, always remember to use character encoding while converting binary data to character data. If you are unsure, just use UTF-8 as default.

Friday, September 11, 2015

Generic Type changes and improvements in Java 8

Java 8 propose some improvements to the existing type-argument inference support that will significantly reduce the need for explicit type-arguments in generic method calls.
1.     Inference in argument position
Consider the following class declaration:

class List {
   static  List nil() { ... };
   static  List cons(Z head, List tail) { ... };
   E head() { ... }
}

The result of a generic method, such as List.nil() may be inferred from the right-hand side of an assignment:

List ls = List.nil();

The compiler's type-inference mechanism figures out that the type-argument to the List.nil() call is indeed String. It seems reasonable that the compiler should be able to infer the type when the result of such a generic method invocation is passed to another method, as below:
List.cons(42, List.nil()); //error: expected List of Integer , found List of Object

Unfortunately, this is not allowed in JDK 5/6/7 -- the only option available to the programmer is to use an explicit type-argument:
List.cons(42, List.nil());

It would be nice if type-argument inference would be extended to consider the formal parameter type in a method call (target typing).

2.  Inference in chained calls

Another fairly common problem is when generic method calls are chained together, as below:
String s = List.nil().head(); //error: expected String, found Object

The right-hand type in the above assignment is unused during type-argument inference -- as a result, the only option for the programmer is (again) to manually specify type-arguments, as in:
String s = List.nil().head();

Again, it would be nice to remove the burden of explicit type-arguments by allowing the right-hand type of the assignment (String) to flow through the chain of generic method calls.


Switch in Java 7

In java 7 we got some significant improvement that is worth noting. Before Java 7 it was only possible to check Integer expressions in switch statements but after Java 7 you can use String Object in the expression of a switch statement.

Example:
/**
 * 
 */
package com.blogspot.thinkwithjava;

/**
 * Program to show the use of String comparison in Switch statements
 * 
 * @author RD
 * 
 */
public class SwitchWithString {

 public String getTypeOfDayWithSwitchStatement(String dayOfWeekArg) {
  String typeOfDay;
  switch (dayOfWeekArg) {
  case "Monday":
   typeOfDay = "Start of work week";
   break;
  case "Tuesday":
  case "Wednesday":
  case "Thursday":
   typeOfDay = "Midweek";
   break;
  case "Friday":
   typeOfDay = "End of work week";
   break;
  case "Saturday":
  case "Sunday":
   typeOfDay = "Weekend";
   break;
  default:
   throw new IllegalArgumentException("Invalid day of the week: "
     + dayOfWeekArg);
  }
  return typeOfDay;
 }

 /**
  * @param args
  */
 public static void main(String[] args) {
  SwitchWithString sws = new SwitchWithString();

  System.out.println("Monday is a "
    + sws.getTypeOfDayWithSwitchStatement("Monday"));

 }

}

Output is: Monday is a Start of work week


Monday, September 7, 2015

Different ways of calculating Factorial in java

Problem : Write a program to calculate factorial of a given number in Java.

Explanation: If you come from Maths background then you know that factorial of a number is number*(factorial of number -1). You will use this formula to calculate factorial in this  Java tutorial. Since factorial is a naturally recursive operation, it make sense to use recursion to solve this problem but its not always the best way.

By the way, factorial of numbers grows very quickly and even the largest integral data type in Java, long is not able to hold factorial of anything or above 50. In such cases you can use BigInteger, which has theoretically no limit and can be used to represent very large integral numbers.
We can calculate Factorial by following 3 ways:

  1. Using recursion 
  2. Using Loop
  3. Using Dynamic Programming.
Solution 1 : Factorial using recursion

In order to create a recursive solution you need a base case where program terminates and in this problem base case is factorial of 1, which is 1. So if given number is greater than 1, we keep applying factorial formula and recursive call this method with n - 1 as shown below :

public static long factorial(int number){        
        //base case - factorial of 0 or 1 is 1
        if(number <=1){
            return 1;
        }        
        return number*factorial(number - 1);
    }

Once input become 1 the method stopped recursive call and return 1. From there onward stack started to roll down and finally factorial of number is calculated.

Example:
import java.util.Scanner;

/** Java Program to calculate factorial using loop
 *
 * @author RD 
 * 
 **/

public class Factorial {

   public static void main(String[] args) {
       Scanner scanner = new Scanner(System.in);
       System.out.print("Enter the number whose factorial is to be found: ");
       int n = scanner.nextInt();
       int result = factorial(n);
       System.out.println("The factorial of " + n + " is " + result);
   }

   public static int factorial(int n) {
       int result = 1;
       for (int i = 1; i <= n; i++) {
           result = result * i;
       }
       return result;
   }
}


Solution 2 : Factorial using loop
As I said instead of using recursion and calling factorial method again you can also use for loop to calculate factorial because !n = n*(n-1)*(n-2).....*1 , which can easily be implemented using loop as shown below :


public static long factorial(long input){
        long factorial = 1L;
        for(long i= input; i > 0; i--){
            factorial = factorial * i;
        }
        
        return factorial;
    }
You can see that we start with the number and multiply it with the factorial which is initialized with 1 then we reduce the number by 1 until number becomes 1, which is nothing but n*(n-1)*(n-2).....*1.  
Why we use Recursion in methods? 

  1. Code is easier to read 
  2. Less lines of code
  3. Problem solving approach is somewhat divide and conquer: Solve bigger problem by solving simpler sub problems.
Example
/**
  * Java Factorial Using Recursion Example
  * This Java example shows how to generate factorial of a given number using recursive function.
  * @author RD
**/
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
public class JavaFactorialUsingRecursion {
       
        public static void main(String args[]) throws NumberFormatException, IOException{
               
                System.out.println("Enter the number: ");
               
                //get input from the user
                BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                int a = Integer.parseInt(br.readLine());
               
                //call the recursive function to generate factorial
                int result= fact(a);
               
               
                System.out.println("Factorial of the number is: " + result);
        }
       
        static int fact(int b)
        {
                if(b <= 1)
                        //if the number is 1 then return 1
                        return 1;
                else
                        //else call the same function with the value - 1
                        return b * fact(b-1);
        }
}

Solution 3 : Factorial using dynamic programming

Dynamic Programming is similar to Recursion in which we break the problem into subproblems and use them to arrive at the final solution. However, it is different from Recursion as we store results of already solved subproblems to avoid re- calculation. Caching of results leads to better time complexity of code at the cost of space complexity.



public static long factorial(int n)
{
    if (n >= 0) 
    {
        result[0] = 1;
        for (int i = 1; i <= n; ++i) 
        {
            result[i] = i * result[i - 1];
        }
        return result[n];
    }
}
Dynamic Programming approach will be caching the solved sub problems and will be more efficiently execute in linear time.

Friday, September 4, 2015

Oracle Nashorn! The Node.js on JVM

Oracle Nashorn: A Next-Generation JavaScript Engine for the JVM


Nashorn is the new JavaScript Runtime that comes with Java 8 and runs on the JVM.

In this post we will see how to run simple 
Node.js applications with Nashorn on the JVM.

Avatar.js is a project to bring the node programming model, APIs and module ecosystem to the Java platform. Unfortunately Avatar.js does not officially provide a binary distribution and the build process looks quite intricate (involving Python and C++).

There is also 
Project Avatar, an upcoming web-platform by Oracle. Project Avatar builds uponAvatar.js.

By reverse-engineering Project Avatar I found the necessary artefacts of Avatar.js in the java.net Maven repository. These artefacts can be used to run Node applications with Avatar.js without having to build Avatar.js yourself.

The following steps show how to run a simple Node.js web application on OSX. The steps should be very similar for Linux or Windows.

1.            Download avatar-js.jar from the java.net Maven Repo.
Current version is here:https://maven.java.net/content/repositories/public/com/oracle/avatar-js/0.10.25-SNAPSHOT/
Example file: avatar-js-0.10.25-20140313.063039-43.jar 

2.            Download the native library avatar-js.dylib from the java.net Maven Repo.
Current version is here:https://maven.java.net/content/repositories/public/com/oracle/libavatar-js-macosx-x64/0.10.25-SNAPSHOT/
Example file: libavatar-js-macosx-x64-0.10.25-20140312.062209-35.dylib
For Linux you would download the corresponding 
.so file from ../libavatar-js-linux-x64/0.10.25-SNAPSHOT/
For Windows you would download the corresponding 
.dll file from ../libavatar-js-win-x64/0.10.25-SNAPSHOT/

3.            Rename the native library to avatar-js.dylib and rename the jar to avatar-js.jarand put both in a directory called dist

4.            Create a simple Node.js app in the a file called app.js:

var http = require('http');

// Configure our HTTP server to respond with Hello World to all requests.
var server = http.createServer(function (request, response) {
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.end("Hello World\n");
});

// Listen on port 8000, IP defaults to 127.0.0.1
server.listen(8000);

// Put a friendly message on the terminal
console.log("Server running at http://127.0.0.1:8000/");

Run the command: 
java -Djava.library.path=dist -jar dist/avatar-js.jar app.js

  1. The output should be: Server running at http://127.0.0.1:8000/ 
  2.  Navigate to  http://localhost:8000/

Wednesday, September 2, 2015

How to use BigInteger class in Java

Some time we need to store some really big numbers. Though we are already using the primitive data types int and long. But sometime we need to store values which cannot be held by these data type.

We will understand the problem with the help of factorial calculation as follows:

If we are calculating factorial of 13 or more and will try to store it in int datatype then we will not get the correct result, and this will result in overflow.
Again if we are calculating factorial of 21 or more it cannot be held through long data type. It will give the same error as mentioned above.

To hold the factorial of 21 or more we need BigInteger class of java.math package. As name suggests BigInteger class is used to hold the really big number, something which is even bigger than maximum value of long primitive

e.g. 2^63 -1 or 9223372036854775807L. The java.math.BigInteger class provides all the operation similar to Java’s integer primitive and have all the relevant methods from Java.Math.

To declare a BigInteger we use:

BigInteger number = BigInteger.valueOf(long number);
Also worth noting that, similar to java.lang.String and other wrapper classes BigInteger is also Immutable in Java, which means its important to store result back into same variable, otherwise result of calculation will be lost. BigInteger stores numbers as 2's complement number like int primitive and support operation supported by int variables and all relevant methods from java.lang.Math class. Additionally it also provide support for modular arithmetic, bit manipulation, primality testing, prime generation, GCD calculation and other miscellaneous operations.

Important things about BigInteger class in Java
BigInteger class in Java is designed to deal with really large numbers in Java, but to do that it’s very important that you make yourself familiar with class. Here are some key points about java.math.BigInteger class :

1. The BigInteger class is used to represent arbitrarily large numbers. Overflow doesn't occur as is the case with int and long primitive.

2. The BigInteger class is immutable which means that the object on which the multiply function was invoked doesn't change the integer it is holding. The multiplication is performed and a new BigInteger is returned which needs to be stored in the variable fact.

3. BigInteger provides operations similar to int primitive type in Java, additionally it provide support for prime generation, bit manipulation, GCD calculations etc.

4. You can create BigInteger object by giving number as String or byte array using constructor, or you can convert a long value to BigInteger using valueOf() method as shown below :

BigInteger bigIntegerFromLong = BigInteger.valueOf(292909333L);
BigInteger bigIntegerFromString = new BigInteger("338948938948");
Java Program to Calculate Factorial of Large Number

Here is our sample Java program to calculate factorial for large numbers, well given number is not exactly large but the factorial value is definitely large. For example, factorial of 45 is 119622220865480194561963161495657715064383733760000000000, which is clearly out of bound for even a long data type. Since theoretically BigInteger has no limit it can hold these values as shown in following example.
There are many ways to calculate factorial like using recursion, dynamic programming or iteration. In following example we have used iteration to calculate factorial in Java.


import java.math.BigInteger;

/**
 * Write a Java program to calculate factorial of large numbers using
 * BigInteger.
 *
 * @author RD
 *
 */
public class LargeFactorialDemo {

    public static void main(String args[]) {

        System.out.printf("Factorial of 32 is %s %n", factorial(32));
        System.out.printf("Factorial of 0 is %s %n", factorial(0));
        System.out.printf("Factorial of 1 is %s %n", factorial(1));
        System.out.printf("Factorial of 5 is %s %n", factorial(5));
        System.out.printf("Factorial of 41 is %s %n", factorial(41));
        System.out.printf("Factorial of 45 is %s %n", factorial(45));

    }

    /*
     * Java method to calculate factorial of a large number
     * @return BigInteger factorial of given number
     */
    public static BigInteger factorial(int number) {
        BigInteger factorial = BigInteger.ONE;

        for (int i = number; i > 0; i--) {
            factorial = factorial.multiply(BigInteger.valueOf(i));
        }

        return factorial;
    }

}

Output
Factorial of 32 is 263130836933693530167218012160000000
Factorial of 0 is 1
Factorial of 1 is 1
Factorial of 5 is 120
Factorial of 41 is 33452526613163807108170062053440751665152000000000
Factorial of 45 is 119622220865480194561963161495657715064383733760000000000

You can see that how large factorial of 45 is, clearly its not possible to use long data type to store such huge integral values. You need to use BigInteger class to store such big values.


Hope you liked the post. Please consider leaving a comment and follow the blog.

Java garbage collection

In this post , we ’ ll take a look at how garbage collection works , why it ’ s important in Java , and how it works in...