Monday, 13 November 2017

Introduction to Kotlin

Kotlin is a high-level programming language runs on JVM. Kotlin compiles the sources code into java byte code and runs the application using jvm. You can use java and kotlin interchangeably, means you can call a kotlin function from Java and vice versa.

Prerequisites
Java fundamentals are necessary. If you are new to Java, I would suggest you to go through java tutorial for beginners.

Is Kotlin Object oriented?
Yes, Kotlin is object oriented language, you can create classes, objects, and apply oops concepts like polymorphism, inheritance etc.,

Is kotlin functional?
Yes, Kotlin is a functional language. In functional programming lngauge, functions are basic building blocks, you can return a function, pass a function as argument to other function etc.,

I would recommend you to go through my post, to know more about functional programming.

Is Kotlin open source?
Yes

What kind of application Can I develop using Kotlin?
a.   Build Mobile Applications
b.   Develop server side applications
c.   You can develop any application, that can be developed in Java

Can I run kotlin code in web browser?
Kotlin can be compiled to JavaScript, so you can run the applications in browser.

Is Kotlin statically typed?
Yes kotlin is statically typed language. For statically typed languages, type of the variable is known at compile time. You can refer my post statically vs dynamically typed languages to know the difference between statically and dynamically typed languages.

Can kotlin infer type?
Yes, unlike Java, you no need to specify the type while defining the variable. Kotlin infer the type based on the context.

Ex
var name = "Krishna"
Since "Krishna" is assigned to the variable ‘name’, koltin infer the type as String.

var age = 28
Since number 28 is assigned to the variable ‘age’, kotlin infer the type as int.

Previous                                                 Next                                                 Home

Kotlin for Beginners

Kotlin Basics

      Introduction to Kotlin
      Install Kotlin
            Installing Kotlin in command line mode
            Install kotlin using brew command
      Hello World program
      Setting up Kotlin in Eclipse
      Variables

Data types

      Data types
      nullable types
      Numbers
      Characters
      Convert character to Int
      Booleans
      Strings
      String template expressions

Arrays

      Arrays
      Define Array of nulls
      Define array using factory function
      Print array elements

Operators, Control flow statements

      Bit wise operators
      Logical Operators
      === vs ==
      Control flow statements
      if statement
      if-else statement
      if-else if-else
      Why there is no ternary operator in kotlin?
      when expression
      Using when as if-else if ladder
      Use When as expression
      for loop
      while, do-while loops
      break statement
      continue statement

Working with classes

      Classes and objects
      Declaring properties
      getters & setters
      Define member functions of class
      initialize member properties
      const: Compile time constants
      const vs val
      Late initialized properties
      Body of the class is optional
      Constructors
      Is Kotlin class requires body?
      Secondary Constructors
      Passing default values to primary constructor
      Default constructor
      Define private primary constructor
      How to create Object
      Any: Super class of all classes
      Inheritance
      Overriding methods
      Overriding properties
      Calling super class methods
      Nested classes
      Inner classes
      Interfaces
      Overriding conflict while implementing interfaces
      Object Expressions
      Define singleton objects
      Companion Objects
      Anonymous Inner classes
      Access super class of outer class from inner class
      Abstract classes
      ?.: Safe call operator: handle nullable types
      ?: Elvis operator

Functions

      Functions
      Call functions using parameter names
      Function default arguments
      varargs : Variable number of arguments
      unit (or) void functions
      Single Expression functions
      infix functions
      Local functions
      Member functions
      Tail recursive functions
      Higher Order function
      Lambda Expressions
      Anonymous functions

Packages, extensions, data classes and Generics

      Packages
      Access specifiers
      Extensions
      Extensions to companion object
      Scope of extension functions
      Declare extensions as members of other class
      Overriding extensions
      Data classes
      Data Classes: copy function
      Data classes: Destructuring declarations
      Generics

Previous                                                 Next                                                 Home

Monday, 6 November 2017

How to generate random bytes in Java?

There are many ways to generate random bytes in Java.

         a. Using nextBytes() method of Random class
         b. Using nextBytes method of SecureRandom class
         c. Using SecureRandom.getInstanceStrong().nextBytes(bytes)
         d. Using ThreadLocalRandom.current().nextBytes(bytes)
        
Using nextBytes() method of Random class
Random class provides nextBytes() method, it takes a byte array as argument and fill the input byte array with random bytes.

                 Random random = new Random();
                 byte[] b = new byte[20];
                 random.nextBytes(b);
                
RandomDemo.java
package com.sample.Random;

