Showing posts with label Core Java Concepts. Show all posts
Showing posts with label Core Java Concepts. Show all posts

Monday, March 12, 2012

Java Synchronization

Synchronization in Java:

Java Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner where only one thread can access one resource at a time. In non synchronized multithreaded application, it is possible for one thread to modify a shared object, while another thread is in the process of using or updating the object's value.

Synchronization prevents such type of data corruption. Synchronization is best use with the Multi-Threading in Java. Synchronization can be done at two levels:
  • Synchronizing a function
  • Synchronizing a block of code
Please find the sample code below

Synchronizing a function
public synchronized void  Display() 
{
   // related code
}
Synchronizing a block of code inside a function:
 public myFunction ()
{
  synchronized (this)
   {
  // Synchronized code
   }
}

Read more...

Friday, January 20, 2012

Java Stack and Heap Memory

Java Stack and Heap Memory: 

Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class). In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed. In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space. The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronization through your code. 

A method in stack is re-entrant allowing multiple concurrent invocations that do not interfere with each other. A function is recursive if it calls itself. Given enough stack space, recursive method calls are perfectly valid in Java though it is tough to debug. Recursive functions are useful in removing iterations from many sorts of algorithms. All recursive functions are re-entrant but not all re-entrant functions are recursive. Idempotent methods are methods, which are written in such a way that repeated calls to the same method with the same arguments yield same results. For example clustered EJBs, which are written with idempotent methods, can automatically recover from a server failure as long as it can reach another server.

Read more...

Thursday, February 4, 2010

STRING OBJECTS in JAVA

The Java String class (java.lang.String) is a class of object that represents a character array of arbitrary length. While this external class can be used to handle string objects, Java integrates internal, built-in strings into the language.

An important attribute of the String class is that once a string object is constructed, its value cannot change (note that it is the value of an object that cannot change, not that of a string variable, which is just a reference to a string object). All String data members are private, and no string method modifies the string’s value.


CONVERTING OBJECTS TO STRINGS


The String + operator accepts a non-string operand, provided the other operand is a string. The action of the + operator on non-string operands is to convert the non-string to a string, then to do the concatenation. Operands of native types are converted to string by formatting their values. Operands of class types are converted to a string by the method toString()

that is defined for all classes. Any object or value can be converted to a string by explicitly using one of the static valueOf() methods defined in class String:

String str = String.valueOf (obj);
If the argument to valueOf() is of class type, then valueOf() calls that object’s toString() method. Any class can define its own toString() method, or just rely on the default. The output produced by toString() is suitable for debugging and diagnostics. It is not meant to be an elaborate text representation of the object, nor is it meant to be parsed. These conversion rules also apply to the right-hand side of the String += operator.

CONVERTING STRINGS TO NUMBERS


Methods from the various wrapper classes, such as Integer and Double, can be used to convert numerical strings to numbers. This is often necessary for command line arguments where the parameter list is available to the
main () method as a string array. The wrapper classes contain static methods ( such as parseInt() ) which convert a string to its own internal data type.

These can be used with class names rather than creating a separate object. Be aware that these particular conversion methods throw a NumberFormatException and must be used in the context of a try and catch block combination.

Read more...

Sunday, June 21, 2009

Java Garbage Collection

Garbage Collection in Java

Java has built-in facility to re-claim unwanted memory, this is known as garbage collection. Garbage collector plays its role if there is any memory defficiency. Usually an object no longer referenced, for example when you assign with null, it could be ready for garbage collection. In java all objects are created in heap memory, whereas primitive type and object reference are placed in stack memory. Object class has defined finalize() method that is called by the garbage collector on an object when garbage collection determines that there are no more references to the object.


The purpose of Java Garbage Collection is to identify and discard objects that are no longer needed by a program so that their resources can be reclaimed and reused. A Java object is subject to garbage collection when it becomes unreachable to the program in which it is used. Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory.


Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to explicitly assign null into a variable when no more in use. In Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. Java Garbage collection is an automatic process and can't be forced.

