Posts

Showing posts with the label String

Mystry of Java String.intern

Mystery of Java String.intern We have all learn about how Java has optimised handling string objects. The String class has been made immutable and string literal definition makes sure that existing instance from string pool will be returned instance creating new one. Here is simple code snippet that explains it String firstName = "John"; String firstNameWithNew = new String("John"); String duplicateFirstName = "John"; //All there strings are same System.out.println(firstName.equals(duplicateFirstName) && firstName.equals(firstNameWithNew));//=> true //Since they defiend using string iterals, even there memory references are same System.out.println(firstName == duplicateFirstName);//=> true //Since one of the object has defined explictly using new operator, there memory references are different. System.out.println(firstName == firstNameWithNew);//=> false This is very basic understanding that everyone has. Then I came across String.in...

Eclipse SWT : Transform Keyboard key codes to String Format

Image
While working on RCP application in eclipse, you need to capture and display the key or combination of key pressed by user. For example to capture key combination for a binding. If it is character key (printable) then its easy to get character presentation from pressed key code. But it would be little difficult to represent sequence of key or non printable key like “Insert”, “Backspace” etc. The straight forward way is to have map between key integer code and its string presentation, liked explained in SWT snippet Print Key State, Code and Character . There is optimized and standard way is available using eclipse JFace framework. It provides a utility class , SWTKeySupport , for converting SWT events into key strokes and KeySequence , to represent zero or multiple key strokes. KeySequence provides standard string presentation of sequence of keys captured. Here is the simple SWT program to demonstrate usage of these utility classes import org.eclipse.jface.bindings.keys.KeySequenc...

StringBuffer vs StringBuilder : Performance improvement figures

