View RSS Feed

My Java Tips

  1. Implementing LIFO principle

    by , 11-03-2011 at 12:04 PM (My Java Tips)
    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");
    ...
    Categories
    Java SE
  2. DateFormat Class

    by , 11-03-2011 at 12:00 PM (My Java Tips)
    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);
    ...
    Categories
    Java SE
  3. XPath VS DOM

    by , 11-03-2011 at 11:55 AM (My Java Tips)
    We use Structured Query Language (SQL) for querying certain kinds of relational databases. Other less familiar query languages include Object Query Language (OQL) and XQuery. XPath, a query language used for querying XML documents.


    Following XPath query finds the titles of all the books in a document whose author is Neal Stephenson:

    //book[author="Neal Stephenson"]/title

    Following example uses DOM to find all the title elements of books by Neal ...
    Categories
    XML
  4. JAXP/XPath example

    by , 11-03-2011 at 11:50 AM (My Java Tips)
    I will present an example that will search a XML file and then prints out the titles of all the books it finds.


    I will use following books.xml in the example.


    <inventory>
    <book year="2000">

    <author>Neal Stephenson</author>
    <publisher>Spectra</publisher>
    <isbn>0553380958</isbn>
    <price>14.95</price>
    </book>
    ...
    Categories
    XML
  5. View for warnings and problems

    by , 11-03-2011 at 11:40 AM (My Java Tips)
    Eclipse has a view that shows all the warnings and errors of the projects in your workspace. I will write about that in this post.


    While working on Java projects involving lot of packages and classes, you want a view to show you all the warnings and errors in your work. This will present all wrong stuff in a single view and you donít need to search for the errors manually. Eclipse provides a view called ĎProblemsí that serves the purpose.

    Name:  viewprob.PNG
Views: 168
Size:  17.9 KB ...

    Updated 11-03-2011 at 11:42 AM by Java Tip

    Categories
    Eclipse
  6. log4j.properties file

    by , 11-03-2011 at 11:34 AM (My Java Tips)
    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 ...
    Categories
    XML , Java SE
  7. JSF - Validators and Converters

    by , 11-02-2011 at 06:21 PM (My Java Tips)
    I will introduce JSF calidators and converters in this post.



    Converters are plug-in for conversions.

    <h:input_text valueref="testingBean.today" convertor="DateTime/">
    </h:input_text>

    Validators are used to perform correctness checks on UIInput values.

    <h:input_text valueref="testingBean.today&lt;br"> </h:input_text>
    Categories
    Frameworks
  8. Sample JSF page

    by , 11-02-2011 at 06:17 PM (My Java Tips)
    Creating JSF page is simple and easy. There are few things to remember which I will list down.


    The page must include JSF tag library and HTML and core tags.

    All the JSF tags must enclosed between a set of view tag.
    Use JSF form and form component tags.
    Use h:input_text and not input type=text
    Use h:command_button and not input type=submit

    A page may include validators and event listeners on any form components

    For example: ...

    Updated 11-02-2011 at 06:19 PM by Java Tip

    Categories
    Frameworks
  9. Tunning Eclipse

    by , 11-02-2011 at 06:15 PM (My Java Tips)
    Sometimes you might feel that your Eclipse is sluggish and performance tuning is required. I will address this issue in this post.


    Implement the following for better performance:

    - Increase your min/max memory settings from 40/256 to 256/512 or higher. You might have to experiment with the min/max setting but increasing the initial memory heap to 128 when Eclipse starts should help.

    - Disabling the code folding feature also helps. To disable this, go ...
    Categories
    Eclipse
  10. Resolving OutOfMemoryExceptions

    by , 11-02-2011 at 06:13 PM (My Java Tips)
    You might have encountered OutOfMemoryException using Eclipse. This post is about solving this issue.


    OutOfMemoryException is caused by too little heap space for virtual machine. Adjusting the maximum heap space with something like -vmargs -Xmx256m works. This gives your Java apps more space to run and this always helps performance. There are situations where even with an enormous heap size you can still end up with OutOfMemoryException. This means that your VM is not running out ...
    Categories
    Eclipse
  11. Example - HashMap

    by , 11-02-2011 at 06:11 PM (My Java Tips)
    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.
    ...
    Categories
    Java SE
  12. Unary operators

    by , 11-02-2011 at 06:09 PM (My Java Tips)
    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. ...
    Categories
    Java SE
  13. Flushing streams

    by , 11-02-2011 at 06:07 PM (My Java Tips)
    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();
    ...
    Categories
    Java SE
  14. Loading images

    by , 11-02-2011 at 06:05 PM (My Java Tips)
    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 ...
    Categories
    Java SE
  15. Go to Line

    by , 11-02-2011 at 06:00 PM (My Java Tips)
    Jumping to a specific line is very useful feature. Ecplise provides line nos along the lines of code and you may just to the required line using 'Go to Line' feature.

    Name:  jump-line.PNG
Views: 134
Size:  26.4 KB
    Ctrl + L, enter line number and you are taken to the required line. Of course if the stack trace is in the Eclipse console, you can just click the hyperlink. But if itís in a log file or something, just use this shortcut to go to the line in a sec.

    Name:  jump-line.PNG
Views: 134
Size:  26.4 KB ...
    Categories
    Eclipse
  16. Go to other open editors

    by , 11-02-2011 at 05:56 PM (My Java Tips)
    You can have a lot of files open your Eclipse IDE and may want to switch the file while working. Eclipse provides a fast way of dong that.


    You can cycle through the editors using Ctrl + F6 but its not that useful since the keys are requires you to keep the Ctrl key down. Better way is to use Ctrl + E and then either use the arrow buttons, or type the name of the file youíre editing.

    Name:  editorswitch.PNG