Java Garbage Collection program

class GC
{

public static void main(String args[]){
MyObj obj = new MyObj();
obj=null;
System.gc();
}
}

class MyObj
{

public MyOb(){
System.out.println("Object created");
}

protected void finalize()
{

System.out.println("Garbage collector in action");
}
}
Garbage collection will start immediately upon request of System.gc(). Garbage collection does not guarantee that a program will not run out of memory. It is possible for programs to use up memory resources faster than they are garbage collected. It is also possible for programs to create objects that are not subject to garbage collection.

Read more...

Friday, May 8, 2009

Java Static Modifier

Static Modifier in Java:

In java we can have a Static Block, Static Variable, Static Method. Static modifier specifies that a variable or method is the same for all objects of a particular class. Some times we need a common variable or method for all objects of a part icular class. Typically, new variables are allocated for each instance of a class.

Variable declared as being static is only allocated once, regardless of how many objects are instantiated and all instantiated objects share the same instance of the static variable.
Similarly, a static method is one whose implementation is exactly the same for all objects of a part icular class. Static methods have access only to static variables.

Example of a static member variable and a static method:

static int refCount;
static int getRefCount() {
return refCount;
}
A beneficial side effect of static members is that they can be accessed without having to create an instance of a class. Static method or a variable is not attached to a particular object, but rather to the class as a whole. They are allocated when the class is loaded.

A static initializer block resembles a method with no name, no arguments, and no return type. It doesn't need a name, because there is no need to refer to it from outside the class definition. The code in a static initializer block is executed by the virtual machine when the class is loaded.

