Java Standard Edition
In the next few posts, I will write about how to perform an XSLT transformation using StAX APIs: Cursor API and Event Iterator API. TrAX (Transformations API for XML) is a Java API for performing XSLT transformations. In J2SE 1.5, there are three different ways to represent the source and the result of an XSLT transformation and they are: by XML stream source/result, by SAX events source/result, and by DOM tree source/result. In J2SE 1.6 an XSLT transformation is performed using a ...
To make your Java applications flexible, you might want to give properties that keep on changing in properties file. A property file is simply a text file that has key-value pairs relation. If you are thinking of writing your parser to read the property files, then think again. Java provides java.util.Properties class, that will help you deal with propery files. Property files comprise of key-value pairs in a file, where the key and value are separated by an equal ...
There are sometimes situations, when you need some look up mechanism. I will present few example in the next few posts. Let me present an scenario. We have an application which reads and writes to files on a file system. We have defined a error generating and tracking mechanism as well. Each error is assigned an error code and that code is thrown in case an error is encountered. To Interpret the code, we need to have some lookup mechanism. I defined a final class with ...
Final classes have a lot of benefits if used where required. I will present benefits of final classes in this post. Sometimes, you wish that no one can inherit from your class since its functionality is completed and should not be inherited. In that case, you may define your class as final, and then no class can inherit from it. The method of final class are also final. Final methods cannot be overridden in any sub class. There is also performance issues related to final class. A ...
A final variables in Java are can only be assigned once. Once they are assigned some value, they cannot be assigned some other value. If you have final class variable, they must be assigned to in the constructor of the class. An interesting thing is that the value of a final variable is not necessarily known at compile time. Consider the following example: Java Code: public class Sphere { public static final double PI = 3.141592653589793; ...
public class Sphere { public static final double PI = 3.141592653589793;
System's setProperties() method can be used to modify existing system's property. It takes a Properties object that has been initialized to contain the key/value pairs for the properties that you want to set. This method actually replaces the entire set of system properties with the new set Properties object. Lets review an example that creates a Properties object,initializes it from a file and then uses System.setProperties() to install the new Properties objects ...
Environment variables are used by operating systems to pass useful information (configurations) to the applications. Environment variables are key/value pairs very much like properties. The key and the value, both are strings. To set environment variables, please read system documentation as it varies from one operating system to another. In our Java applications, we use System.getEnv to retrieve environment variable values. If no argument is passed, getEnv will return ...
Guys, who are new to Java will find this post interesting. I will present for loop with examples. Use for loop when you know the maximum number of times you have to iterate in advance or backwards. Java Code: for ( int i=0; i { System.out.println( i ); } for ( int i=n-1; i>=0; i-- ) { System.out.println( i ); } You may increment 2 variables in the for loop as shown below: ...
for ( int i=0; i { System.out.println( i ); } for ( int i=n-1; i>=0; i-- ) { System.out.println( i ); }
There are different ways to span an array. I will present few of them here. This simplest way is to use a for loop as shown: Java Code: String[] stuff = new String[ 10 ); for ( int i=0; i { String s = stuff[i]; System.out.println( s ); } Java 1.5 introduces a new for of for loop and can also be used to span an array. Java Code: String[] stuff = new String[ 10 ); ... for ( String s : ...
String[] stuff = new String[ 10 ); for ( int i=0; i { String s = stuff[i]; System.out.println( s ); }
String[] stuff = new String[ 10 ); ... for ( String s :
Spanning enum in Java 1.5 is easy using for loop. Java Code: enum Breed { DALMATIAN, LABRADOR, DACHSHUND } ... for ( Breed dog : Breed.values() ) { System.out.println( dog ); } Let me show hot to span an enumeration. Java Code: for ( Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); System.out.println( ...
enum Breed { DALMATIAN, LABRADOR, DACHSHUND } ... for ( Breed dog : Breed.values() ) { System.out.println( dog ); }
for ( Enumeration e = props.propertyNames(); e.hasMoreElements(); ) { String key = (String) e.nextElement(); System.out.println(
You may use Iterator to remove elements from a List (ArrayList, LinkedList etc.) efficiently. You must be aware that you cannot remove elements from a List using for:each. Other approach is to get and them remove the elements which is not that efficient. Java Code: for ( Iterator iter = items.iterator(); iter.hasNext(); ) { Item item = iter.next(); if ( item.isUnwanted() ) { // remove from underlying Collection ...
for ( Iterator iter = items.iterator(); iter.hasNext(); ) { Item item = iter.next(); if ( item.isUnwanted() ) { // remove from underlying Collection
Subtyping is very important in Java. One type is said to be subtype of other if they are related by an extend or implements clause. For instance: Integer is a subtype of Number Double is a subtype of Number ArrayList is a subtype of List List is a subtype of Collection Collection is a subtype of Iterable Subtyping principle says that a variable of type A can be assigned a value of any subtype of A and methods ...
Each computer on internet is called a node or a host. Each host has unique address called Internet Protocol (IP) address. IP addresses are not easy for the humans to remember therefore, Domain Name System (DNS) was introduced. DNS assigns a human understandable name to IP addresses. InetAddress class represents IP addresses which can be useful in networking environment. Let see what we can o with this one: Following code finds and prints the IP address ...
AbstractList implements Collection and List interfaces. ArrayList, Vector and AbstractSequentialList extends from AbstractList. Actually AbstractList contains implementation of List interface for random access. If you want to create a list that should not be modified, then you should extend this class. But then you have to provide implementations for the get(int index) and size() methods. Java Code: public class MyList extends AbstractList { @Override ...
public class MyList extends AbstractList { @Override
Like Vectors and ArrayLists, LinkedList can also be made to deal with only one type of objects. Lets see how to do that. Java Code: LinkedList ll = new LinkedList(); ll.add("Str1"); ll.add("Str2"); ll.addFirst("Str3"); The LinkedList named ll can only store String objects. This is very useful and provides more control over collection. You are always sure that you will get objects of a specific type from the list. ...
LinkedList ll = new LinkedList(); ll.add("Str1"); ll.add("Str2"); ll.addFirst("Str3");
Stack is a special type of Vector as it extends Vector class. Stack works on last-in-first-out (LIFO) principle. Stack class provides 5 operations to treat the vector in a special way. Java Code: boolean empty() Object peek() Object pop() Object push(Object item) int search(Object o) Lets try push and pop operation on a Stack Java Code: Stack newStack = new Stack(); newStack.push("10"); newStack.push("20"); ...
boolean empty() Object peek() Object pop() Object push(Object item) int search(Object o)
Stack newStack = new Stack(); newStack.push("10"); newStack.push("20");
DateFormat class is a very useful class included in java.text package that can be used to display date in different formats. Following example will show you how to use it with Date object in meaningful way. Java Code: Date now = new Date(); DateFormat df = DateFormat.getDateInstance(); DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM); DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG); ...
Date now = new Date(); DateFormat df = DateFormat.getDateInstance(); DateFormat df1 = DateFormat.getDateInstance(DateFormat.SHORT); DateFormat df2 = DateFormat.getDateInstance(DateFormat.MEDIUM); DateFormat df3 = DateFormat.getDateInstance(DateFormat.LONG);
log4j.properties file is a configuration file (not in XML format). If you have a stand alone application, then log4j.properties should be in the directory where you issued the java command. In case of web application (JSP/Servlet), place log4j.properties at /WEB-INF/classes/. A sample properties file is given below: log4j.appender.stdout=org.apache.log4j.ConsoleAppe nder log4j.appender.stdout.Target=System.out log4j.appender.stdout.layout=org.apache.log4j.Patt ...
Map is an object that stores key/volume pairs. Given a key, you can find its value. Keys must be unique, but values may be duplicated. The HashMap class provides the primary implementation of the map interface. The HashMap class uses a hash table to implementation of the map interface. This allows the execution time of basic operations, such as get() and put() to be constant. This code shows the use of HaspMap. In this program HashMap maps the names to account balances. ...
I will present an an example that will show the use of following uniary operators: Unary minus operator, Increment operator, Decrement operator, Logical compliment operator Unary plus operator (+) indicates positive value. This (+) operator is used to perform a type conversion operation on an operand. The type of the operand must be an arithmetic data type i.e. if a value of the integer operand is negative then that value can be produced as a positively applying unary plus (+) operator. ...
Flushing outputstreams has its own importance. You will realize this when working on socket programming. If you do not flush the output stream every time you write something on it, the data may not actually get written out to the socket, and the two programs will keep on waiting for the data forever. You can just call flush() after you write something important: Java Code: // OutputStream out; // byte[] data out.write(data); out.flush(); ...
// OutputStream out; // byte[] data out.write(data); out.flush();
You can load GIF, JPEG, and (in SDK 1.3) PNG images using Toolkit's getImage() method: Java Code: Image i = Toolkit.getDefaultToolkit().getImage("car.png"); However, Images use lazy data loading, so the data for the image won't start to be loaded until you try to display the image. You can use a MediaTracker to force the data to load, but it's a pain in the butt. An easier solution is to use one of ImageIcon's constructors, which does ...
Image i = Toolkit.getDefaultToolkit().getImage("car.png");
You will learn about deprecated annotation in this post. Deprecated is a standard annotation and it’s a marker annotation. We use Deprecated to annotate a method that shouldn't be used anymore. Note: Deprecated should be placed on the same line as the method being deprecated. Java Code: package com.domian.a.test; public class DeprecatedClass { @Deprecated public void doSomething() { // some code } ...
package com.domian.a.test; public class DeprecatedClass { @Deprecated public void doSomething() { // some code }
I will present an example that will show start, stop, suspend, and resume threads. It uses the Runnable interface. Such threads are useful for things like controlling animation sequences or repeatedly playing audio samples. This example uses a thread that counts and prints a string every second. The thread starts when the applet is initialized. It continues to run until the user leaves the page. If the user returns to the page, the thread continues from where it left off. This allows ...
LinkedList has a benefit over ArrayList/Vector when it comes to insert and delete operation. LinkedLists can add and delete any element in the list very efficiently because only the node pointers are to be updated. While talking about the memory consumption, each element/object in a LinkedList takes a bit more memory as compared to ArrayList/Vector because of the pointers involved. ArrayList, Vector and LinkedList all have their importance. The important thing is to use them ...
Since ArrayList implements the Serializable interface, therefore ArrayList can be serialized which means it can be persisted on the disk. Following example does exactly that. Code example follows: Java Code: ArrayList arrayList = new ArrayList(); arrayList.add("Mars"); arrayList.add("Satrun"); arrayList.add("Pluto"); FileOutputStream f_out = new FileOutputStream("C:\arraylist.data"); ...
ArrayList arrayList = new ArrayList(); arrayList.add("Mars"); arrayList.add("Satrun"); arrayList.add("Pluto"); FileOutputStream f_out = new FileOutputStream("C:\arraylist.data");
IO is always a performance issue. I will write about this in this post. IO is a performance issue but now its really simple and efficient to do IO related tasks. Always use buffering if you need performance. Because if you directly use FileInputStream, JVM is going to issue file read system call everytime you read a byte of data. In case of buffering, whole buffer is read in one go and only if there's no data in the buffer, JVM issues a system call to read the disk.
One should try avoiding null pointer exception. In case of coding an application that needs high degree of reliability, don't take risks. I will present an example. Check the following piece of code. Java Code: private boolean isNullString(String string) { return (string.equals("")); } It seems a normal piece of code. But still there's a hidden trap here. What is the string which is passed is null? So try to rephrase ...
private boolean isNullString(String string) { return (string.equals("")); }
I will present few important methods of HashMap class in this post. The most useful methods are: get and put. get(Object key) returns the value associated with specified key. It returns null if there is no value for this key. put(K key, V value) associates the specified value with the specified key. Other useful methods are: containsKey(Object key) - (boolean) returns true if this map contains a value for the specified key ...
Java 5 introduces StringBuilder which implements Serializable and CharSequence interfaces. It represents a mutable sequence of characters. StringBuilder is an API compatible with StringBuffer, but with no guarantee of synchronization. Following are the available constructors: Java Code: StringBuilder() StringBuilder(CharSequence seq) StringBuilder(int capacity) StringBuilder(String str) This can be used in place of StringBuffer ...
StringBuilder() StringBuilder(CharSequence seq) StringBuilder(int capacity) StringBuilder(String str)
Size Reduced for Images in PDF &...
05-15-2013, 05:53 PM in Java Software