IN previous post StringBuffer vs StringBuilder , I have explained benefits of using StringBuilder over StringBuffer. Here are some performance figure using both for concatenating string. package com.test;   public class StringConcatenateTest { public static void main(String[] args) { System.out.println( "Using StringBuffer" ); long bufferTime = usingStringBuffer(); System.out.println( "Using String Builder" ); long builderTime = usingStringBuilder(); double perc = (( double )(bufferTime-builderTime)/bufferTime)* 100; System.out.println( "Improved in performance = " + perc + "%" ); } public static long usingStringBuffer(){ long startTime = System.currentTimeMillis(); System.out.println( "\tStart time = " + startTime); StringBuffer sb = new StringBuffer(); for ( int i=0;i<1000000;i++){ sb.append( "\tSample ...

Lazy initializing your code

Many time we have static fields in our Java classes. These fields are get initialized with loading of your classes and all other static fields. But many time its not the urgent to initialize few of the fields while loading the class itself. Here the concept of lazy initialization comes in picture. Consider the code below public class LazyInitilaizationTest { public static String[] field = getStringContent(); static { System.out.println( "Loading Class" ); } public static String[] getStringContent(){ System.out.println( "Initializing field" ); return new String[]{}; } public static void main(String[] args) { System.out.println( "Accessing Field" ); System.out.println(field); } } Here the class has private & static field which gets initialized by invoking getStringContent () method. Running above class prints following output Initializing field Loading Class Acce...

Java Puzzle : String concatenation

I have simple program to print date after month from now. 1: package com.test; 2:   3: import java.text.ParseException; 4: import java.text.SimpleDateFormat; 5: import java.util.Date; 6:   7: public class Test{ 8: public static void main(String[]args) throws ParseException{ 9: Date currentDate = new Date(); 10: int d = currentDate.getDate(); 11: int month = currentDate.getMonth()+1; 12: int year = currentDate.getYear() +1900; 13: //trying to update to next moth same date 14: Date nextMonthDate = new SimpleDateFormat( "dd-MM-yyyy" ) 15: .parse(d + "-" 16: + month+1 + "-" // increasing month by one to get next month 17: + year); 18: System.out.println( "Current Date = " + currentDate); 19: System.out.println( "Next Month Date = " +nextMonth...

Java Puzzle–Immutable String

what will be output of the following program ? 1: class StringTest2 2: { 3: public static void main(String[] args) 4: { 5: String str1 = " Hello "; 6: String str2 = " HELLO "; 7: String str3 = str1.toUpperCase(); 8: String str4 = str2.toUpperCase(); 9: System.out.println(str1 == str3); 10: System.out.println(str2 == str4); 11: } 12: }

Java puzzle–StringBuffer

What will be the output of following program ? 1: class StringBufferTest2 2: { 3: public static void main(String[] args) 4: { 5: StringBuffer sb1,sb2; 6: sb1 = new StringBuffer(); 7: sb2 = new StringBuffer(); 8: sb1.append(" Hello "); 9: sb1.append(" Hello "); 10: boolean result = sb1.equals(sb2); 11: System.out.println(" Result = "+ result); 12: } 13: }

StringBuilder over StringBuffer

As String is an immutable class , any update operations  like replace/substring/append is very expensive. As solution for this StringBuffer class has been introduced for all string update related operations. But problem with StringBuffer is that it is a synchronized class. All its public methods are tagged as “synchronized”. This adds an extra cost to string update operation whenever synchronized is actually not needed. As part of JDK 1.5 a new utility class called StringBuilder has been introduced for non-synchronized string update operations. StringBuilder is designed as a replacement for StringBuffer in single-threaded usage. It means using StrinBuilder instead of StringBuffer where ever synchronization is not an issue will be added to program performance.

Understanding Java Garbage Collector

Image
     Java’s garbage collection system reclaims objects automatically occurring transparently, behind the scenes, without any programmer intervention. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object is released. This recycled memory can then be used for a subsequent allocation. Although it complete transparent to developer, understanding how GC works helps developer to improve efficiency of Java Program. It is also helpful to improve performance of the program. JDK provides many runtime options to analysis GC and analysis your program behavior. Here is the simple java program to understand GC behavior 1: public class GCTest { 2: public GCTest() { 3: } 4: 5: public static void main(String[] args) { 6: int count = 10000; 7: long startTime = System.currentTimeMillis(); 8: System.out.println(" Total Count = " + count...

Concurrency in Singleton Designing Pattern

      Please refer previous post for Singleton Designing Pattern . Concurrency is the one of the major issues with singleton designing pattern.       There will be multiple client accessing same singleton resource instance. If this resource is mutable then concurrency need to be taken care . Example from previous post is being used here. 1: package demo.singleton; 2: import java.util.concurrent.locks.ReadWriteLock; 3: import java.util.concurrent.locks.ReentrantReadWriteLock; 4: /** 5: * Singleton Resource Class 6: * @author Yogesh 7: */ 8: public class SingletonResource { 9: private static SingletonResource resorce = null ; 10: int count; 11: private ReadWriteLock writeLock = new ReentrantReadWriteLock(); 12: 13: public static SingletonResource getInstance(){ 14: if (resorce == null ){ 15: synchronized (SingletonResource. class ){ 16: if (res...

RESTful WS using Jersey Part 3 – Java Client

This post is with reference of Restful WS using Jersey Part 2 – Parameterized approach to provide a java client for accessing Restful services The Complete code for Java Client /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package demo.client; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URL; import java.net.URLConnection; /** * * @author Yogesh */ public class JavaClient {     public static void main(String[] args) {         String restUrlStr = " http://localhost:17286/HelloWorldRestWSPrj/resources/hello/Yogesh?query=age";         URLConnection conn = null;         try {             URL restUrl = new URL(restUrlStr);   ...

RESTful WS using Jersey Part 1 - Hello World

Image
Here is the simple tutorial for RESTful Web Service using jersey implementation for RESTful Web Services. Java EE 6 has introduced jersey API as implementation for JSR-311 as API for RESTful Web Services. For ease of development,deployment and testing i have used NetBean 6.8 which supports JEE 6. Jersey is an annotation based implementation. Here are the few important annotations used in this tutorial @path(“/path/”) - a relative URI path indicating where the Java class will be hosted @GET - a request method designator and corresponds to HTTP Get method @POST - a request method designator and corresponds to HTTP Post method @Produces("text/plain") - specify the MIME media types of representations a resource can produce @Consumes("text/plain") -specify the MIME media types of representations a resource can consume @PathParam("User_Name") - a type of parameter that you can extract for use in your resource class @QueryPar...