Example of a Static Block
static{
date1 = new Date();
for(int count = 0; count <>
var = var+1;
}
Static blocks are blocks defined within the body of a class using the static keyword but which are not inside any other blocks.

Read more...

Thursday, May 7, 2009

Java Access Modifiers

Access Modifiers in Java

Access to variables and methods in Java classes is accomplished through access modifiers. Access modifiers define varying levels of access between class members and the outside world (other objects). Access modifiers are declared immediately before the type of a member variable or the return type of a method.

There are four access modifiers in java :

  • default
  • public
  • protected
  • private
Access modifiers affect the visibility not only of class members, but also of classes themselves.

Default Access Modifier

The default access modifier specifies that only classes in the same package can have access to a class's variables and methods. Class members with default access have a visibility limited to other classes within the same package. There is no actual keyword for declaring the default access modifier, it is applied by default in the absence of an access modifier.

Code for default access variable and member:
long length;
void getLength() {
return length;
}
Notice that neither the member variable nor the method supplies an access modifier, so each
takes on the default access modifier implicitly.

public Access Modifier

The public access modifier specifies that class variables and methods are accessible to anyone, both inside and outside the class. This means that public class members have global
visibility and can be accessed by any other object.

Sample Code for public member variables:
public int count;
public boolean valid;
protected Access Modifier

The protected access modifier specifies that class members are accessible only to methods in that class and subclasses of that class. This means that protected class members have visibility limited to subclasses.

Sample code for protected variable and a protected method :
protected char Name;
protected char getName() {
return Name;
}
The private Access Modifier

The private access modifier is the most restrictive; it specifies that class members are accessible only by the class in which they are defined. This means that no other class has access to private class members, even subclasses.

Code example for private member variables:
private String firstName;
private double Value;
Access to classes, constructors, methods and fields are regulated using access modifiers. Access modifiers in Java determine the visibility and the scope of the Java elements.

Read more...

Monday, May 4, 2009

Java Object Serialization

Serialization in Java :

Serialization is the process of converting a set of object instances that contain references to each other into a linear stream of bytes, which can then be sent through a socket, stored to a file, or simply manipulated as a stream of data. Serialization involves saving the current state of an object to a stream, and restoring an equivalent object from that stream.

Serialization is the mechanism used by RMI to pass objects between JVMs, either as arguments in a method invocation from a client to a server or as return values from a method invocation.

For an object to be serialized, it must be an instance of a class that implements either the Serializable or Externalizable interface. Both interfaces only permit the saving of data associated with an object's variables.

The Serializable interface relies on the Java runtime default mechanism to save an object's state. Writing an object is done via the writeObject() method in the ObjectOutputStream class or the ObjectOutput interface.

The Externalizable interface specifies that the implementing class will handle the serialization on its own, instead of relying on the default runtime mechanism.

Classes ObjectInputStream and ObjectOutputStream, which respectively implement the ObjectInput and ObjectOutput interfaces, enable entire objects to be read from or written to a stream (possibly a file). To use serialization with files, we initialize ObjectInputStream and ObjectOutputStream objects with stream objects that read from and write to files—objects of classes FileInputStream and FileOutputStream, respectively.

Initializing stream objects with other stream objects in this manner is sometimes called wrapping—the new stream object being created wraps the stream object specified as a constructor argument. To wrap a FileInputStream in an ObjectInputStream, for instance, we pass the FileInputStream object to the ObjectInputStream’s constructor.

The ObjectOutput interface contains method writeObject, which takes an Object that implements interface Serializable (discussed shortly) as an argument and writes its information to an OutputStream. Correspondingly, the ObjectInput interface contains method readObject, which reads and returns a reference to an Object from an InputStream. After an object has been read, its reference can be cast to the object’s actual type.

The object to be serialized must implement java.io.Serializable. This example serializes a javax.swing.JButton object.


Object object = new javax.swing.JButton("push me");

try {
// Serialize to a file
ObjectOutput out = new ObjectOutputStream(new FileOutputStream("filename.ser"));
out.writeObject(object);
out.close();

// Serialize to a byte array
ByteArrayOutputStream bos = new ByteArrayOutputStream() ;
out = new ObjectOutputStream(bos) ;
out.writeObject(object);
out.close();

// Get the bytes of the serialized object
byte[] buf = bos.toByteArray();
} catch (IOException e)
{
}


Object serialization is performed with byte-based streams, so the sequential files created and manipulated will be binary files. Recall that binary files cannot be viewed in standard text editors.

Read more...

Friday, April 17, 2009

HashSet Collection Sample Program Code

Sample Program on HashSet Collection:

A HashSet is a collection set that neither allows duplicate elements nor order or position its elements.

HashSet Methods

  • add() method is used to insert an element in the HashSet collection.
  • size() method helps you in getting the size of the collection.
  • remove() method will be used to delete an element in the HashSet collection.
  • clear() method is used to remove all data from the HashSet collection.
Sample program: HashSet program shows the methods to add, remove and iterate the values of collection. Keys will be used to put and get values. When the HashSet is empty, the below program checks and will display a message "Collection is not having any Elements". If the collection is having Elements then program displays the size of HashSet collection.

import java.util.*;

public class HSetHasHSetet {
public static void main(String [] args) {
System.out.println( "HashSet Example" );
int size;

// Create a HashSet
HasHSetet HSet = new HasHSetet ();
String string1 = "Yellow", string2 = "White",
string3 = "Green", string4 = "Blue";
Iterator iterator;

//Adding data in to HashSet
HSet.add(string1);
HSet.add(string2);
HSet.add(string3);
HSet.add(string4);
System.out.print("HashSet data: ");

//Create a iterator
iterator = HSet.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();

// Get size of a HSet
size = HSet.size();
if (HSet.isEmpty()){
System.out.println("HashSet is empty");
}
else{
System.out.println( "HashSet size: " + size);
}
System.out.println();

// Remove specific data
HSet.remove(string2);
System.out.println("After removing [" + string2 + "]\n");
System.out.print("Now HashSet data: ");
iterator = HSet.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = HSet.size();
System.out.println("HashSet size: " + size + "\n");

//HashSet empty
HSet.clear();
size = HSet.size();
if (HSet.isEmpty()){
System.out.println("Collection is not having any Elements");
}
else{
System.out.println( "HashSet size: " + size);
}
}
}

Read more...

Wednesday, April 15, 2009

Java Wrapper Classes (java.lang package)

(java.lang package) Wrapper Classes in Java:

Each of Java's eight primitive data types has a class dedicated to it. These are known as wrapper classes, because they "wrap" the primitive data type into an object of that class. So, there is an Integer class that holds an int variable, there is a Double class that holds a double variable, and so on. The wrapper classes are part of the java.lang package, which is imported by default into all Java programs.

For each primitive type there is a Wrapper Class: Boolean, Byte, Character, Double, Float, Integer, Long, and Short. Byte, Double, Float, Integer and Short extend the abstract Number class and all are public final ie cannot be extended.

Classes have two constructor forms:

  • constructor that takes the primitive type and creates an object eg Character(char), Integer(int)
  • constructor that converts a String into an object eg Integer("1"). Throws a NumberFormatException if the String cannot be converted to a number.
There is also a wrapper class for Void which cannot be instantiated.

Observe that an Object starts with a capital letter, while the primitives all start with a lowercase and also remember that Strings are Ojects.

Check here for primitive to Wrapper mapping:
byte --> Byte
short --> Short
int --> Integer
long --> Long
char --> Character
float --> Float
double --> Double
boolean --> Boolean
void --> Void
Sample Code for some of the Java Wrapper Classes :
Integer:
int i = 5;
Integer I = Integer.valueOf(i); //Wrapper Class
int i2 = I.intValue(); //Converting to primitive

Float:
float f = 5.5f;
Float F = Float.valueOf(f); //Wrapper Class
float f2 = F.floatValue(); //Converting to primitive

Double:
double d = 5.55555;
Double D = Double.valueOf(d); //Wrapper Class
double d2 = D.doubleValue(); //Converting to primitive

Boolean:
boolean b = true;
Boolean B = Boolean.valueOf(b); //Wrapper Class
boolean b2 = B.booleanValue(); //Converting to primitive
The wrapper classes also provide various tools such as constants nd static methods. We will often use wrapper methods to convert a number type value to a string or a string to a number type as mentioned above.

Read more...

Wednesday, April 8, 2009

Heap Memory and Stack Memory in Java

Difference between Heap Memory and Stack Memory in Java:

STACK memory is referred as temporary memory,if you come out of the program the memory of the variable will not no more there. STACK memory and HEAP memory may be allocated by the compiler for data storage. The stack is where memory is allocated for automatic variables within functions. A stack is a Last In First Out (LIFO) storage device where new storage is allocated and de-allocated at only one 'end' called the Top of the stack.

HEAP memory is referred as permanent memory,memory allocated for the object will be maintained even if we came out of the program. For example memory for OBJECT will remains there ever.

The heap segment provides more stable storage of data for a program memory allocated in the heap remains in existence for the duration of a program. Therefore, global variables (storage class external), and static variables are allocated on the heap. The memory allocated in the heap area, if initialized to zero at program start, remains zero until the program makes use of it. Thus, the heap area need not contain garbage.

Comparison:

When a function or a method calls another function which in turns calls another function etc., the execution of all those functions remains suspended until the very last function returns its value. This chain of suspended function calls is the stack, because elements in the stack (function calls) depend on each other. The stack is important to consider in exception handling and thread executions.

The heap is simply the memory used by programs to store variables. Element of the heap (variables) have no dependencies with each other and can always be accessed randomly at any time.

Read more...

Saturday, February 21, 2009

Creating a zip file in Java

Java Code Example: Create a zip file in Java

Steps:

  • Create an input stream from the file to compress
  • Read from it we write the contents to an output stream.
  • Output stream is of type ZipOutputStream which takes an FileOutputStream as parameter.
  • Add a zip entry to the output stream before we start writing to it.
  • Clean up by closing the zip entry and both the input stream and output stream.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
*
* @author javadb.com
*/

public class Main {

/**
* Creates a zip file
*/

public void createZipFile() {

try {
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";

//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new
FileOutputStream(zipFileName));

// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));

byte[] buffer = new byte[1024];
int bytesRead;

//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}

//Close zip entry and file streams
outStream.closeEntry();

outStream.close();
inStream.close();

} catch (IOException ex) {
ex.printStackTrace();
}
}

/**
* @param args the command line arguments
*/

public static void main(String[] args) {
new Main().createZipFile();
}
}