Views: 126
Size:  57.6 KB
    I hope you will find this useful.
    Categories
    Eclipse
  17. Open a type

    by , 11-01-2011 at 06:26 PM (My Java Tips)
    Opening a type for example: a class, an interface) without clicking through interminable list of packages really is a handy feature. The shortcut key combination is: Ctrl + Shift + T.


    If what you want is a Java type, this shortcut will do the trick. Unlike the previous shortcut, this even works when you donít have the Java source file in your workspace for instance: when youíre opening a type from the JDK).

    Name:  typeopen.PNG
Views: 130
Size:  77.8 KB


    try this. ...

    Updated 11-01-2011 at 06:29 PM by Java Tip

    Categories
    Eclipse
  18. Quering an XML document with a fixed XPath expression

    by , 11-01-2011 at 06:22 PM (My Java Tips)
    I will present a complete program to query an XML document with a fixed XPath expression.


    The method can throw several exceptions that must be declared in try- catch blocks. Do proper exception handling.

    Java Code:
    import java.io.IOException;
    import org.w3c.dom.*;
    import org.xml.sax.SAXException;
    import javax.xml.parsers.*;
    import javax.xml.xpath.*;
    
    public class XPathExample {
    
      public static void main(String[]
    ...
    Categories
    XML
  19. Binding a single namespace

    by , 11-01-2011 at 06:16 PM (My Java Tips)
    The XPath expression that finds the titles of all of Laiq's books will be //pre:book[pre:author="Laiq"]/pre:title/text(). However, you have to map the prefix pre to the URI.



    It's a little strange that the Namespace Context interface doesn't have a default implementation in the Java software development kit (JDK) or JAXP, but it doesn't. However, it's not hard to implement. Following simple implementation is for one namespace. You should map the xml prefix as well. ...
    Categories
    XML
  20. Java Naming and Directory Interface

    by , 11-01-2011 at 06:14 PM (My Java Tips)
    I will introduce Java Naming and Directory Interface (JNDI) in this post. Its an API for accessing different kinds of naming and directory services.


    Many people believe that JNDI is specific to a particular naming or directory service, which is not correct. JNDI can be used to access many different kinds of systems including file systems; distributed objects systems (CORBA, Java RMI, and EJB) and directory services like LDAP, Novell NetWare, and NIS+.

    JNDI is similar ...
    Categories
    JBoss
  21. JNDI lookup with a corbaname URL

    by , 11-01-2011 at 06:09 PM (My Java Tips)
    A corbaname can be useful at times as a lookup name. If, for example, the target object is not a member of the federated name space and cannot be located with a qualifiied name, a corbaname can be a convenient way to look up the object.


    A lookup with a corbaname URL follows.

    Java Code:
    // Get the initial context as shown in a previous example.
    ...
    // Look up the home interface using a corbaname URL.
    try {
       java.lang.Object ejbHome = initialContext.lookup(
    ...
    Categories
    JBoss
  22. JNDI - Fixed qualified names

    by , 11-01-2011 at 06:08 PM (My Java Tips)
    If the target object has a cell-scoped fixed name defined for it, you can use its qualified form instead of the topology-based qualified name. Even though the topology-based name works, the fixed name does not change with the specific cell topology or with the movement of the target object to a different server.




    An example lookup with a qualified fixed name follows.


    Java Code:
    // Get the initial context as shown in a previous example.
    // Using the
    ...
    Categories
    JBoss
  23. JNDI - Fixed qualified names

    by , 11-01-2011 at 06:07 PM (My Java Tips)
    If the target object has a cell-scoped fixed name defined for it, you can use its qualified form instead of the topology-based qualified name. Even though the topology-based name works, the fixed name does not change with the specific cell topology or with the movement of the target object to a different server.




    An example lookup with a qualified fixed name follows.


    Java Code:
    // Get the initial context as shown in a previous example.
    // Using the
    ...
    Categories
    JBoss
  24. Deprecated annotation

    by , 11-01-2011 at 06:04 PM (My Java Tips)
    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
      }
    ...
    Categories
    Java SE
  25. Override annotation

    by , 11-01-2011 at 06:02 PM (My Java Tips)
    Tiger provides many built-in annotation types and Override is one of them. Override should be used only on methods to indicate that the annotated method is overriding a method in a superclass. An example is presented below:





    Java Code:
    package com.domian.a.test;
    
    public class OverrideTester {
    
      public OverrideTester() { }
    
      @Override
      public String toString() {
        return super.toString() + " [Override Tester
    ...
    Categories
    Annotations
  26. Simple Thread Examples

    by , 11-01-2011 at 05:58 PM (My Java Tips)
    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 ...
    Categories
    Java SE
  27. Adding MIME types to JBOSS

    by , 11-01-2011 at 05:51 PM (My Java Tips)
    Consider that you have an application deployed on JBOSS application server. You offer different files in your application that can be opened or downloaded. But someone complains that the web application shows code of the file imbedded in the web page instead of opening or downloading it. What problem can there be?


    Actually you have to tell your JBOSS application server of the supported files. For this, you need to add an entry in web.xml. For instance:


    <mime-mapping> ...

    Updated 11-01-2011 at 05:54 PM by Java Tip

    Categories
    JBoss , XML
  28. LinkedList - insertion/deletion

    by , 11-01-2011 at 05:48 PM (My Java Tips)
    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 ...
    Categories
    Java SE
  29. Writing/Retriving ArrayList to disk

    by , 11-01-2011 at 05:31 PM (My Java Tips)
    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");
    ...
    Categories
    Java SE
  30. Java IO tasks

    by , 11-01-2011 at 05:28 PM (My Java Tips)
    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.
    Categories
    Java SE , Performance
Page 11 of 15 FirstFirst ... 910111213 ... LastLast