Saturday, 29 August 2015

Difference between StringBuilder and StringBuffer in Java


In Java String class is immutable. So each concatenation or substring operation yields a new String.

Yes we all have heard String concatenation is bad to create long Strings. Concatenating large number of String literals will fill up the permgen area (where String pool resides) faster. One of the reason why SLF4J is preferred over LOG4J  . Incase you need to concatenate String literals you can use StringBuilder or StringBuffer instance instead. You can just keep appending your String literals to this instance and finally call toString() to get a single String instance. In this post we will see the difference between StringBuilder and StringBuffer.

StringBuilder and StringBuffer in Java

Their usages are quite simple.

        StringBuffer sBuffer = new StringBuffer("abc");
        StringBuilder sBuilder = new StringBuilder("abc");

As you can see the usage is similar but their difference is very important which we will see now. Just a note no new strings are created when append is called. Internally an array is maintained and String characters are appended to it.

Difference between StringBuilder and StringBuffer in Java

The most important difference between them is 
  • StringBuffer is synchronized, StringBuilder is not.
Hence unless you have a multithreaded scenario to deal with always go for  StringBuilder and not StringBuffer. Even if you have multithread situation you can use a synchronized block around StringBuilder.

 You can say - "StringBuilder is intended as a drop in replacement for StringBuffer where synchronisation is not required"

Quoting the API docs for StringBuilder -

"A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations."

A simple for performance would be -

public class HelloWorld {
    public static void main(String args[]) throws IOException
        int limit = 1000000;
        long currTime;
        long timeTaken;