Read more...

Saturday, February 14, 2009

Thread Constructors

Several constructors are available for creating new Thread instances.
  • Thread()
  • Thread(String)
  • Thread(Runnable)
  • Thread(Runnable,String)
  • Thread(ThreadGroup,String)
  • Thread(ThreadGroup,Runnable)
  • Thread(ThreadGroup,Runnable,String)
  • Thread(ThreadGroup, Runnable, String, long)
ThreadGroup– All threads belongs to an instance of the ThreadGroup Class. ThreadGroup is used to represent a group of threads. ThreadGroups can be shown in a hierarchical manner. There is only one root ThreadGroup that contains all other thread and groups and each subgroups can contain other groups and threads.

All thread have only one thread group. And all thread groups (except the root thread group) belongs to exactly one parent thread group. Threads can access only belonging thread group.

When a new ThreadGroup is created, it is added as a member of existing ThreadGroup.
If a thread x in group1, and executes the code:
  • ThreadGroup group2=new ThreadGroup(“group2”);
Then the newly formed group2 comes under group1. If you want a parent group other than default then you have to specify the parent group at the time of creation.
  • ThreadGroup group2=new ThreadGroup(group2,“group3”);
Then newly formed group3 comes under the group2.

Some important methods are:

getName() – This method is used to retrieve the name of particular group.
  • ThreadGroup g=new ThreadGroup(“RoseIndia”);
  • String gname=g.getName();
