Java Stream API

I have been using Java Stream API massively these days. So I thought, why not write a short tutorial on it.

So what is steam anyway?

Don’t be confused with InputStream or OutputStream of Java IO. Stream are complete different thing in Java 8.

A stream basically represents a sequence of elements and provide a rich set of operations to compute those elements.

Its common to do bulk operation in our day to day business application. So normally we do use for loops and collections to do that, we iterate over the collection and then write if then else code and various variables come into play and we get a big chunk of ugly and sequential code.

We do the same thing using stream API but can abstract things in to a very high level using lambda and functional approach and write more elegant understandable and clean code. After having certain abstraction, we can do certain optimization, like we might want to go parallel, which was never easy before.

Well enough talk, lets do some code example –

1. First of all, lets remove regular for loop with IntStream. What I want to do is, print 1 to 10-

IntStream.range(0, 10)
          .forEach(value -> System.out.println(value));

Or just using method reference-


IntStream.range(0, 5)

2. I want to count number of elements in the list –

List<Integer> list = IntStream.range(1, 100).boxed().collect(Collectors.toList());;

3. I want to find average of all elements in the list –

Double avarage = -> item));

4. I want to get complete summery of the list

IntSummaryStatistics intSummaryStatistics = -> value));


//IntSummaryStatistics{count=99, sum=4950, min=1, average=50.000000, max=99}

5. Create a map out of the list

Map<Integer, Integer> map = -> p, q -> q * 3));


//{1=3, 2=6, 3=9, 4=12}

6. I want to get the maximum number of the list

        // first make a random integer list 
        List<Integer> randomInts = new Random().ints(-100, 100).limit(250).boxed().collect(Collectors.toList()); 
        Optional<Integer> max =; 
        max.ifPresent(value -> System.out.println(value)); 
        // or  
        max.ifPresent(System.out::println);// method reference 

7. Say I have a array of name and I want to count the name that starts wit ‘C’

String[] names = {"Fred Edwards", 
                "Anna Cox", 
                "Deborah Patterson", 
                "Ruth Torres", 
                "Shawn Powell", 
                "Rose Thompson", 
                "Rachel Barnes", 
                "Eugene Ramirez", 
                "Earl Flores", 
                "Janice Reed", 
                "Sarah Miller", 
                "Patricia Kelly", 
                "Carl Hall", 
                "Craig Wright", 
                "Martha Phillips", 
                "Thomas Howard", 
                "Steve Martinez", 
                "Diana Bailey", 
                "Kathleen Hughes", 
                "Russell Anderson", 
                "Theresa Perry"}; 
long c = Arrays.asList(names) 
                .filter(s -> s.startsWith("C")) 

8. Say I want to make all the name upper case and the sort and then print


An advance example

Say I have a class named Person ->

