Sunday, December 30, 2018

Java 8 at a glance

In Java  8 following are the major enhancement.

- Lambda Expression
- Method Reference for Lambda Expression
- Java Streams
- Improved Interface

    a) Now we can have concrete methods in an interface. It can be either static or default. Default methods can be overridden in implemented class. If a class implement two or more interface and there is a collision of default method then it is mandatory to override.
    b) Functional interface. For lambda expression we can define an interface as function it will have only one abstract method.
Here is an good article explaining in details # https://www.journaldev.com/2752/java-8-interface-changes-static-method-default-method

- Enhancement to Annotation
More details # https://www.javatpoint.com/java-8-type-annotations-and-repeating-annotations

- Parallel Array Sorting
    java.util.Arrays support sorting in parallel which will be faster.
- Hash Map performance improvement in case of Key collision
- Removed JDBC-ODBC bridge


More details on Java 8 features
http://www.oracle.com/technetwork/java/javase/8-whats-new-2157071.html

Friday, December 28, 2018

Java Streams

Streams are very popular feature in Java 8. Its another step in the direction of supporting functional programming in Java.
Streams are a way of accessing data from various data source. Data source can be an array, any java collection objects, I/O channel (like files, socket etc) or a generator function. One important thing is Streams are not data structure it doesn't store data, it just convey the data from data source.

Streams facilitate various computational operations like fetch, filter, sort, aggregate, search etc. in a efficient way. But all these operations produces a result while not changing its source.
Stream operations are of two types,  intermediate or terminal .Filter and map are examples of intermediate operation For each and reduce are terminal operation. Intermediate operation doesn't get executed instantly ,it creates a new stream. Only after terminal operation it get evaluated.

Intermediate operations are further divided into stateless or stateful. In case of stateless like filter or map no state of previous element is required. But in case of sateful eg: sort or distinct to process new element previous element details are necessary.

By default streams are executed sequential, Streams support parallelism also. So that the elements can be processed in parallel manner.  

Lets see some code.

package demo.streams;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamDemo {

public static void main (String args[])
{
String[] arr = {"python", "perl", "java", "java script", "c", "c++", "html", "sql"};
List<String> strList =  Arrays.asList(arr);
// steam creation
Stream<String> stream  = strList.stream();
// sort the elements
stream.sorted().forEach(System.out::println);
// find first element starts with j
Stream<String> filteredStream = strList.stream().filter(string-> string.startsWith("j"));
System.out.println(filteredStream.findFirst().get());
// in first 4 element how many elements start with p
System.out.println(strList.stream().limit(4).filter(str->str.startsWith("p")).count());
// map
// prepend hello begin of each string
strList.stream().map(str->"Hello "+str).forEach(System.out::println);
// close
filteredStream.close();
stream.close();
// parallel Stream, count the number of letters
strList.parallelStream().map(str->str + "="+ str.length()).forEach(System.out::println);
}
}


Saturday, December 22, 2018

tnsnames.ora parsing in java

tnsnames.ora is a configuration file which store the information about network service names and connect descriptor. These information are vital to connect the database.  More details about tnsora can be found here. https://docs.oracle.com/database/121/NETRF/tnsnames.htm#NETRF259

The configurations are defined key value manner. value can be literal or one or multiple key values again. Syntax rule can be found here https://docs.oracle.com/cd/A57673_01/DOC/net/doc/NWUS233/apb.htm                                            
To parse the same in Java please refer below code


import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.Stack;

public class TnsOraParser {
private static final String COMMENT = "#";
private Stack<Parameter> stack = new Stack<Parameter>();
private List<Parameter> netServiceNames = new ArrayList<Parameter>();
private boolean bracketOpen;
public TnsNamesOra parse(InputStream is) {
Scanner scan = new Scanner(is);
StringBuilder buffer = new StringBuilder();
boolean quote = false;
while (scan.hasNextLine()) {
String aLine = scan.nextLine();
aLine = aLine.trim();
if (aLine.startsWith(COMMENT)) {
continue;
}

for (int i = 0; i < aLine.length(); i++) {
char ch = aLine.charAt(i);
if (ch == '"')
{
quote = !quote;
}
else if (quote)
{
buffer.append(ch);
continue;
}
else if (ch == ' ' || ch == '\n' || ch == '\r') {
continue;
}
if (ch == '=')
{
gotNewParam(buffer);
}
else if (ch == '(')
{
bracketOpen = true;
}
else if (ch == ')')
{
bracketOpen = false;
Parameter cp = stack.pop();
if (cp != null)
{
if (buffer.length() > 0)
{
cp.setValue(buffer.toString());
buffer.delete(0, buffer.length());
}
if (!stack.isEmpty())
{
stack.peek().addParm(cp);
}
}
}
else
{
buffer.append(ch);
}
}
}
scan.close();
return new TnsNamesOra(netServiceNames);
}

private void gotNewParam(StringBuilder buffer) {
Parameter param = new Parameter(buffer.toString());
if (!bracketOpen && stack.size() == netServiceNames.size())
{
netServiceNames.add(param);
}
buffer.delete(0, buffer.length());
stack.push(param);
}

public static void main(String args[]) throws Exception {
FileInputStream testFile = new FileInputStream("D:\\Work\\tnsnames.ora");
TnsOraParser tnsOraParser = new TnsOraParser();
TnsNamesOra tnsOra = tnsOraParser.parse(testFile);
System.out.println(tnsOra.getServiceNames());
}
}


Parameter .java
==============

import java.util.ArrayList;
import java.util.List;

public class Parameter {
private String name;
private String value;
private List<Parameter> parameters;

public Parameter(String name) {
this.name = name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getValue() {
return value;
}

public void setValue(String value) {
this.value = value;
}

public List<Parameter> getParameters() {
return parameters;
}

public void setParameters(List<Parameter> parameters) {
this.parameters = parameters;
}

public void addParm(Parameter cp) {
if (parameters == null) {
parameters = new ArrayList<Parameter>();
}
parameters.add(cp);
}

public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append(name + "=(" );
if (value != null)
{
sb.append(value);
}
else if (parameters != null)
{
for (Parameter param : parameters)
{
sb.append(param);
}
}
sb.append(")");
return sb.toString();
}


}

TnsNamesOra.java
==================

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class TnsNamesOra {
private List<Parameter> netServiceName;
private final String DESCRIPTION_LIST = "DESCRIPTION_LIST";
private final String DESCRIPTION = "DESCRIPTION";
private final String ADDRESS_LIST = "ADDRESS_LIST";
private final String ADDRESS = "ADDRESS";
private final String PROTOCOL = "PROTOCOL";

public TnsNamesOra(List<Parameter> netServiceNames) {
this.netServiceName = netServiceNames;
}

public List<String> getServiceNames() {
List<String> serviceNames = null;
if (netServiceName != null) {
serviceNames = new ArrayList<String>();
for (Parameter param : netServiceName) {
serviceNames.add(param.getName());
}
}
return serviceNames;
}


}



Sunday, December 16, 2018

Java Interview Preparation article : OOPS concept

This is continuation of Java Interview Preparation . Here we will see OOPS concept. Encapsulation, Abstraction, Inheritance and Polymorphism are the basic pillars of object oriented programming language. And how Java adhere to these principle is crucial. These topics are covered in almost all the java book or can be found over internet also. Here is one link.

While answering abstraction and encapsulation it may sound overlapping. My explanation for encapsulation is, inside class all the members would be private to prohibit direct access of them from out side of the class. The public methods are for carry out various operation. And the caller of those methods need not know the internal implementation, only the meaning of required arguments to invoke the method is sufficient to achieve the goal. This is called abstraction.

In Java inheritance is achieved by "extends" and "implements" key word. It means either by extending another class or implementing a interface.
Child class is always a super set of parent class. Its also known as "is a" relation ship. There cloud be many questions under this topic. How the objects get created, the order of invocation of constructors. How a parent class reference can hold a child class object etc. Why java doesn't allow multiple inheritance. What are marker interface ? Several questions fall under this.

This is an nice article to understand polymorphism. There are two aspects of this compile time polymorphism and run time polymorphism.

https://www.geeksforgeeks.org/dynamic-method-dispatch-runtime-polymorphism-java/
https://www.dineshonjava.com/compile-time-polymorphism-in-java/

There could be other question like difference between aggregation vs composition.
"is a" vs "has a"
How can you achieve multiple inheritance in java ? ( By interface)

But I feel the major three concepts will put you in good spot to attempt the question around it.

Sunday, December 9, 2018

Java Interview Preparation article :1

Time and again I get requests to write on preparation for interviews in Java. So I am planning to write series of post targeting interview preparation.
To start if the interview is for service based company the key is breadth. And for product based company its the depth. The exception for (breadth/depth) is directly proportional to years of experience.
Another point I want to make entry level roles (0 years to 5 years) you need to do well in java interview rounds to get selected. For more experience this round is kind of elimination round.

Topics in core Java

  1. OOPs concept
  2. Java key word, more priority to the latest released key words.
  3. Inheritance, interface, marker interface, abstract class and is a has a relationship  
  4. Enums
  5. The details about java.lang.Object 
  6. Strings 
  7. Exception handling
  8. Collections 
  9. Threads and Concurrent Package
  10. Design Pattern
All these topics will cover good amount of ground. There might be some here and there question about garbage collection, jvm architecture, java memory management etc. Those questions were more relevant when java was dominant. Now we see the increase popularity of python, Scala so its kind of ok to focus energy in understanding other topics.

Once you get thorough these topic next stage is Java in web development, which we will see in another post.