getParent() – This method is used to retrieve the name of parent threadgroup of sub group.
  • ThreadGroup group=group3.getParent();
activeGroupCount() – This method returns the number of active thread group in a particular thread group and all its subgroups.
  • int size=group.activeGroupCount();
getThreadGroup() – This method is used to know the thread is belong to which thread group.
  • ThreadGroup group=threadx.getThreadGroup();

Read more...

Java Virtual Machine (JVM)

Java is that it uses bytecode - a special type of machine code. Java bytecode executes on a special type of microprocessor. Strangely enough, there wasn't a hardware implementation of this microprocessor available when Java was first released. Instead, the processor architecture is emulated by what is known as a "virtual machine". This virtual machine is an emulation of a real Java processor - a machine within a machine (Figure One). The only difference is that the virtual machine isn't running on a CPU - it is being emulated on the CPU of the host machine.

The Java Virtual Machine is responsible for interpreting Java bytecode, and translating this into actions or operating system calls. For example, a request to establish a socket connection to a remote machine will involve an operating system call. Different operating systems handle sockets in different ways - but the programmer doesn't need to worry about such details. It is the responsibility of the JVM to handle these translations, so that the operating system and CPU architecture on which Java software is running is completely irrelevant to the developer.

Different JVM implementations:

Though implementations of Java Virtual Machines are designed to be compatible, no two JVMs are exactly alike. For example, garbage collection algorithms vary between one JVM and another, so it becomes impossible to know exactly when memory will be reclaimed. The thread scheduling algorithms are different between one JVM and another (based in part on the underlying operating system), so that it is impossible to accurately predict when one thread will be executed over another.

Initially, this is a cause for concern from programmers new to the Java language. However, it actually has very little practical bearing on Java development. Such predictions are often dangerous to make, as thread scheduling and memory usage will vary between different hardware environments anyway. The power of Java comes from not being specific about the operating system and CPU architecture - to do so reduces the portability of software.

The Java Virtual Machine provides a platform-independent way of executing code, by abstracting the differences between operating systems and CPU architectures. Java Runtime Environments are available for a wide variety of hardware and software combinations, making Java a very portable language. Programmers can concentrate on writing software, without having to be concerned with how or where it will run. The idea of virtual machines is nothing new, but Java is the most widely used virtual machine used today. Thanks to the JVM, the dream of Write Once-Run Anywhere (WORA) software has become a reality.

