Monday, February 10, 2014

Best Practices Java - StringBuffer Part 2

It's good to define string as StringBuffer for most of the common use(Refer Part 1). We will now see how StringBuffer enlarge itself, as it is mutable.

If you are just calling the default creation of StringBuffer, the following code will get called(default size of 16 characters).

StringBuffer takes its data structure from its parent class which is AbstractStringBuilder, something like:

abstract class AbstractStringBuilder implements AppendableCharSequence {
            char value[]; // actual character storage.
int count; // count the no. of char's used.

This is how expandCapacity has been written in JDK:

void expandCapacity(int minimumCapacity) {
 int newCapacity = (value.length + 1) * 2;
 if (newCapacity < 0) {
  newCapacity = Integer.MAX_VALUE;
 } else if (minimumCapacity > newCapacity) {
  newCapacity = minimumCapacity;
 value = Arrays.copyOf(value, newCapacity);

This expandCapacity() has been called from append() method of StringBuffer. Most of the methods of StringBuffer are synchronized as expected.

For more understanding, you can see the openJDK source code. 


Saturday, February 08, 2014

Best Practices Java - StringBuffer

It's been 3 years when I have not done any blogging here. Some day before, one of my friends was asking me about StringBuffer and he has the point that I don't have any justification that why Sun has created StringBuffer.

I am writing this blog from a very rural village of Bihar, India. The common problem I found was people are not utilizing the time in best of work. Many of the kids go to the market to bring one-one item at a time. Alright, are we engineers also follow the same trend.

We use String as default and then we keep adding things in it. Something like:

String dontUse = "This";
dontUse +="is not right";

Alright, here is a small code I have written to understand the estimated time.

public class StringBufferExample {

public static void main(String[] args) {

String[] dontUse = new String[10000];
                //StringBuffer[] dontUse = new StringBuffer[10000];
for(int i=0;i<10000;i++) { }
long startTime = System.nanoTime();
for(int i=0;i<10000;i++) {
                        dontUse[i]= new String("this");
// dontUse[i]= new StringBuffer("this");
for(int i=0;i<10000;i++) {
                        dontUse[i]+="is wrong";
// dontUse[i].append("is wrong");
long endTime = System.nanoTime();
System.out.println(endTime - startTime);


Approx Time taken from this code: 5501435(ns) whereas if you run the commented code, it will take: 2258812(ns)
So, not visible but normal String operation for "simply" addition of two string is "twice" costlier than StringBuffer.

Running: javap -c -classpath . StringBufferExample (copying those lines which are costly), will clearly tell you why String operation is a costly affair(actually it was never a String operation, it changes things to StringBuffer and then again convert it by toString to String).

   64:  if_icmpge       97
   67:  new     #6; //class java/lang/StringBuilder
   70:  dup
   71:  invokespecial   #7; //Method java/lang/StringBuilder."<init>":()V
   74:  aload_1
   75:  iload   4
   77:  dup2_x1
   78:  aaload
   79:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/
   82:  ldc     #9; //String is wrong
   84:  invokevirtual   #8; //Method java/lang/StringBuilder.append:(Ljava/lang/
   87:  invokevirtual   #10; //Method java/lang/StringBuilder.toString:()Ljava/l
   90:  aastore

Now in the next blog, I will cover how StringBuffer handles the capacity, how it enlarge its capacity and when. It's a pretty simple code written in JDK.

Wednesday, October 06, 2010

JDK7 is on the way ...

Being a part of Oracle, I have not written any blog here. Anyways, Java doesn't belong to a company, its belong to the heart of billion people. There is lot which is coming in JDK7. Max. download is going to JDK6 which is a good news. People shifted from JDK1.5 and 1.4.2 to JDK6.

I will write some technical blog in coming days.

Friday, March 12, 2010

Garbage First prsentation - G1

My last year presentation on G1 aka Garbage First in Sun tech days.

This time also we are talking on G1. Join us at tech days at Hyderabad.

If you are interested in knowing more about Garbage First or any Garbage collector algorithms, please let me know here.

JDK6u12 - Mixing heavy and lightweight component

So, if you are a Swing Developer, you have heard many stories where someone messed up Lightweight component with Heavyweight component. In one line " A heavyweight component
is one that is associated with its own native screen resource (commonly
known as a peer). A lightweight component is one that "borrows" the
screen resource of an ancestor (which means it has no native resource
of its own -- so it's "lighter")." AWT is all heavyweight, Swing is all lightweight except top level ones like JFrame, JWindow...

Now many times you have heard "Don't mix lightweight and heavyweight". What will happen ? Alright, here is a small code :


import javax.swing.*;
import java.awt.*;

public class Test extends JPanel {

public Test() {
JComboBox jc = new JComboBox();
JButton btn1 = new JButton("Button1");
Button btn2 = new Button("Button2");
Button btn3 = new Button("Button3");


public static void main(String[] args) {
JFrame frame = new JFrame();
frame.getContentPane().add(new Test());
frame.setSize(200, 200);

Here what you see the output:

Now, this is what it happen what you mix lightweight and heavyweight. No way, you can bring the drop down items on top of Button2 !!

All Past :) , JDK6 update 12 and JDK7 build 19, the output will be like this:

New JDK release fixed all these problem of mixing lightweight component and heavyweight component. So, don't worry, keep messing :).

For more detail, please see this :

For more: Please join us at Tech Days at Hyderabad on 24-25th of March.

LiveConnect Docs for JDK6

JDK6 has done lot of changes in LiveConnect. LiveConnect is a feature in the browser for communication between Java Applet and JavaScript. With the new Plugin2, most of the work has been left on browser to do. Initially it was Java which do a good amount of work. So, now the Java Plug-in will operate like any other scriptable Plug-in.

This is one of the great document written :

If you want to see some code help, visit:

Have Fun !!

Monday, August 24, 2009

Hyperlink in JavaFX

It's a long time being blogging. Actually not done anything new from long time :). Here is one simple concept which some guys asked me. We have provided hyperlink API in JavaFX 1.2 but some of us struggled to open a URL using hyperlink API.

Hmm, 2 ways to do it actually.

No1 : Use the Desktop API of JDK6. It's simple to use. One example is here.

So, very basic code will go like this :


package sample2;

import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.control.*;

Stage {
title: "HyperLink to URL"
width: 240
height: 320
scene: Scene {
content: [
translateY: 160
translateX: 40
width: 150
text: bind "Visit javafx Samples! "
action: function():Void{
java.awt.Desktop.getDesktop().browse(new URI(""));

So, 2 things for running this code. First,Desktop API has been added in JDK6, so this code won't run on JDK5. Second, Add rt.jar(rt.jar of JDK6) file in the Libraries if you are using Netbeans

No2 : For only JavaFX code, we can use AppletStageExtension like this :

package sample1;

import javafx.stage.Stage;
import javafx.scene.Scene;
import javafx.scene.control.Hyperlink;
import javafx.stage.AppletStageExtension;

Stage {
title: "Hyperlink to URL"
width: 250
height: 80
scene: Scene {
content: [
Hyperlink {
text: "JavaFX Samples !"
action: function() {

In this case, you cant send hyperlink from Desktop Application, but it will work fine for applet or Browser application. So, best is to use this and then use our normal funda : if {__PROFILE__}" != "browser") --> use the Desktop API code. What you say :).

Please let me know if there is any issue in the code ! Or also if there is any better way to do this.

Java Debugging basics

Some simple debugging tools related to Java. These are for those who are new to Java.

1. Application is crashing : Most miserable one. Get your log file, try to analysis log. How to write log file, use Java Logger API. Java Logger had been introduced in JDK 1.4.2. The most awesome feature of Logger API is that you can use it in production without much overhead. The overhead is controlled by something called level in API. Level goes from FINEST to SEVERE. You can refer to O'Relly Book "Java, In a NutShell". I guess, it covers Logging API into a great detail.

Lot many things to know: Standalone application is crashing or web application. Its crashing with -client or -server option, appletviewer or browser, plugin or plugin2.

2. Application Hang: Most prominent reason for Hang is thread related. I don't know too many language but Java handles thread in most graceful way. What we can do when a Java Process or Application Hang:

- Hmm, get stack trace at Java and native level.
- Get to know current thread conditions and their status.
- Try to get core dump. Sometime, application will refuse to give you.
- Get to know machine detail. Almost all OS, use different thread model. Not only that in Solaris, 8 and 9 use different models. Sometime, it narrow down the problem, if you are luck :).

How to get all these information. Easy actually. Take help of Java Debugger, jdb(which is a part of JDK). In jdb, you can run the command like threads, thread, dump and many more. Take help of Windbg, if its a windows machine for native level. I find it useful and painful.

3. Your application is drinking memory: There is some memory leak. Best is to use jhat(part of JDK). First take a heap dump by using jmap, jconsole hprof. Pass that heap dump to jhat and it will bring a server and

dump all the information. Analyze where most of the memory is going. Writing to track the place from where memory is going. What is GC response on it. Change some arguments of GC and then give a try.

There are lot of JDK tools that help in analyzing JVM, threads, memory, process. See the list :

Garbage collector play important role in all of them, so always get to know what is best for what:- (Even you know less about GC, you can't resist yourself finishing this page, this is so interesting). In terms of GC, everything is improving day be day and we have new GC, Garbage First aka G1 ready. With Vikram, I had one presentation on G1 in Sun tech days -

If you have any wired debugging story related to Java, please share :). Also, visit Visual VM which is meant to integrate all the command line tools of JDK.

Tuesday, December 30, 2008

Z-Order is supported in JavaFX !

While writing some of the samples in which we have to play with images, we sometimes has to manage the depth of the images. Like for the Carousel example, every image has a depth. In that example, actually images are not overlapping with each other, so we never need to write the Z-Order concept. But if someone want to write a Carousel or some application in which Images are residing over other images, we need to set the Z-order of Images. Z-Order in literal term means depth-ness of images. JavaFX gracefully provide API's to set the Z-order of images. With a simple call, you can set the images toFront or toBack features.

In this example, I have taken 3 images and try to set the depth-ness of images on the event of Buttons.

First Image on Top Second Image on Top

Third Image on Top

Here is the code to set the Z-Order :

package zorder;

import javafx.scene.Group;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.paint.Color;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.scene.shape.Rectangle;
import javafx.scene.input.MouseEvent;
import javafx.ext.swing.SwingButton;

var im1 = ImageView {
x: 100
y: 100
image: Image {
url: "{__DIR__}im1.PNG"
opacity: 0.8

var im2 = ImageView {
x: 130
y: 130
image: Image {
url: "{__DIR__}im2.PNG"
opacity: 0.8

var im3 = ImageView {
x: 160
y: 160
image: Image {
url: "{__DIR__}im3.PNG"
opacity: 0.8

var gp = Group {
im1, im2,im3

Stage {
title: "Application title"
width: 400
height: 400
scene: Scene {
fill: Color.BLACK
content: [
SwingButton {
translateX: 10
translateY: 10
text: "Image 1"
action: function() {
SwingButton {
translateX: 90
translateY: 10
text: "Image 2"
action: function() {
SwingButton {
translateX: 170
translateY: 10
text: "Image 3"
action: function() {

From next blog, I will use applet or JNLP in place of images, as suggested by Dmitry in last blog. Pictures make it bulky and uneasy to load. But I was getting some problem in deploying the application on Sun blog which will be rectified soon.

Monday, December 22, 2008

JavaFX production Suite - How it work

Here is the little discussion on Designer + Developer workflow in JavaFX. Powered with Project Nile, we can export data from PhotoShop or Illustrator. Actually the complete production suite is awesome and provide developer and designer to work in parallel. Here how it is :

So, Developer can work on the business logic and till that time designer can design the actually content for developer. Finally it will merge in a great style. 

 Basic Requirement to do :

1. JavaFX Production Suite : Download from the start section of

2. For Designer : Any tool, either PhotoShop CS3 or Illustrator CS3. Officially CS3 is the supported platform but it works for CS4 as well.

3. For Developer : Java FX SDK: Download from the start section of

Now, I am going ahead with PhotoShop. Copy the plugin from JavaFX production suite to PhotoShop. Run the PhotoShop, in export it will give you a save option in JavaFX, which basically saves the file in fxz format(a new format, why Sun need a new format, there is a lot of discussion and Jeet has pointed some reason in his blog).

Alright, so work started : 

I was watching the batman movie, so decide to take his awesome car, which is here :

In photoshop, I have changed the hue and exported all in fxz format.

Then I made a Netbeans Project, Copy the fxz file into the project space. We can now click on fxz file, we can see the preview and code as well. Right now, if we put some of the complex features of PhotoShop, I am afaird to say JavaFX will not catch those changes.

So, my fxz file(JavaFX.fxz) looks like this :

 * Generated by JavaFX plugin for Adobe Photoshop.
 * Created on Fri Dec 19 19:17:33 2008
//@version 1.0

Group {
    clip: Rectangle { x:0 y:0 width:576 height:432 }
    content: [
        ImageView {
            opacity: 1.0
            x: 0
            y: 0
            image: Image {
                url: "{__DIR__}Background.png"

Actually in my case there was nothing, so it generated a simple code :).

Now, I have made another file, calling it CarRotate.fx :

package psfx;

import java.lang.*;
import javafx.fxd.FXDLoader;
import javafx.scene.*;
import javafx.scene.input.*;
import javafx.scene.paint.Color;
import javafx.scene.shape.*;
import javafx.stage.*;

var group = Group {
    content: []
var fxdContent = FXDLoader.load("{__DIR__}JavaFX.fxz"); // loads the content
insert fxdContent into group.content; // inserts the fxd content into the group

Stage {
    title: "JavaFX Invaders"
    resizable: true
    width: 700
    height: 700
    onClose: function() {
        System.exit (0);

    scene: Scene {
        content: [
            Rectangle {
                x: 330,
                y: 500
                width: 60,
                height: 30
                fill: Color.GRAY
                onMouseClicked: function( e: MouseEvent ):Void {
                    fxdContent.rotate = 90;

Some part of the code is point of interest :

  var group = Group {

    content: []


var fxdContent = FXDLoader.load("{__DIR__}JavaFX.fxz"); // loads the content

insert fxdContent into group.content; // inserts the fxd content into the group

Here I have loaded the .fxz file into var fxdContent which is a node and node means things are in our hand. I have simply written a rotate equation on a button click which is working nicely.

We can see the rotated car and hue which is the asset of PhotoShop in Green color. Huh, finally its done. Sorry, for posting bad example.

JavaFX - Developer and Designer work !

One more example of JavaFX production Suite. Though the complete thing can be done in Photoshop alone but I am just giving an example. I have made a house in Photoshop, which is not very good :(, but fair enough. And I animated the star effect in JavaFX.

So, here is my home in photoshop :

Actually this is funny, I was following a tutorial to make house and in temptation, I made shadow as well, but there is no meaning of shadow in night :). Now, I filled star sparking effect in this from JavaFX.

Filling star effect need same which we have written for sparkling glasses. Just some changes here and there. In the last blog we have already discussed how to import work from Photoshop.

Here are the things to download:

1. House in fxz format .

2. Code (Main.fx, Star.fx)

Lot many things can be done. But I don't know Photoshop.