            StringBuffer sb = new StringBuffer();
            currTime = System.currentTimeMillis();
            for (int i = limit; i --> 0 ;) {
            timeTaken = System.currentTimeMillis() - currTime;
            System.out.println("StringBuffer Time : " + timeTaken);
            StringBuilder sb = new StringBuilder();
            currTime = System.currentTimeMillis();
            for (int i = limit; i --> 0 ;) {
            timeTaken = System.currentTimeMillis() - currTime;
            System.out.println("StringBuilder Time : " + timeTaken);

and this prints (one execution) -

StringBuffer Time : 29
StringBuilder Time : 6


So to summarize always use StringBuilder and not StringBuffer.

Related Links

Wednesday, 26 August 2015

Java memory allocation


If you are acquainted with Java then you must have heard that objects are created on heap and there is automatic garbage collection in Java. In this post we will see the java memory allocation. Not everything is created on heap. Let's start with the basics. Whenever you run a new java process a new JVM is created that takes care of running your Java program. Like any other process your operating System will provide this JVM instance some memory to run. You can also specify heap size of your Java program in your jvm arguments.

Java memory allocation

You can use following options to alter JVM memory
  1. -Xms<size>      set initial Java heap size (Eg. java -Xms1g TestProgram)
  2. -Xmx<size>      set maximum Java heap size (Eg. java -Xmx2g TestProgram)
  3. -Xss<size>        set java thread stack size (Eg. java -Xss4m TestProgram)
Java memory is of two types.
  1. Stack
  2. Heap


Stack is where local variables are stored and that includes primitive types and object references. Each thread will have it's own private stack (which you can define in Java with -Xss JVM parameter). Each method will create it's own section on this stack for maintaining scope. This is called stack frame. Whenever a local variable is in methods scope it is pushed to this stack frame and when it is out of the scope it is poped out. Note this is all scope based. There is no concept of garbage collection in stacks.


Heap is where your objects are created (memory is allocated for the object). Whenever you create a new instance of a class using new keyword it is created on this heap. This object will be garbage collected when it is no longer referenced from any of the GC roots.

Difference between Stack and Heap memory

  1. As mentioned earlier Stack stores local variables and object references where as heap stored the actual object instance.
  2. If stack memory is filled up JVM will shutdown throwing java.lang.StackOverFlowError error where as if heap memory is filled JVm will shutdown throwing java.lang.OutOfMemoryError error.
  3. Each thread will have it's own private stack. Meaning each stack memory is private to some thread where as heap area is shared among all the threads.

Related Links

Saturday, 8 August 2015

Creating and customizing new user in Ubuntu Linux


In this post we will see how to add a new user using command line. Then we will add it to sudoers list which will essentially make this user administrator. Next we will also see how can we personalize this new users profile and then we will see how we can change permissions or copy files from other users directory to this new users. We will also see how to remove an existing user and how to list files that belong to a user/group. And all of it with command line :)

Adding a new User

If you want to see list of existing user then you can browse the file /etc/passwd
  • less /etc/passwd
Here  you will see list of all user with their configurations like what shell the user uses.

To add new user use following command -
  • sudo add user <username>
 You will have to enter user details like name, phone no etc. You can just press enter if you do not wish to provide this information.

User should get created now. To verify
  1. You can see directory with same username getting created in /home folder.
  2. You can also inspect contents of /etc/passwd file. You should now start seeing row corresponding to this new user

Lastly to change user you can use following command
  • su <username>
You will need to provide corresponding users password.

Adding user to sudoers list

 Just creating a user will not grant it administrative privileges. This user can't use sudo command and thereby not execute tasks that requires administrative privileges.

To add a user to sudoers list you can execute following command - 
  • sudo adduser <username> sudo
Note that the user from which you execute this command should be in sudoers list.

 Personalizing User profile

What I mean here by personalizing is setting environment variables and aliases that user will need in his or her daily usage. For example lets say a developer create his/her account and now want JAVA_HOME variable set. Sure it can be exported and be done for the day but lets see how we can permanently set it.

All of this magic happens in a file called .bashrc that is located in the home folder of user. You can export your variable or set aliases here. For eg

  • export PATH=$PATH:$HOME/firefox/adt-bundle-linux-x86-20140702/sdk/tools:$HOME/firefox/adt-bundle-linux-x86-20140702/sdk/build-tools:$HOME/firefox/adt-bundle-linux-x86-20140702/sdk/platform-tools

For demo purpose lets create an alias to print hello world. Go to ~/.bashrc file and add following line

  • alias hw='echo hello world!'
save the file. Then in console just type hw and you should see "Hello World!" printed.

This was just an example you can set alias to command use frequently use.

Note : If you making any change in the .bashrc file you will have to open a new terminal window to see the effects. If you want to see the changes in same terminal you have to use source command as show in screenshot above.
  • source ~/.bashrc

Changing file permissions 

To change a permission of a file or a folder you can use chmod command. Yo give all read, write and execute permissions to all - user, group, others you can use - 

  • chmod ugo+rwx filename
 You can mix and match u,g,o and r,w,x combinations.
  • u = user
  • g = group
  • o = others
  • r = read
  • w = wite
  • x = execute
Use this with caution. You don't want to give others unauthorized access to your profile.

Also if you want to do this action recursively you can use -R option.

If you want to change ownership of a file or a directory you can use chown command.

To change file owner user you can use
  • sudo chown <username> <filename>
To cahnge file owner group you can use
  • sudo chown :<groupname> <filename>
Or to change both user and group simultaneously
  • sudo chown <username>:<groupname> <filename> 


  Removing an User

To remove an existing user simply execute following command -
  • sudo userdel <username>
You will see row corresponding to this user in /etc/passwd file will get removed.

Note : Though user gets deleted it's home directory will not get deleted. You have to manually delete it. To delete users home directory use following command
  • sudo rm -rf /home/<user_directoryname>

Finding all files owned by a particular User/Group

For finding files owned by a group you can use 
  • find directory-location -group {group-name} -name {file-name}
For finding files owned by a user you can use
  • find directory-location -user {username} -name {file-name}

Related Links

Friday, 31 July 2015

Setting up open vpn client on Ubuntu with two factor authentication Support


In this post we will see how to setup open vpn on ubuntu and then configure it to use Duo Two factor Authentication.

Installing openvpn

Installing openvpn is fairly simple. Just execute following command in command line

  •  sudo apt-get install openvpn
 This should install openvpn client in you Linux machine. You can verify the installation by checking the version.
  • openvpn --version

Connecting to VPN

 You can then connect to your vpn by executing command - 
  • sudo openvpn --config /path/to/config.ovpn
Next obvious question  -  What is this config.ovpn file? and where do I get it?

This is the file you would typically get from your vpn service provider. You can simply log on to your vpn with browser and download it from there. Note this file contains inline private keys and must be kept confidential.It will also have your vpn configuration like vpn address, ports , protocols etc.

Connecting to VPN with two factor Authentication like Duo

If two factor authentication is enabled on your server then your authentication will fail. 

You need to do some extra setup before you can start handling two factor authentications.

Configuring open VPN client
  1. Make sure you have following like in your OpenVPN client configuration file 
    • auth-user-pass    
  2. Next you should append you openvpn connect command with following - 
    • --auth-retry interact
And you should be all set for your vpn connection. You can run the command -

  • sudo openvpn --config /path/to/config.ovpn --auth-retry interact
You should not get a prompt to enter your dual auth password.

Simply enter your dual auth password and you should be good.

Related Links

Saturday, 4 July 2015

Understanding CSS Specificity


Life is good when you have a small web project with limited and simple CSS but as your project size grows and more CSS is to be applied complexity increases. 

In there are two or more conflicting CSS rules that point to the same element then your web browser will apply some rules to figure out which rule should be given higher precedence and be applied.

We term this rule weight as selectivity. More the selectivity more is the preference given to that rule.


Enough of the theory lets see an example. Consider following html

        <style type="text/css">
            .redbutton{color: red;}
            .bluebutton{color: blue;}
             #innerdiv input {color: green;}
        <script src="" type="text/javascript"></script>
            function changecolor()
    <title>Testing CSS Selectivity</title>
        <div id="ouderdiv">
            <div id ="innerdiv">
                <input id="colorbutton" type="button" class="redbutton" value="Click Me" onclick="changecolor()"/>

What do you expect will be the color of the button on page load and on click ? Well think a bit and then try it out. Paste above html in a file and open it in any browser. Observer the color, click on the button and then observer the color again. 

Before Cick

After Click

Whats happening?

Have questions? Will be answered soon. Lets take a step back and review our html code. We have a button. For this button we provided a class called redbutton (which should make the button red) and then on click we are dynamically changing the class to bluebutton (which should make the button blue). But none of these worked. It is still green. As you must have guessed correctly by now there is another css rule that is getting applied.

#innerdiv input {color: green;}

But why? Because CSS specificity of this rule is more than other class rules that we have defined. Next natural question - How is css specificity determined by the browser?

How is CSS specificity calculated?

There are some basic rules to determine specificity of a CSS rule.

Determination of specificity of a CSS rule depends on what type of selector is used
  • HTML selector (Eg input) has specificity 1
  • Class selector (Eg .redcolor) has specificity 10
  • ID selector (Eg. #innerdiv) has specificity 100
And if you have multiple such selectors in an CSS rule then their individual specificity just get added to form rule specificity that is used by the browser to determine precedence.

Here are few example
  • a - specificity 1 (1 HTML selector)
  • div a - specificity 2 (2 HTML selectors,  1+1)
  • div .someclass - specificty 11 (1 HTML selector and 1 class selector, 1 + 10)
  • div #someid - specificity 101  (1 HTML selector and 1 id selector, 1 + 100)  
  • div #someid .someclass - specificity 111  (1 HTML selector and 1 id selector and 1 class selector, 1 + 100 + 10)  

and so on.... Hope you got the point.

Note : If two conflicting rules have same selectivity then the one applied or parsed later is picked up.

So lets apply it to our rules.

  • .redbutton{color: red;} - specificity 10 (1 class selector)
  • .bluebutton{color: blue;} - specificity 10 (1 class selector)
  • #innerdiv input {color: green;} - specificity 101 (1 id selector and 1 html selector, 100+1)
So how can we leverage this information now? Lets increase the specificity of first two color rules now.

  • #innerdiv .redbutton{color: red;} - specificity 110 (1 id selector and 1 class selector,100+10)
  • #innerdiv .bluebutton{color: blue;} - specificity 110 (1 id selector and 1 class selector,100+10)
  • #innerdiv input {color: green;} - specificity 100 (1 id selector and 1 html selector,100+1)

With above rules now test our page again.

 Before Click

 After Click

That's all with CSS selectivity. Ideal scenario is when no two rules conflict but in my personal experience conflicting rules are bound to happen for a big web project. This is when this rules come handle. Let me know if you still have any questions :).
t> UA-39527780-1 back to top