import java.util.Random;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

  public static void main(String args[]) {
    Random random = new Random();
    byte[] b = new byte[20];
    random.nextBytes(b);
    printArray(b);
  }
}

Sample Output
-56,108,-21,-73,83,1,-2,-117,-52,-66,-96,-51,89,-79,100,-106,121,68,79,81,

Using nextBytes method of SecureRandom class
'java.security.SecureRandom' class provides nextBytes method, it takes byte array as argument and fill the byte array with random bytes. I would prefer to use Secure Random to generate random numbers than Random. It is because, Random class uses System clock to generate the seed, where as SecureRandom class uses random data from operating system (For ex interval betweem keystorkes, cpul cycles etc.,) to generate the seed. SecureRandom is more secure as compared to Random.

                 SecureRandom random = new SecureRandom();
                 byte[] b = new byte[20];
                 random.nextBytes(b);
                

RandomDemo.java
package com.sample.Random;

import java.security.SecureRandom;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

  public static void main(String args[]) {
    SecureRandom random = new SecureRandom();
    byte[] b = new byte[20];
    random.nextBytes(b);
    printArray(b);
  }
}

Sample Output
9,62,-83,114,6,70,68,-63,-94,33,-100,-75,-91,-36,-60,-26,27,-116,64,-113,

Using SecureRandom.getInstanceStrong().nextBytes(bytes)
SecureRandom.getInstanceStrong() is avialble in Java1.8. 'SecureRandom.getInstanceStrong()' returns a secure random object that was selected by using the algorithms/providers specified in the securerandom.strongAlgorithms (Ex: Windows-PRNG:SunMSCAPI,SHA1PRNG:SUN)

Get the algorithms specified in 'securerandom.strongAlgorithms'
By using below statements, you can get the algorithms specified in 'securerandom.strongAlgorithms' property
                 String randomAlgorithms = Security.getProperty("securerandom.strongAlgorithms");
                 System.out.println(randomAlgorithms);

Below statements are used to generate random bytes.
                 SecureRandom random = SecureRandom.getInstanceStrong();
                 byte[] b = new byte[20];
                 random.nextBytes(b);
        

RandomDemo.java
package com.sample.Random;

import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

  public static void main(String args[]) throws NoSuchAlgorithmException {
    SecureRandom random = SecureRandom.getInstanceStrong();
    byte[] b = new byte[20];
    random.nextBytes(b);
    printArray(b);

  }
}


Sample Output
73,-22,-8,-24,-80,-50,113,-33,-34,-69,104,-66,-74,-114,-104,-118,102,-26,-106,-72,

Prefer to use 'SecureRandom.getInstanceStrong()' over all other methods

Using nextBytes method of ThreadLocalRandom class
Below statements are used to generate random numbers.
                 ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
                 byte b[] = new byte[20];
                 threadLocalRandom.nextBytes(b);


RandomDemo.java
package com.sample.Random;

import java.security.NoSuchAlgorithmException;
import java.util.concurrent.ThreadLocalRandom;

public class RandomDemo {
  private static void printArray(byte[] byteArr) {
    for (byte b : byteArr) {
      System.out.print(b + ",");
    }
  }

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

    ThreadLocalRandom threadLocalRandom = ThreadLocalRandom.current();
    byte b[] = new byte[20];
    threadLocalRandom.nextBytes(b);
    printArray(b);
  }
}





Friday, 3 November 2017

Implement a stream that writes to multiple streams

Implement a OutputStream such that, when you write some information to this stream, it will write to multiple streams.

One of my friend got this interview question, I feel interviewer asked this question to check how comfortable he is while handling streams. The question is abstract, but interviewer seems to be expecting whether the implementation is handling all the cases or not.

Let’s break the question into small tokens.

When you write some information to the stream it should write to multiple streams.
From this statement, it is clear that the stream that we are going to implement should handle multiple output streams.
public class MultiOutputStream extends OutputStream {

 private List<OutputStream> outStreams;

 public MultiOutputStream(OutputStream... outputStreams) {

  if (outputStreams == null) {
   throw new IllegalArgumentException("outputStreams should not be null");
  }

  outStreams = new ArrayList<>();

  for (OutputStream outStream : outputStreams) {
   if (outStream != null) {
    outStreams.add(outStream);
   }
  }
 }

 .....
 .....
 .....
}

Override write methods
Since OutputStream writes information to the streams, we need to override write methods such that, whenever you call write method on this stream, it should call the write operation on all underlying streams.
 @Override
 public void write(int b) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b);
  }
 }

What about flush and close operations?
Implementation is similar like how we implemented write method in previous step. Whenever user calls flush, we need to flush all the underlying streams and whenever close() is called on this stream, it should close all the underlying streams.
 @Override
 public void flush() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.flush();
  }
 }

 @Override
 public void close() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.close();
  }
 }


Find the below working application.

MultiOutputStream.java
package com.sample.streams;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Output stream class to write to multiple streams.
 * 
 *
 */
public class MultiOutputStream extends OutputStream {

 private List<OutputStream> outStreams;

 public MultiOutputStream(OutputStream... outputStreams) {

  if (outputStreams == null) {
   throw new IllegalArgumentException("outputStreams should not be null");
  }

  outStreams = new ArrayList<>();

  for (OutputStream outStream : outputStreams) {
   if (outStream != null) {
    outStreams.add(outStream);
   }
  }
 }

 @Override
 public void write(int b) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b);
  }
 }

 @Override

 public void write(byte b[]) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b);
  }
 }

 @Override
 public void write(byte b[], int off, int len) throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.write(b, off, len);
  }
 }

 @Override
 public void flush() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.flush();
  }
 }

 @Override
 public void close() throws IOException {
  for (OutputStream outputStream : outStreams) {
   outputStream.close();
  }
 }
}

Test.java
package com.sample.streams;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;

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

  PrintStream fileStream1 = new PrintStream(new FileOutputStream("outputFile1.log", true));
  PrintStream fileStream2 = new PrintStream(new FileOutputStream("outputFile2.log", true));

  try (MultiOutputStream multiOutputStream = new MultiOutputStream(fileStream1, fileStream2, System.out)) {
   multiOutputStream.write(new String("Hello World").getBytes());
  }

 }
}



Thursday, 2 November 2017

Redirect System out and error messages to files programmatically

java.lang.System class provides setErr, setOut methods to reassign error and output streams. In this post, I am going to show how to redirect the 'System.out' messages to 'output.log' and error messages to 'error.log' by using setOut and setErr methods.

Below step-by-step procedure explains how to redirect the output and error messages to output.log and error.log files.

Step 1: Define two PrintStream instances, one should point to 'output.log' and other should point to 'error.log'.
PrintStream pOut = new PrintStream(new FileOutputStream("output.log", true));
PrintStream pErr = new PrintStream(new FileOutputStream("error.log", true));

Step 2: Set the output and error streams using setOut and setErr methods
System.setOut(pOut);
System.setErr(pErr);

Find the below working application.

Test.java
package com.sample.streams;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;

public class Test {
 public static void main(String args[]) throws FileNotFoundException {

  try (PrintStream pOut = new PrintStream(new FileOutputStream("output.log", true));
    PrintStream pErr = new PrintStream(new FileOutputStream("error.log", true))) {
   System.setOut(pOut);
   System.setErr(pErr);

   System.out.println("Hello World");
   System.err.println("Got Error");
  }

 }
}

Wednesday, 1 November 2017

Remove element at given index from array

In java, arrays are fixed in size, you can’t increase/decrease the size of the array after initialization. To solve this problem, we need to return new array by not including the element at given index of input array.

Below code snippet do that.
 public static Object removeEleAtIndex(Object array, int index) {
  if (array == null || index < 0) {
   return array;
  }

  int length = Array.getLength(array);

  if (index > length - 1) {
   return array;
  }

  Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);

  System.arraycopy(array, 0, result, 0, index);
  System.arraycopy(array, index + 1, result, index, length - index - 1);
  return result;
 }

Find the below working application.

ArrayUtil.java
package com.sample.collections;

import java.lang.reflect.Array;

public class ArrayUtil {

 /**
  * Remove element at given index and return new array
  * 
  * @param array
  * @param index
  * 
  * @return array, if array is null (or) index < 0 (or) index is > number of
  *         elements in array
  */
 public static Object removeEleAtIndex(Object array, int index) {
  if (array == null || index < 0) {
   return array;
  }

  int length = Array.getLength(array);

  if (index > length - 1) {
   return array;
  }

  Object result = Array.newInstance(array.getClass().getComponentType(), length - 1);

  System.arraycopy(array, 0, result, 0, index);
  System.arraycopy(array, index + 1, result, index, length - index - 1);
  return result;
 }

 public static void printArrayToConsole(Object array) {
  for (int i = 0; i < Array.getLength(array); i++) {
   System.out.println(Array.get(array, i));
  }
 }
}


Test.java
package com.sample.collections;

public class Test {

 public static void main(String args[]) {
  int[] arr = { 2, 3, 5, 7, 11, 13, 17 };

  int[] result = (int[]) ArrayUtil.removeEleAtIndex(arr, 4);
  ArrayUtil.printArrayToConsole(result);
 }
}