The Java Virtual Machine forms part of a large system, the Java Runtime Environment (JRE). Each operating system and CPU architecture requires a different JRE. The JRE comprises a set of base classes, which are an implementation of the base Java API, as well as a JVM. The portability of Java comes from implementations on a variety of CPUs and architectures. Without an available JRE for a given environment, it is impossible to run Java software.

Read more...

Monday, November 24, 2008

EJB Design Patterns eBook

EJB Design Patterns
By Floyd Marinescu

EJB Design Patterns goes beyond high-level design pattern descriptions into critical EJB-specific implementation issues, illustrated with source code implementations. The book contains a catalog of twenty advanced EJB patterns and provides strategies for mapping application requirements to patterns-driven design, J2EE development best practices, and a collection of EJB tips and strategies, and other topics such as Build-System best practices using Ant, JUnit testing strategies, using Java Data Objects (JDO) as an alternative to entity beans, and more.

Floyd Marinescu draws on his work building TheServerside.com J2EE community site and offers best practices for three different strategies used in creating primary keys for entity beans: sequence blocks, UUID for EJB, and stored procedures for autogenerated keys.

Read more...

Saturday, November 22, 2008

StringBuilder StringBuffer

StringBuilder vs StringBuffer

StringBuffer is used to store character strings that will be changed (String objects cannot be changed). It automatically expands (buffer size) as needed. Related classes: String, CharSequence.

StringBuilder was added in Java 5.0. It is identical in all respects to StringBuffer except that it is not synchronized, which means that if multiple threads are accessing it at the same time, there could be trouble. For single-threaded programs, the most common case, avoiding the overhead of synchronization makes the StringBuilder very slightly faster. No imports are necessary because these are both in the java.lang package.

StringBuffer and StringBuilder methods and constuctors

Assume the following code:

StringBuffer sb = new StringBuffer();
StringBuffer sb2;
int i, offset, len;
char c;
String s;
char chararr[];
Constructors
sb = new StringBuffer(); // Creates new, empty, StringBuffer
sb = new StringBuffer(n); // Creates new StringBuffer of size n
sb = new StringBuffer(s); // Creates new StringBuffer with initial value s
Using StringBuffer
sb2 = sb.append(x) //appends x (any primitive or object type) to end of sb.
sb2 = sb.append(chararr, offset, len) //appends len chars from chararr starting at index offset.
sb2 = sb.insert(offset, x) // inserts x (char, int, String, ...) at position offset.
sb.setCharAt(index, c) // replaces char at index with c
Deleting from StringBuffer
sb2 = sb.delete(beg, end) //deletes chars at index beg thru end.
sb.setLength(n) // Sets the length of the content to n by either truncating current content or extending it with the null character ('\u0000').
Use sb.setLength(0); to clear a string buffer.
Extracting Values from StringBuffer
c = sb.charAt(i) // char at position i.
s = sb.substring(start) // substring from position start to end of string.
s = sb.substring(start, end) // substring from position start to the char before end.
s = sb.toString() // Returns String.
Searching in StringBuffer
i = sb.indexOf(s) //Returns position of first (leftmost) occurrence of s in sb.
i = sb.lastIndexOf(s) // Returns position of last (rightmost) occurrence of s in sb.
Misc
i = sb.length() // length of the string s.
sb2 = sb.reverse()
Converting values in StringBuffer

An interesting aspect of the append() and insert() methods is that the parameter may be of any type. These methods are overloaded and will perform the default conversion for all primitive types and will call the toString() method for all objects.

Chaining calls in StringBuffer

Some StringBuffer methods return a StringBuffer value (eg, append(), insert(), ...). In fact, they return the same StringBuffer that was used in the call. This allows chaining of calls. Eg,
sb.append("x = ").append(x).append(", y = ").append(y);
Efficiency of StringBuffer compared to String

Because a StringBuffer object is mutable (it can be changed), there is no need to allocate a new object when modifications are desired. For example, consider a method which duplicates strings the requested number of times.

// Inefficient version using String.
public static String dupl(String s, int times) {
String result = s;
for (int i=1; i<times; i++) {
result = result + s;
}
return result;
}
If called to duplicate a string 100 times, it would build 99 new String objects, 98 of which it would immediately throw away! Creating new objects is not efficient. A better solution is to use StringBuffer.

// More efficient version using StringBuffer.
public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s);
for (int i=1; i<times; i++) {
result.append(s);
}
return result.toString();
}
This creates only two new objects, the StringBuffer and the final String that is returned. StringBuffer will automatically expand as needed. These expansions are costly however, so it would be better to create the StringBuffer the correct size from the start.

// Much more efficient version using StringBuffer.
public static String dupl(String s, int times) {
StringBuffer result = new StringBuffer(s.length() * times);
for (int i=0; i<times; i++) {
result.append(s);
}
return result.toString();
}
Because StringBuffer is created with the correct capacity, it will never have to expand. There is no constructor which allows both an initial capacity to be specifed and an initial string value. Therefore the loop has one extra iteration in it to give the correct number of repetitions.

Read more...

Friday, November 21, 2008

String Class & StringBuffer

Difference between StringBuffer and String Class :

A String object is immutable. A StringBuffer object is mutable. StringBuffer object is like a String object but can be modified. A string buffer is a sequence of characters but the length and content of the sequence can be changed through certain method calls. The principal operations on a StringBuffer are append() and insert() methods. The append() method adds characters at the end of the buffer and the insert() method adds the characters at a specified location.

The significant performance difference between these two classes is that StringBuffer is faster than String when performing simple concatenations. In String manipulation code, character strings are routinely concatenated. Every string buffer has a capacity. As long as the length of the character sequence does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If there is an overflow, the string buffer is automatically made larger.

Java provides the StringBuffer and String classes, and the String class is used to manipulate character strings that cannot be changed. Simply stated, objects of type String are read only and immutable. The StringBuffer class is used to represent characters that can be modified.
String str = new String ("Item"); str += "Found!!";
If you were to use StringBuffer to perform the same concatenation, you would need code that looks like this:
StringBuffer str = new StringBuffer ("Item");
str.append("Found!!");
Normally we assume that the first part of the code is more efficient because they think that the second part, which uses the append method for concatenation, is more costly than the first example, which uses the + operator to concatenate two String objects.
The + operator appears innocent, but the code generated produces some surprises. Using a StringBuffer for concatenation can in fact produce code that is significantly faster than using a String.

To trace that,we must see the generated bytecode from our two examples. The bytecode for the example using String looks like this:
0 new #7
3 dup
4 ldc #2
6 invokespecial #12
9 astore_1
10 new #8
13 dup14 aload_1
15 invokestatic #23
18 invokespecial #13
21 ldc #1
23 invokevirtual #15
26 invokevirtual #22
29 astore_1
The bytecode at locations 0 through 9 is executed for the first line of code, namely:
String str = new String("Stanford ");
Then, the bytecode at location 10 through 29 is executed for the concatenation:
str += "Lost!!";
The bytecode generated for the concatenation creates a StringBuffer object, then invokes its append method: the temporary StringBuffer object is created at location 10, and its append method is called at location 23. Because the String class is immutable, a StringBuffer must be used for concatenation.

After the concatenation is performed on the StringBuffer object, it must be converted back into a String. This is done withthe call to the toString method at location 26. This method creates a new String object from the temporary StringBuffer
object. The creation of this temporary StringBuffer object and its subsequent conversion back into a String object are veryexpensive.

In summary, the two lines of code above result in the creation of three objects:
A String object at location 0 A StringBuffer object at location 10 A String object at location 26

Now, let's look at the bytecode generated for the example using StringBuffer:
0 new #8
3 dup4 ldc #2
6 invokespecial #13
9 astore_110 aload_1
11 ldc #1
13 invokevirtual #
15 16 pop
The bytecode at locations 0 to 9 is executed for the first line of code:
StringBuffer str = new StringBuffer("Stanford ");
The bytecode at location 10 to 16 is then executed for the concatenation:
str.append("Lost!!");
Notice that, as is the case in the first example, this code invokes the append method of a StringBuffer object. Unlike the first example, however, there is no need to create a temporary StringBuffer and then convert it into a String object. This code creates only one object, the StringBuffer, at location 0.

In conclusion, StringBuffer concatenation is significantly faster than String concatenation. Obviously, StringBuffers should be used in this type of operation when possible. If the functionality of the String class is desired, consider using a StringBuffer for concatenation and then performing one conversion to String.

Read more...

Wednesday, November 19, 2008

Head First Servlets and JSP eBook

Head First Servlets and JSP

This book let you know the latest J2EE 1.4 versions of Servlets and JSPs. You can got for Sun Certified Web Component Developer (SCWCD) 1.4 exam with this one. Head First Servlets & JSP will show you how to write servlets and JSPs, what makes the Container tick, how to use the new JSP Expression Language (EL), and more.

Head First Servlets and JSP eBook

Read more...

Thursday, November 13, 2008

Hashtable Hashmap in Java

Difference between Java Hashtable and Java Hashmap

Hashmap can contains null values as the keys and as well as values.But Hashtable dose not allow null values as keys and values.

Hashtable is syncronized. Hashmap is not syncronized.

Hashtable is one of the original collections of Java but HashMap is added with Java 2, v1.2

HashMap does not guarantee that the order of the map will
remain constant over time.

Class HashMap implements Map interface. Hashtable is a concreate implementation of Dictionary class, is Legacy class, all legacy classes are synchronized.

Only one "null" key is allowed in HashMap but multiple "null" values are allowed in HashMap.

HashMap provides Collection views instead of direct support for iteration via Enumeration objects(as in Hashtable). Collection views greatly enhance the expressiveness of the interface.

HashMap allows you to iterate over keys, values, or key-value pairs whereas a Hashtable does not provide the option.

HashMap provides a safe way to remove entries in the midst of iteration, the older Hashtable
does not.

HashMap retrieval is not in order (random). HashTable provide ordered retrieval.

A hashmap is faster than hashtable.

HashMap has a more complex hashing algorithm then Hashtable. It takes the hash value from the key and then hashes it again (double hashing). This can improve the distribution of the keys and hence the performance of the Map. It does take more time to compute though. This is a useful feature as many hashCode implementations are not very good.

Read more...

Difference between Interface and Abstract Class

Abstract Class and Interfaces

A class implementing an interface must implement all of the methods defined in the interface, while a class extending an abstract class need not implement any of the methods defined in the abstract class.

Abstract class does not support Multiple Inheritance . Interface supports Multiple Inheriatance.

Abstract class can implemented some methods also. Interfaces cannot implement methods.

In Interface all member functions are public by default but in abstract class we can have private and protected members.

With abstract classes, you are grabbing away each class’s individuality. With Interfaces, you are merely extending each class’s functionality.

Interfaces are slow as it requires extra indirection to to find corresponding method in in the actual class. Abstract classes are fast compared to interfaces.

Interfaces can be best the choice when your program need some global variables.

Abstract class definition begins with the keyword "abstract" keyword followed by Class definition. An Interface definition begins with the keyword "interface".

Abstract classes are useful in a situation when some general methods should be implemented and specialization behavior should be implemented by subclasses. Interfaces are useful in a situation when all its properties need to be implemented by subclasses

The problem with an interface is, if you want to add a new feature (method) in its contract, then you MUST implement those method in all of the classes which implement that interface. However, in the case of an abstract class, the method can be simply implemented in the abstract class and the same can be called by its subclass

There is no difference between a fully abstract class (all methods declared as abstract and all fields are public static final) and an interface.

Neither Abstract classes nor Interface can be instantiated.

Read more...
Blog Widget by LinkWithin

JS-Kit Comments

  © Blogger template Newspaper III by Ourblogtemplates.com 2008

Back to TOP