public class Person { 
    private String name; 
    private int age; 
    public String getName() { 
        return name; 
    public Person setName(String name) { = name; 
        return this; 
    public int getAge() { 
        return age; 
    public Person setAge(int age) { 
        this.age = age; 
        return this; 
    Person(String name, int age) { = name; 
        this.age = age; 
    public String toString() { 
        return name; 

9 . I want to get persons  group by age

        Map<Integer, List<Person>> collect = persons 

10  I want to get average age of all the persons

        Double collect1 = persons 

11. I want to print all the names that are eligible to vote in Bangladesh in a single string

        String sentence = 
                .filter(p -> p.getAge() >= 18) 
                .collect(Collectors.joining(" and ", " In Bangladesh ", " are of legal age for voting,")); 
        // In Bangladesh Rahim and Karim and Rehana and Rajib are of legal age for voting, 

To be continued …..

How to drop all tables in postgresql

Execute following commands:-

TO postgres;
TO public;
ON SCHEMA public IS 'standard public schema';

it works like a charm.

For details, please visit:

Gradle to maven conversion and vice versa

How to convert maven to gradle

The first thing is, you have to install gradle. Its easy. I know you can do it.  Go to the installing guide:

Now the second step is to run ‘gradle init‘ in the directory containing the POM file. This will  convert the maven build to a gradle build generating a setting.gradle file and one or  ore more build.gradle files.

Thats all.

How to convert gradle to maven

You just need to add  a maven plugin in your build.gradle.

Your build gradle should be like this-

apply plugin: 'java'
apply plugin: 'maven'

group = ''
// artifactId is taken by default, from folder name
version = '0.1-SNAPSHOT'

dependencies {
compile 'commons-lang:commons-lang:2.3'

Now run ‘gradle install‘ in the build.gradle folder.

Now you will find in the build/poms subfolder, a file called pom-default.xml which will contain the dependencies.

Now its all yours, copy it, customise it add up new stuff.

How to read call logs programmatically from android

It’s fairly easy. You need add following uses-permission in android manifest to get call history programmatically.

<uses-permission android:name="android.permission.READ_CONTACTS" />

That’s all here.

And then create an activity and layout. We need to query from ContentProvider. And for that I used CursorClassLoader.

Read about CursorLoader from here:


I want to load 4 properties and they are- phone Number, type of call eg. Outgoing or ingoing or missed call, Date and Time of the call and duration of the call.

So first use LoaderManager.LoaderCallbacks<Cursor> interface in your activity. It has three methods.

abstract Loader        onCreateLoader(int id, Bundle args)

//Instantiate and return a new Loader for the given ID.

abstract void      onLoadFinished(Loader loader, D data)

//Called when a previously created loader has finished its load.

abstract void      onLoaderReset(Loader loader)

//Called when a previously created loader is being reset, and thus making its data unavailable.

To initialize a query, we need to call LoaderManager.initLoader() at the very first place.

We are going to add a button and call this in that button events here and after this background framework will be initialized. As soon as the background framework is initialized, it calls your implementation of onCreateLoader(). To start the query, we have to return a CursorLoader from this method.


public Loader onCreateLoader(int loaderID, Bundle args) {
Log.d(TAG, "onCreateLoader() >> loaderID : " + loaderID);

switch (loaderID) {
// Returns a new CursorLoader
return new CursorLoader(
this,   // Parent activity context
CallLog.Calls.CONTENT_URI,        // Table to query
null,     // Projection to return
null,            // No selection clause
null,            // No selection arguments
null             // Default sort order
return null;


We are going access our expected data from a Cursor. And we will get this in the onLoadFinished() method.


    public void onLoadFinished(Loader loader, Cursor managedCursor) {
        Log.d(TAG, "onLoadFinished()");

        StringBuilder sb = new StringBuilder();

        int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
        int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
        int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
        int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);

        sb.append("<h4>Call Log Details <h4>");


        while (managedCursor.moveToNext()) {
            String phNumber = managedCursor.getString(number);
            String callType = managedCursor.getString(type);
            String callDate = managedCursor.getString(date);
            Date callDayTime = new Date(Long.valueOf(callDate));
            String callDuration = managedCursor.getString(duration);
            String dir = null;

            int callTypeCode = Integer.parseInt(callType);
            switch (callTypeCode) {
                case CallLog.Calls.OUTGOING_TYPE:
                    dir = "Outgoing";

                case CallLog.Calls.INCOMING_TYPE:
                    dir = "Incoming";

                case CallLog.Calls.MISSED_TYPE:
                    dir = "Missed";

                    .append("<td>Phone Number: </td>")
                    .append("<td>Call Type:</td>")
                    .append("<td>Date & Time:</td>")
                    .append("<td>Call Duration (Seconds):</td>")








Full Source code:



How the java code gets executed and performs better?

Please bear with my attempt to inform you a little regarding the execution of Java code.

Java’s code is compiled into byte code, which Java’s virtual machine executes.  This output is an intermediate language (IL) that is neither human readable nor machine-executable. Only the virtual machine understands it.  To execute this output, the virtual machine uses a Just in Time (JIT) compiler to interpret the byte code – so is Java an interpreted language as some people describe it, or is Java a compiled language?  The answer: Java is both.  Its source code is compiled with a static compiler into byte code – and then, the JIT interprets the compiler’s output.

From the previous description, one might be tempted to conclude that the JIT hurts performance, as it compiles during execution, a design that would seem to cause Java to run slowly. This conclusion, while intuitive, is incorrect.  The JIT actually performance quite well. At run time, it compiles byte code into machine code, which is later run by the JVM.   When Java executes, it executes machine code just as native code does – so it should run – discounting the JIT’s compilation costs – as fast as native code does.

However, C/C++ is generally regarding as providing better performance than Java does. The on-the-fly nature of Java’s execution lends credence to this thinking.  Compiling a piece of code into machine code takes a non-trivial amount of time.  If a language executes similar machine instructions but does not need compilation prior to the execution of them, then one can assume that the language in question runs faster than Java does – even when Java’s machine code output is maximally optimized.  However, Java isn’t maximally optimized, but C++ is not maximally optimized either.  No compiler can match the performance a top-notch assembly programmer who is an expert at manipulating the targeted hardware – so both Java and C++ can never be maximally optimized.  Making matters worse, both languages have inherent issues. Java must bear the reality that at least some of its code has to be compiled every time that it runs, and C++ is, when it must be generic, often not fully tailored to its hardware, as Java always is.  Even with the aforementioned handicap, one still expects Java’s compilation cost to give C++ in edge every scenario outside of very poorly coded or compiled C++.

However, appearances are deceiving; the JVM is a very intelligent environment and the JIT an intelligence compiler. For example, the JVM knows which methods are called frequently, as it maintains a count of each method’s calls.  When this count exceeds a certain threshold, the method’s machine code is kept, so that the JIT does not have to compile the method when it is called again – a decision that greatly reduces the cost of translating byte code into machine code.  Furthering this performance improvement, the JIT optimizes the most frequently used code. The JIT collects statistics to determine which parts of code fit this mold. Intelligent optimization of this ilk can, as Research indicates, yield big gains. Most research states that 80% of execution time is spent executing 20% of the code (“hot code”) – so optimizing these sections of code can yield sizeable performance benefits. The JIT optimizes “hot code.” It executes these sections in a highly optimized way directly on the operating system.  To achieve this goal, the JIT uses statistics to identify the “hot code.” In fact, Java performs even more optimization than efficiently executing “hot code.” It identifies the code that it executes the most and recompiles to run more efficiently than it previously did. These optimizations allow Java to achieve, in certain situations, better performance than C++ gives, without the need to resort to dangerous compiler settings or to dangerous optimization techniques.

Few resources to read:


I would like to thank my friend Collin Rusk for his help without which it would not be publish anyway.

Is it necessary to know everything about a programming language before starting to develop an application in it?

I want to build an application in Java that uses Swing, networking and databases (JDBC). However, the catch is that I donot know anything about these three fields. However, I do know some concepts of core java such as interfaces, inner classes, exceptions and debugging, collections, multithreading and I/O Streams.

I want to know if I “really” want to develop this application, should I wait and learn these concepts or should I jump right in? I am facing this as a severe mental handicap and would greatly appreciate some help here.

★ No

Answer by Bazlur Rahman Rokon:

So my suggestion would be, first learn a little stuff on swing, start developing the UI using swing, and then start learning few stuff on JDBC and then integrate your swing app with jdbc. And when you are little advance on these two, you may start networking stuff.
And doing all these, you will face problems, and thus you need to find more and learn more stuff to solve those problems.

Personally I loved this approach.

View Answer on Quora

Let’s play deep sleep

Do you ever take a train, bus, or cab? Do you ever fall asleep? Do you regularly miss your bus stop? Well, sleeping kit is here to help! Enter your destination into the application. When your transport is near your stop, sleeping kit will sound an alarm to alert you. If you’re asleep, the alarm will wake you up. If you’re forgetful, the alarm will remind you. Sleeping kit helps you travel more easily and effectively by removing part of the hassle.

Additionally you can share your location to anyone with sleeping kit easily.


You wanna give it try, right?

Get it on Google Play

Android Layout Property Initializer Plugin for IntelliJ IDEA

Well, the very first version of IntelliJ IDEA plugin that I wrote over the last two nights, is now available for public use. This is nothing big, just a little, doing for fun. Any feedback would be greatly appreciated.

General instruction

  1. First, download it from here.
  2. Just install it as you normally install plugin. Go to settings, then plugins and then click on the button named “Install from disk” and then locate it.
  3. Restart your IDE.

Now you can create an android project, create an activity and a layout. Design your layout.

Click on the image for further instruction.



or watch in

NB: I have tested with IntelliJ IDEA 13.


Update:  The plugin now available on Jet-brain plugin repository :

The 3rd party tools that I use in my every android application

Ormlite for Android

Well many of you love ORM (Object rational mapper). It’s just another cool orm tool simply works fine with android’s sqlite database.



Who didn’t hear of Dependency Injection these days?

RoboGuice is a framework that brings the simplicity and ease of Dependency Injection to Android, using Google’s own Guice library. You must love it.



Simple Logging Wrapper Library for Android. Those who are used to with SLF4J, would love it.


Android Asynchronous Http Client

An asynchronous callback-based Http client for Android built on top of Apache’s HttpClient libraries. It’s really handy and easy to use. It covers almost everything regarding http request response stuff. Its only 25Kb for everything.


Sherlock ActionBar

After android 3.0 you have notice there is a nice stuff called Action bar and most of the android application use it.  It’s a nice extension of android support library designed to facilitate the use of the action bar design pattern across all versions of Android with a single API. You gotta love it.


A great place to learn and mingle

The Java User Group Bangladesh (JUGBD) is now formed and successfully finished its 2nd meetup in last week. We are doing great, it’s not an exaggeration.

For those who doesn’t know what is JUG, let me brief a little. Java User Groups (JUGs) are basically a group of enthusiastic people who loves java and develop product and service using Java related technology and love to share their knowledge to others. We get together in some place and then talk to each other, eat and have fun.

The primary vision of JUGBD is to continue meeting on very regular basis. As all the people are involved here are too much cool and enthusiastic, it always feels better to talk to each other and learning new things.

In August 2013, we had our first meetup. On this day, we formed the group with a few Java programmers of different software firms and with some students, both of whom were present at the event. Later we decide to have another meetup, which was held on 6th December, 2013. This time we received a huge response from the programmers here in Dhaka, a lot of them were physically present and most of them supported us. We had three speakers at this event. They gave talk on how Java technology influenced other technology, big data (Cassendra) and JVM diagnostic. All of talks were excellent.

A lot of software firm are stepping forward to help our events. Meetup 2.0 was sponsored by Therap Services, LLC. In addition, we got our sponsor for the next meetup already, which is really helpful to our community. We greatly appreciate this sort of help.

Right now, we are looking to contribute in some open source projects and thus we are looking for problems, ideas. Here is an open invitation to everybody: if you are a java programmer, enthusiastic about learning new stuff and love to talk about technologies, please join us. It’s a great opportunity for us to learn and mingle.

Android – Expandable TextView

There are so many thread in Stack overflow for expandable TextVeiw.

The idea is, initially the TextView will show a small portion of a long text and when it is clicked, it will show the rest of the text.

So here is the code that how I solved it.
Using following class:

package com.rokonoid.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.text.SpannableStringBuilder;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TextView;
 * User: Bazlur Rahman Rokon
 * Date: 9/7/13 - 3:33 AM
public class ExpandableTextView extends TextView {
    private static final int DEFAULT_TRIM_LENGTH = 200;
    private static final String ELLIPSIS = ".....";

    private CharSequence originalText;
    private CharSequence trimmedText;
    private BufferType bufferType;
    private boolean trim = true;
    private int trimLength;

    public ExpandableTextView(Context context) {
        this(context, null);

    public ExpandableTextView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.ExpandableTextView);
        this.trimLength = typedArray.getInt(R.styleable.ExpandableTextView_trimLength, DEFAULT_TRIM_LENGTH);

        setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                trim = !trim;

    private void setText() {
        super.setText(getDisplayableText(), bufferType);

    private CharSequence getDisplayableText() {
        return trim ? trimmedText : originalText;

    public void setText(CharSequence text, BufferType type) {
        originalText = text;
        trimmedText = getTrimmedText(text);
        bufferType = type;

    private CharSequence getTrimmedText(CharSequence text) {
        if (originalText != null && originalText.length() > trimLength) {
            return new SpannableStringBuilder(originalText, 0, trimLength + 1).append(ELLIPSIS);
        } else {
            return originalText;

    public CharSequence getOriginalText() {
        return originalText;

    public void setTrimLength(int trimLength) {
        this.trimLength = trimLength;
        trimmedText = getTrimmedText(originalText);

    public int getTrimLength() {
        return trimLength;

And add following line in your attr.xml

<?xml version="1.0" encoding="utf-8"?>
<declare-styleable name="ExpandableTextView">
<attr name="trimLength" format="integer"/>

Put the following in your main.xml

<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android=""

And test your activity

package com.rokonoid.widget;

import android.os.Bundle;

public class MyActivity extends Activity {

    public void onCreate(Bundle savedInstanceState) {

        String yourText = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. " +
                "Ut volutpat interdum interdum. Nulla laoreet lacus diam, vitae " +
                "sodales sapien commodo faucibus. Vestibulum et feugiat enim. Donec " +
                "semper mi et euismod tempor. Sed sodales eleifend mi id varius. Nam " +
                "et ornare enim, sit amet gravida sapien. Quisque gravida et enim vel " +
                "volutpat. Vivamus egestas ut felis a blandit. Vivamus fringilla " +
                "dignissim mollis. Maecenas imperdiet interdum hendrerit. Aliquam" +
                " dictum hendrerit ultrices. Ut vitae vestibulum dolor. Donec auctor ante" +
                " eget libero molestie porta. Nam tempor fringilla ultricies. Nam sem " +
                "lectus, feugiat eget ullamcorper vitae, ornare et sem. Fusce dapibus ipsum" +
                " sed laoreet suscipit. ";

        ExpandableTextView expandableTextView = (ExpandableTextView) findViewById(;


Screenshot of textview with a small portion of long text.
Expandable TextView

Screenshot when you click on the text

Expandable TextView

How to Remove Duplicate Rows from a Table in SQL Server


It is obvious that if somehow duplicate rows get inserted into a table, it becomes a major issue to delete those duplicate rows. So this topic will help us to delete those duplicate rows from the specific table.


I used some basic T-SQL (Transact-SQL*) code to accomplish the problem. So you don’t need to worry understand the codes and even you can use just blindly.


I had a database table with duplicate rows and I wanted to get rid of it. So this is how I solved my issue.


First, say I have a table named Stores with following column.


So my first select query:


And Output:


Now look carefully in above figure, Stores table does contain duplicate records. Check first two columns marked with rad box. Every the columns are the same except Id.

Now let’s find out duplicate rows in a way so that we can easily understand. We are now going to add an extra column in a temporary table, let’s name it RowNumber. RowNumber will hold count of duplicate rows.

So let’s execute the following query:

,Longitude ORDER BY DmsCode) AS RowNumber, *
FROM Stores

You see, I haven’t include Id, since it’s not duplicate.


Now if you look above table RowNumber column, you will able to know which records contain duplicate values on rows with RowNumber greater than 1.

Now if we want to keep unique values in the table and delete others execute following query:

ORDER BY DmsCode) AS RowNumber, *
FROM nps_new.dbo.Stores
DELETE from Temp WHERE RowNumber >1

If the query executes, we will find only unique values in the table.


I did not explain the queries as I assumed that people who deals with such thing already know SQL.

Random Thoughts – Caffeine

I’m worried about my personal productivity these days. I am a person who used to spend (maybe waste) time doing random things, but still worried about personal productivity. There are people that the term personal productivity meant nothing to them at all. To be honest, I do not like them. I love those people who are always calculative, thoughtful and hardworking. I am kinda person, who at least pretend to be working all the time. By the way, I’m a programmer, I used to work in a close room sitting in a chair staring at a computer screen for hours upon hours. For the common people (who are not a programmer and have no idea what does a programmer actually)  may find it too wired and crazy things and I have some friends who cannot even imagine how a man can sit such long time without moving (my longest record is 18 hours in a day). Recently I did a little digging on YouTube and found that sitting for long without moving minimize productivity. Although I do not believe in their research. I believe only coffee or tea can improve the productivity and it is my secret. You have to know how to make great coffee or a tea. I believe that most people cannot make a good coffee or tea. I make my own coffee or tea. I believe I do make the best coffee / tea, though only a few of my friends agreed. And I don’t offer coffee/tea to everybody.

I have a random thought that programmer productivity is very dependent on caffeine.

My personal productivity is exhausted due to not having coffee too much these days. I feel sleepy during the day time and used to sleep all night. By the way, this is the Holy month of Ramadan and I do fast from dawn to dusk, and that is about 15 hours. And that’s why I cannot have a lot of coffee these days.

In my own definition productivity means, some actions that accomplish goal in a timely manner.

Programmers Freedom

There is no such thing as true freedom. This is probably a true realization. In my understanding, freedom means, minimizing the level of dependence. As a programmer, we used to think we have a true freedom in computer stuff, as it seems we can do whatever we want to do. It is true, in fact, at least in theory, but in practice we simply cannot do. We think about a problem and make a conceptual design in our head to solve that particular problem, and then select a programming language to implement. This is a typical scenario.

But the problem is to map our conceptual model into a programming language. This is not an easy task to do as we are heavily dependent on programming infrastructure. Sometimes we have to wait for the language designer to update certain things (we used to joke about Java updates), and if we require additional power from the IDE, we must wait for IDE vendor. Most importa­­ntly programming language has simple and few notations that can be expressed in comparison with our natural language. Most of the cases we the programmers spent our time to find ways to express our conceptual model in terms of programming level abstractions which is difficult and not creative and more or less waste of time.

So where’s our freedom? Are we not locked in some ways.

Java Installation in Ubuntu

Method 1

Step 1: download jdk from:


Step 2 : go to downloaded folder using command line terminal :

 cd ~/Download 

Step 3: install jdk

sudo tar -xzvf  jdk-7u21-linux-i586.tar.gz --directory=/usr/local/

sudo ln -s /usr/local/[jdk_folder_name]/ /usr/local/jdk

* change the folder name according to extracted jdk folder name,

Step 4: open .bashrc

sudo gedit .bashrc

Step 5: add following line end of the .bashrc file

export JAVA_HOME=/usr/local/jdk

Save and close .bashrc file.

Step 6: compile .bashrc file

source .bashrc


Step 7:  now test whether java is installed properly or not: goto terminal and time following line

java -version

if java is installed properly, java runtime information will be displayed.

if not… follow second method:
Method  2:

Step 1:  Preparing your system

First you need to remove openjdk for this run the following command from your terminal

 sudo apt-get purge openjdk*

Step 2:  If you installed java 7 from any other PPA and you are having problem with java then you have to do following steps before installing the PPA mentioned here

sudo rm /var/lib/dpkg/info/oracle-java7-installer*

sudo apt-get purge oracle-java7-installer*

sudo rm /etc/apt/sources.list.d/*java*

sudo apt-get update

Step 3:  Install oracle java 7 in ubuntu 13.04/12.10/12.04

Open the terminal and run the following commands

sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

sudo apt-get install oracle-java7-installer

now give a smile :) :) :D

Executing Linux command from Java

You know Linux commands are always fun. We always play on terminals. How about executing from our favorite language java?

Then you need following class


public class CommandExecutor {
public static String execute(String command) {
StringBuilder sb = new StringBuilder();
String[] commands = new String[] { "/bin/sh", "-c", command };
try {
Process proc = new ProcessBuilder(commands).start();
BufferedReader input = new BufferedReader(new InputStreamReader(

BufferedReader stdError = new BufferedReader(new InputStreamReader(

String s = null;
while ((s = input.readLine()) != null) {

while ((s = stdError.readLine()) != null) {
} catch (IOException e) {
return sb.toString();

Now you can execute any command using this class.
For example-

public static void main(String[] args) {</pre>
String output = CommandExecutor.execute("ps aux | head -3");

And output will in your console like:

root         1  0.0  0.0  24600  2212 ?        Ss   Apr12   0:00 /sbin/init
root         2  0.0  0.0      0     0 ?        S    Apr12   0:00 [kthreadd]

Check out Birds Puzzle on Google Play

I have got an android app named Birds Puzzle in the android market. It is a kid friendly image slide puzzle game for Android displaying a set of bird picture slides that you move into the correct order.



in the very first window there is a menu, you have to press on new puzzle, and then a cover flow with different birds will appear, you have to select one. When you will select one, a new window will appear showing you the correct order of slides. And then you have to press play button in the top right corner of action bar, and puzzle will begin. You have to complete the puzzle with the time limit show in action bar. If you can solve the image within the limit, a dialog will appear showing the name of birds and a short description of birds with playing its voice.

Checkout : Birds Puzzle on Google Play

How to decompile android apk to java source code?

I wrote another post with the same title here and it got a lot of comments and people wanted to know more, and some point some visitors was confused. so here is the easiest copy-paste solution.

  1. Download dex2jar from
  2. Extract to a folder. for example /home/codexplo/( for linux), or  C:\ (for windows)

unzip -x -d /home/codexplo

  1. use dex2jar to generate .jar file. dex2jar will generate a file named someApk-dex2jar.jar in the working folder.
   linux sh /home/codexplo/dex2jar-version/ /home/codexplo/someApk.apk
   windows C:\dex2jar-version\d2j-dex2jar.bat someApk.apk
  1. use a decompiler to view the source.

that’s it

Reference :

How to enable usb debugging in ubuntu for nexus 7

get the terminal, type:

sudo vi /etc/udev/rules.d/70-android.rules


sudo gedit /etc/udev/rules.d/70-android.rules

and then add the following line:

SUBSYSTEM==”usb”, ATTR{idVendor}==”18d1″, ATTR{idProduct}==”4e42″, MODE=”0666″

DNS Explained

DNS মানে হলো Domain Name System.

এটি ইন্টারনেট এর সবচেয়ে গুরুত্বপূর্ণ জিনিস। এটি ছাড়া ইন্টারনেট যেকোন মুহূর্তে ধসে পরতে বাধ্য। ডিএনএস না থাকা মানে No Internet, No facebook, No Google. সুতরাং বুঝা যাচ্ছে ডিএনএস দি-ই-ই-ই-ই-ই-ই ইম্পট্যার্ন্ট!

তাহলে ডিএনএস কি?

আমরা সবাই জানি (যারা জানি না তারা নিজ দায়িত্ব জেনে নিন) প্রত্যেকটি কম্পিউটারের একটি আইপি এড্রেস থাকে। আইপি এড্রেস এর মাধ্যমে একটা কম্পিউটার আরেকটি কম্পিউটারকে চিনতে পারে। ধরা যাক ফেইসবুক, ফেইসবুক একটা এপ্লিক্যাশান, আলোচনার সুবিধার্থে ধরে নিলাম একটা মাত্র কম্পিউটারে ফেইসবুকটি চলে, আর কম্পিউটারের একটা আইপি এড্রেস আছে। সুতরাং আমাদের যে কম্পিউটারে ফেইসবুক চলে, সেই কম্পউটারের আইপি এড্রেসটি জানতে হবে যদি আমরা ফেইসবুক ব্যবহার করে চাই। আইপি এড্রেস হতে হয় ইউনিক। দুনিয়াতে যেহেতু কোটি কোটি কম্পিউটার, সুতরাং এই আইপি এড্রেস ইউনিক করতে গিয়ে এমন হয়েছে যে আমরা যারা সাধারণ মানুষ(যারা পাই-এর মান ২০০ ঘর পর্যন্ত মনে রাখতে পারে, তারা অসাধরণ) কোন ভাবেই মনে রাখতে পারি না। যেমন ফেইসবুকের আইপি এড্রেস হলো- গুগলের হলো সুতরাং হাজার হাজার ওয়েব সাইট যেগুলা আমরা প্রতিনিয়ত ব্রাউজ করি সেগুলার একটা নির্দিষ্ট আইপি এড্রেস থাকে। আমাদের কারো পক্ষেই এতো আইপি এড্রেস মনে রাখা সম্ভব না। আমরা যেহেতু বুদ্ধিমান, সুতরাং একটা উপায় বের করে ফেলেছি, আর সেটিই হলো ডোমেইন নেম সিস্টেম। আমরা প্রত্যকটি আইপি এড্রেস এর জন্যে একটি করে সুন্দর নাম দিয়ে রাখি, তাতে করে আমাদের মনে রাখতে সুবিধা হয়। ডোমেইন নেম সিস্টেম হলো একটা Distributed ডাটাবেইস এবং নেটওয়ার্ক সিস্টেম যেখানে আপইপি এড্রেসের সাথে একটা নাম লেখা থাকে এবং এতে করে আমাদের ফেইসবুকের আইপি এড্রেস মনে রাখতে হয় না, আমাদের মনে রাখলেই চলে।

এখন এটি তাহলে কিভাবে কাজ করে? আমারা যখন ব্রাউজারের এড্রেস বারে লিখি, তখন ব্রাউজার এবং অপারেটিং সিস্টেম চিন্তা করবে, এর আইপি এড্রেস আগে তারা থেকে জানে কিনা(will first determine if they know what the ip address is already)। এটি কম্পউটারে কনফিগার করা থাকতে পারে কিংবা মেমরীতে থাকতে পারে(it could be configured in computer or it could be in memory(cache)). এখন আসি, যদি ব্রাউজার এবং অপারেটিং সিস্টেম দুটির কেও-ই না জানে, তাহলে কি হবে?

What happens next?

ব্রাউজার অপারেটিং সিস্টেম এর কাছে ডোমেইন এর আইপি এড্রেস চেয়ে বসে থাকবে, আর অপারেটিং সিস্টেম এমনভাবে কনফিগার করা থাকে যে, সে একটি Resolving Name Server এর কাছে আস্ক করে পারে ডোমেইন নেইম এর জন্যে।

Resolving Name Server এর কাজ হলো ডিএনএস লুকআপ করা। এটি ওপারেটিং সিস্টেমের সাথে কনফিগার করা থাকে।

কিন্তু Resolving Name Server আইপি এড্রেস জানতেও পারে আবার নাও জানতে পারে। অপশন দুইটা। যদি মেমরিতে থাকে থাকে, তাহলে সাথে সাথে অপারেটিং সিস্টেমকে আইপি এড্রেসটি দিয়ে দেবে। না থাকলে সাথে সাথে রুট নেইম সার্ভারক কুয়েরি করবে। কিন্তু রুট নেম সার্ভার সাথে সাথে রিপ্লাই দিবে, I don’t know. But I do know where to find the com name severs. কম নেইম সার্ভার হচ্ছে টপ লেভেল ডুমেইন নেইম সার্ভার। রিসলভিং সার্ভার রুট সার্ভার এর কাছে সব ইনফরমেশন নিয়ে কেশ করে রাখে যাতে করে দ্বিতীয় বার রুট সার্ভারের কাছে যেতে না হয়। এরপর সে টপ লেভেল ডুমেইন সার্ভারের (TLD) কাছে কুয়েরি করে। এবং যথারীতি টপ লেভেল ডুমেইন সার্ভার রিপ্লায় দেয়… a a ah.. I don’t know, But I do know where to find the name server.

নেক্সট লেভেল নেইম সার্ভারের নাম হলো, Authoritative Name Server. সুতরাং আগের মতোই রিসলভিং সার্ভার TLD এর কাছ থেকে সব ইনফরমেশন নিয়ে Authoritative Name Server এর কাছে কুয়েরি করে, এবং সাথে সাথে Authoritative Name Server বলবে, Hey! I know where that is! Tell your browser to go to the IP address:

রিসলভিং নেইম সার্ভার ANS এর কাছে এই ইনফরমেন নিয়ে নিজের কাছে কেশ করে রাখে এবং অপারেটিং সিস্টেমকে বলে, অপারেটিং সিস্টেম তখন আইপি ব্রাওজারকে বলে, আর ব্রাওজার সাথে সাথে সেই আইপিতে হিট করে(কানেকশান ক্রিয়েট করে,Http protocol একটা বিশাল ফিরিস্তি, পরে কোন একসময় বলবো)।

Pretty Cool, huh!!

যদিও প্রসেসটা একটু জটিল, কিন্তু নেইম সার্ভার সিস্টেম কে এমন ভাবে বানানো হয়েছে, যাতে করে এটি চোখের পলকেই কাজ করে ফেলে।

সুতরাং চারটা জিনিস, Resolving Name Server, The ROOT server, The TLD server and Authoritative Name Server.

এর কোন একটি যদি কলাপস হয়, হে হে, সাথে সাথেই সব ইন্টারনেট নাই হয়ে যাবে।

Problems with unicode encoding in spring projects

I had a problem with the encoding of Unicode characters. I developed a simple web application with support for multiple languages​​, which is called internationalization or i18n. In this application, the data were saved in a database, and then re-shown. But I get exceptions on production and it was a unicode utf-8 character encoding problem.
By the way, my application was developed using spring and hibernate and jpa2. It was kind of a nightmare and I was getting the exceptions frequently and I was completely no where-zone. At least, after searching and using many sources, I found out the solutions.

So here is the solutions–

First you need add some extra parameter in your database url. For example–


Secondary you’ve to add a filter in your web.xml

















And finally you have to make sure you have added following line in your jsp pages

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

and finally follow the command in your terminal

You should now be logged into the MySQL prompt. Here type the following commands :

mysql> use user_db;

mysql> alter database user_db default character set utf8 collate utf8_unicode_ci;

Query OK, 1 row affected (0.00 sec)

This should have done it.

okay, that’s how I solved the issue.

A brief introduction of String in Java

What is string?

String is traditionally a sequence of characters. In Java string is an object and it is widely used in Java. String class is defined in java.lang package and implicitly available for all program.

String can be created in two ways.

  1. By string literal
  2. by new keyword

String literal

String literal is created by double quote, for example-

String aStrign = “A String is Created”:

each time you create an new string, the JVM first check the constant pool whether it is already in constant pool. If is already in available, JVM doesn’t create new string, instead, it just refer the old string as it is already available.

So, if we create strings like-

String a = “A”;

String b = “A”

here, first we created a string which referenced to the reference value a. now if we need another string and if we create like 2nd line of the example, JVM will first check whether there is already a string object in the constant pool which contained “A” available or not, if it is already there, no new string will be created, instead, our new string is referenced by the old one.

Now what is object pool?

Object pool is another kind of data structure managed by Java virtual machine. We all know about constant who ever writes codes in his life time. Constant pool are used for frequent access and less memory consumptions. If a constant is already available in Constant pool, JVM doesn’t need to create a new object.

By new Keyword

String can be create by new keyword as all the other objects are created. Example –

String aString = new String(“Rokon”);

Here is something we need to know.

String is immutable object. Immutable means if a object once created, it will never get changed.

So when we create a string object, it will just never get changed. So now if we assign a new value to an string, the scenario is like, for example –

aString = “A new value is assigned”;

here, a new string object will be created with the value “A new value is assigned” and the object will be referenced to aString and the previous String will be ready for garbage collector.

String concatenation : String concatenation is easy in Java, what you need to do, is adding a plus-

for example –

String firstName ="Bazlur";

String lastName = "Rahman";

int age = 45;

String textToPrint = "My Name is "+ firstName + " " + lastName + " and my age is "+ age;


Output: My Name is Bazlur Rahman and my age is 45

here every concatenation,a new object is created and old one gets ready for gc.

So if we need a thousand of concatenation, JVM will create thousands of new object which required huge memory. To avoid this issue, there is two Class available, they are, StringBuilder and StringBuffer.

Mutability and immutability : A long time ago, once I chatted with my friend. I think its something worthy about.

(08:08:44 PM) Bazlur Rahman: hey

(08:08:53 PM) crusk8: hey

(08:08:59 PM) Bazlur Rahman: how are u ?

(08:09:39 PM) Bazlur Rahman: do u know difference the between mutable and immutable object ?

(08:12:20 PM) crusk8: I was just looking at the idea on wikipedia. looks like the idea for immutable objects is to create an object, set to what you want, use it, and then let it alone

(08:13:16 PM) Bazlur Rahman: i have some basic idea though … but question is when to use them?

(08:14:16 PM) Bazlur Rahman: mutable object can be changed using mutator, and immutable object cant be changed… this is the main motivation ..right ..

(08:15:19 PM) crusk8: yeah. I guess you could use an immutable objects to modify other objects, but, for safety, that immutable object itself couldn’t be modified

(08:17:30 PM) Bazlur Rahman: yup.. don’t you think, immutable object is responsible for less performance.. every time, new object is created, old object is dropped, reference is changed, garbage collector is called…

(08:18:27 PM) crusk8: yeah. if you’re going to use an immutable object. you should use it cases where that object will almost never change

(08:20:10 PM) Bazlur Rahman: but is it good practice using immutable object always? because it is thread safe, I don’t need to do locking, it is protected,

(08:20:49 PM) Bazlur Rahman: and sometime it has good performance… like we dont need to make defensive copy ..

(08:21:39 PM) crusk8: you probably wouldn’t need to do locking on that object. for languages like c++ it would be const protected

(08:21:55 PM) crusk8: you only need to do locking when that object tries to modify other objects

(08:24:05 PM) Bazlur Rahman: so whats the point of using mutable or immutable object. should I always immutable object ?

(08:26:39 PM) crusk8: mutable objects are ones that need to be modified a lot. immutable ones are that rare if ever need to be modified. an immutable object could act like a controller for the mutable objects

(08:26:58 PM) crusk8: it can change them but the mutable objects can’t change it

(08:29:47 PM) Bazlur Rahman: I’m still confused, in which situation, I should use immutable object..? for security issues ?

(08:30:45 PM) crusk8: yeah. you’re the limiting the ways that an object can modified. only through reallocating the object

(08:31:03 PM) crusk8: not through mutators

(08:34:12 PM) Bazlur Rahman: hmm but it has some complexity while implementing immutable object I think ..

(08:35:23 PM) crusk8: I’m not sure if immutable means that object can’t modify its own internal variables. while processing something internal settings can;t be changed

(08:35:43 PM) crusk8: or just that the outside world can’t change things directly

(08:36:12 PM) crusk8: I suppose only data could be local to the function

By the way,

Here I’m going to tell you some advantage and disadvantage of immutable object.


Protection : you can send and immutable object to any class without worrying about it being altered by that class and you never have to make defensive copy.

Thread safe: Its fully thread safe, any number of threads can access them simultaneously, without any synchronization.

Disadvantage :

Constructor injection : it requires constructor injection while you are going implement inversion of control. In immutable object, there is no way to use mutator.

Implementation complexity : its very much boring to implement immutable object.

Some worthy reading list:

10 Things about Design

  1. “Simplicity is the ultimate sophistication.” – da Vinci
  2. The best deliverable are prototypes.
  3. Sketching is the most effective design method.
  4. Creativity comes from everywhere.
  5. Design is writing.
  6. Interruption is the enemy of productivity.
  7. Being healthy leads to better work.ay
  8. A great culture is the byproduct of great behavior.
  9. Design is at the heart of great companies.
  10. Design is never done.

Courtesy: Joshua Kaufman



A list of really good user interface design resources

Here is the list of links I found from a question in Quora



Well-Grounded Java Developer

Reading Well-Grounded Java Developer by Benjamin J.Evans, Martijin Verburg. You must read this book if you are really  a java fanatic.

you can read the review of this book here:

State Diagram of Java Thread

Figure:  Java thread state diagram

Runnable:  A thread becomes runnable when start() is called. It doesn’t mean that thread gets running immediately, rather it is pooled waiting for its turn to be picked for execution by the thread scheduler based on thread priorities.

Running: A thread started its execution when scheduler picks. It runs until it is blocked or voluntarily gives up its turn with this static method Thread.yield( ).

Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish. A call to current Object.wait( ) method causes the current thread to wait until some other thread invokes current Object.notify( ) or the current Object.notifyAll( ) is executed.

Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);

Blocked on I/O: it moves to runnable after I/O condition like reading bytes of data etc. changes.

Blocked on synchronization: it moves to running when a lock is acquired.

Dead: The thread is finished working.


Chain of responsibility pattern

Pattern name: Chain of responsibility

What it is: Avoid coupling the sender of request to its receiver by giving more than one object to a chance to handle request. Chain of receiving objects and pass the request along the chain until and object handle it.

Family of patterns: Behavioral Patterns

Structure of patterns:

Figure: structure of chain of responsibility pattern

Handler— define an interface for handle request

Concrete handler— concrete handler implements the handler interface and handle the request it is responsible for if it can handle the request, otherwise it sends the request to its successor.

Clients— send the request to the first object of the chain that may handle the commands

When to use this pattern: this pattern is recommended when—

  •  Multiple objects can handle a request and the handler doesn’t have to be specific object
  •   A set of object should be able to handle a request with the handler determined at runtime
  •  A request  not being handled is an acceptable outcome

Downside: this pattern has mixed blessing. The request could reach the end of the chain and not be handled at all.

Real Life Example: let’s think a scenario; I have an email client which store email in different folders to store emails. If it is from Gmail, it will store in Gmail folder and if it is from, it will store in folder. So have different email handlers, they do basically same type of job. We can solve this problem using chain of responsibility pattern.

Code Example:

Interface Handler

package com.codexplo.patterns.behavioural.chainofresponsibility;

public interface EmailHandler {
public void setNext(EmailHandler emailHandler);

public void handleRequest(String email);




Concrete Handler 1

package com.codexplo.patterns.behavioural.chainofresponsibility;

public class GmailEmail implements EmailHandler {
private EmailHandler next;

public void setNext(EmailHandler emailHandler) { = emailHandler;

public void handleRequest(String email) {
if (email.contains("")) {
.println("Email is from, so it will go in Gmail folder");
} else {

Concrete Handler 2

package com.codexplo.patterns.behavioural.chainofresponsibility;

public class BusinessEmail implements EmailHandler {

private EmailHandler next;

public void setNext(EmailHandler emailHandler) { = emailHandler;

public void handleRequest(String email) {
if (email.contains("")) {
.println("Email is from, so it will go in Folder");
} else {

Email Processor

package com.codexplo.patterns.behavioural.chainofresponsibility;

public class EmailProccessor {
private EmailHandler successor;
private EmailHandler first;

public void addHandler(EmailHandler handler) {
if (this.first == null) {
this.first = handler;
} else
this.successor = handler;

public void handle(String email) {

Email Client

package com.codexplo.patterns.behavioural.chainofresponsibility;

public class EmailClient {
private EmailProccessor proccessor;

public EmailClient() {

private void createProccessor() {
proccessor = new EmailProccessor();
proccessor.addHandler(new BusinessEmail());
proccessor.addHandler(new GmailEmail());

public void emailRecieved(String email) {

public static void main(String[] args) {
EmailClient client = new EmailClient();

CloudBess maven deployment Command

Deploy :

clean install bees:deploy

deploy skipping test :

clean install bees:deploy -Dmaven.test.skip=true

Java Tutorial for Absolute Beginners Part 2

Think twice before diving into ocean, check JOEL Test score

As we are graduating this year, most of us spend a significant amount of time looking for a job and certainly I do. There are always jobs out there but are they all good for you? You know the answer, some of them are too good and some of them are average and some of them are really poor. By the way, I’m talking about software developer’s job.  So getting a good job always is our priority which will make use of your talents and expertise. The ideal environment will be professionally stimulating and will offer opportunity for career advancement.

There is a term named Joel Test, most of you already heard about, if not stay with me.

This is a very neat and clean test, very easy to get a quick yes or no to each question.

They questions are –

  • Do you use source control?
  • Can you make a build in one step?
  • Do you make daily builds?
  • Do you have a bug database?
  • Do you fix bugs before writing new code?
  • Do you have an up-to-date schedule?
  • Do you have a spec?
  • Do programmers have quiet working conditions?
  • Do you use the best tools money can buy?
  • Do you have testers?
  • Do new candidates write code during their interview?
  • Do you do hallway usability testing?

A score of 12 is perfect, 11 is tolerable, but 10 or lower and you’ve got serious problems.

The truth is that most software organizations are running with a score of 2 or 3, and they need serious help, because companies like Microsoft run at 12 full-time.

Personally I want to get a job where the score at least 10 out of 12, what’s yours?

So before dive, check the score of that company you’re supposed to join.

To Get More Help, please visit: