View RSS Feed

My Java Tips

  1. Javap

    by , 05-24-2011 at 02:58 PM (My Java Tips)
    Javap is shiped with JDK and it really very useful when you want to see what your compiler is doing to your code. It generates source code from a compiled class file.

    Javap is a utility provided in Java Development Kit (JDK) that can be used to improve source code. this is done by generating source code from compiled code and seeing how our code was treated by the Compiler. Later code improvements can be made.

    A very interesting example can be to see how source code ...
  2. ArrayStoreException

    by , 05-24-2011 at 02:48 PM (My Java Tips)
    java.lang.ArrayStoreException is a runtimeException and is thrown when we try to store wrong type of object into an array of objects.


    Java Code:
    ArrayStoreException(String s)
    For example: Storing an Integer object in a Strign array will cause this exception.

    Java Code:
    Object x[] = new String[3];
    x[0] = new Integer(0);
    Since its a runtime exception, compiler won't ...
    Java SE
  3. Finalize

    by , 05-24-2011 at 02:46 PM (My Java Tips)
    All Java classes inherits the finalize() method from java.lang.Object and this method is called by the garbage collector when it determines no more references to the object exist.

    The finalize method performs no actions but it may be overridden by any class. It is overridden to clean-up non-Java resources ie closing a file, closing a connection etc. In overridding finalize() it is a good programming practice to use a try-catch-finally statement and to always call super.finalize(). ...
    Tags: finalize Add / Edit Tags
    Java SE
  4. Writing a file from JSP

    by , 05-24-2011 at 02:45 PM (My Java Tips)
    You may want to write a file from JSP page. For example, user fills a form and you want to persist the details on a text file on server. Now you need to know how to write text file from JSP.

    Remember, always give the path from root. In the given snippet, nameOfTextFile contains the file path. We will use FileOutputStream to write to the file.

    Java Code:
    <%@ page import="*"  %>
    String str = "form data goes here";
  5. Reading files from JSP

    by , 05-24-2011 at 02:44 PM (My Java Tips)
    Working in Servlets/JSP, you might have encountered The javax.servlet.ServletContext API. It provides methods to access resources in general.

    • getResource(String resource): will returns a URL for the resource in the web application.
    • getResourceAsStream(String resource): will returns an InpuStream for the resource in the web application
    • getResourcePaths(String path): will a directory-like listing of all the paths to resources within the web application.

    An example ...
  6. Using Java Beans in JSP

    by , 05-24-2011 at 02:42 PM (My Java Tips)
    JavaBeans are classes written in the Java programming language conforming to a particular convention.

    Consider the scenario: you are writing a JSP and you wish to write pure Java code in it. You may use scriptlets within JSP.

    Java Code:
    // Java code goes here
    Using scriptlets means that your JSP will contains business logic as well which is not a good design approach. Ideally you would like to keep business logic separately ...
  7. Fetching parameters from web.xml

    by , 05-24-2011 at 02:30 PM (My Java Tips)
    The file named web.xml is part of your web applications. You may use it for different purpose. Sometimes you wish to define some parameters for your web application in it. Obviously, you need to use this in your application. I will briefly tell you how to do this.

    At first, let me give you an example. We have a web application that needs to send its id and license code to some authentication server before doing some business operation. The id and license code are static and you may ...

    Updated 05-24-2011 at 02:34 PM by Java Tip

    JSP , Servlet , XML
  8. Stack traces

    by , 05-24-2011 at 02:28 PM (My Java Tips)
    You must have seen stack traces in console window of your Eclipse. Good this is that Java stack traces in the console appear with hyperlinks. This means you can click these to go to the referred place in the code. This helps in problem identification.

    Here is how is works: place the mouse over a line in a stack trace and the pointer changes to the hand. Pres the mouse button and associated Java source file will be opened and the cursor will be placed at the corresponding line. Pressing ...
    Tags: stack Add / Edit Tags
  9. Running code with compile errors

    by , 05-24-2011 at 02:26 PM (My Java Tips)
    While coding in Java using Eclipse, you might have experienced situations where your Java class has some compile errors but stilly you want to run it. The reason might be that the problematic area might be invoked in your execution. What ever is the reason, Ill briefly explain how to execute code with compile errors.

    In Eclipse, you can run and debug code that did not compile cleanly. You cannot do this using command prompt. If line of code with compile error is executed, following ...
    Tags: debug, debugger Add / Edit Tags
  10. Debugger: Code Assist

    by , 05-24-2011 at 02:25 PM (My Java Tips)
    You might have used code assistant while coding in Eclipse. Its really useful and saves time for trivial stuff. Most of us think that code assistant is only available in code writing context. That’s not right.

    Code assistant is available in debug mode at following:

    • When entering a breakpoint condition,
    • In the Details pane of the Variables & Expressions view,
    • When entering a Detail Formatter code snippet,
    • When entering a Logical Structure code snippet,
    • When
  11. Scrapbook in Eclipse

    by , 05-24-2011 at 02:23 PM (My Java Tips)
    Consider the following scenario: you are working on a project with client specific APIs .You need to test some API methods before you put them in your real code. For that, you might consider a separate test workspace or defining a new test class in your running workspace. What about scrapbook page? Ever heard of it?

    Eclipse provide scrapbook pages to test write test code for experimental purposes. It is easier to use a Java scrapbook page than create a new class. A scrapbook page ...
    Tags: scrapbook Add / Edit Tags
  12. Setting watches in Eclipse

    by , 05-21-2011 at 11:55 PM (My Java Tips)
    Watch point is a special type of break point that suspends execution when specified filed is accessed or modified.

    Setting a watchpoint is simple. First select a field in the Outline view and choose Toggle Watchpoint from its context menu.

    Name:  watches.jpg
Views: 710
Size:  22.9 KB

    Now you have to configure this watchpoint. This is done by selecting the watchpoint in the view and choose Properties from its context menu. Don’t forget to configure the important properties ...
  13. Motivation for unit tests

    by , 05-21-2011 at 11:53 PM (My Java Tips)
    Unit tests are essential part of software development especially. In complex and large softwares, introducing new changes in very tricky as it can break some other part. If you have clearly defined test cases, then you can check the working of newly introduced change and make sure it works as expected.

    Unit tests are small snippets of code that are written to check a particular method or class. With unit tests in place, when a change is made to the code we can simply run all the tests ...
    Tags: unit test Add / Edit Tags
  14. Importing junit.jar

    by , 05-21-2011 at 11:52 PM (My Java Tips)
    Before you start writing unit tests, you must import junit.jar, so we have access to the testing framework. Follow these steps to import the required jar:

    • Right-click on the project name, and choose Properties.
    • In the tree on the left, select Java Build Path.
    • Next, choose Add External JARs… and browse to find junit.jar.

    It will be located in "<eclipsedir>\plugins\org.junit_<version number>\junit.jar".

    Once you successfully ...
    Tags: jar Add / Edit Tags
    Eclipse , JUnit
  15. Wrapping Strings

    by , 05-21-2011 at 11:50 PM (My Java Tips)
    Its always useful to wrap strings if they are too long. This provides better readability. Eclipse has support for this.

    String literals can wrapped when you edit them. Place your cursor at the point of literal where you want to wrap and press Enter. For example:

    Java Code:
    String message= "Java is fun to learn and it sure is a popular programming language.";
    I kept the cursor at ‘sure’ and pressed enter key. The String was changed to: ...
    Tags: string Add / Edit Tags
  16. Safe JAR file migration in Eclipse

    by , 05-21-2011 at 11:48 PM (My Java Tips)
    Its always a good idea to include refactoring information into the JAR file when you are exporting it from Eclipse. Eclipse’s JAR Export Wizard offers this option.

    Here is how it works:

    • File > Export
    • Select JAR file
    • Select: Export refactorings for checked projects

    This is very useful because then all the clients that are using older version of JAR will be able to migrate an old version of the JAR file to a new one using the Refactor > Migrate ...
    Tags: jar, refactoring Add / Edit Tags
  17. Searching methods with some return type in Eclipse

    by , 05-21-2011 at 11:47 PM (My Java Tips)
    Working on a project, I need to search all the methods defined in my workspace or in a package or in a class with a specific return type. Eclipse search feature (ctrl + h) provides support for this. We all have used eclipse search window a lot of times but many of us don’t know how to really use it to great affect.

    To search the methods with a specific return type, type

    Java Code:
    * String
    is used as wildcard for method name and String is the return ...
  18. Mark occurrences in Eclipse

    by , 05-21-2011 at 11:44 PM (My Java Tips)
    Mark occurrences is a nice feature in Eclipse. It simply marks/highlights all the occurrences of a variable, method or a type.

    This can be done by clicking ‘Mark Occurrences’ icon on the menu bar. If you like to use short cut keys, then use Alt+Shift+O. If you select methods return type, and mark occurrences is enabled, all the method exit points will be highlighted.

    Name:  mark-occurances.jpg
Views: 529
Size:  21.6 KB

    You may also select a super class or interface and then ...
  19. Hot Code Replace in Eclipse

    by , 05-21-2011 at 11:41 PM (My Java Tips)
    Ever heard of hot code replace in reference to debugging in Eclipse? Well, its sure is a powerful and useful feature. It enables you to change code while debugging. It simply means that you may change the code in debug mode and see its affect.

    Hot code replace is supported in 1.4 or higher VM. There are some changes like adding or deleting methods, class variables or inner classes which cannot be hot swapped. This depend on the support provided by a particular VM. This might also ...
  20. Threads and Monitors in Eclipse

    by , 05-21-2011 at 11:40 PM (My Java Tips)
    When you are working with multi threading where resources are locked and released, deadlock prevention becomes very important. To prevent starvation, proper lock and release mechanism has to be defined/implemented.

    Eclipse’s debugger provides monitor information in the debug view. To use it, use the Show Monitors action which can be found in the Debug view drop down menu. It will show which threads are holding locks and which are waiting to acquire locks. The threads in red indicated ...
  21. SessionFactory Monitoring

    by , 05-21-2011 at 11:37 PM (My Java Tips)
    There are few ways of accessing SessionFactory metrics. One of them is to use JMX to publish metrics. For that you need to enable the StatisticsService MBean. A single MBean can be enabled for your SessionFactory or one per factory.

    Following snippet presents a configuration example:

    Java Code:
    // MBean service registration for a specific SessionFactory
    Hashtable tb = new Hashtable();
    tb.put("type", "statistics");
  22. Hibernate logging

    by , 05-21-2011 at 11:36 PM (My Java Tips)
    Hibernate logs various events using Apache commons-logging. Hibernate logs are very interesting to read if you want to do some troubleshooting or performance improvement. Hibernate uses commons-logging service for logging. It actually sends the log to either Log4j or to JDK1.4 logging.

    If you want hibernate to log using Log4j, then put log4j.jar into class path along with Since log4j has almost become a standard these days, I would advice using that.
    Hibernate ...
    Tags: hql, jdbc, log4j, logging, sql Add / Edit Tags
  23. Defining fetch strategy

    by , 05-21-2011 at 11:33 PM (My Java Tips)
    To tune fetch strategy, you have various options. Which to choose depends on the scenario. You may define the fetch strategy in the mapping document. For instance:

    XML Code:
    <set name="permissions" 
        <key column="userId"/>
        <one-to-many class="Permission"/>
    <many-to-one name="mother" class="Cat" fetch="join"/>
    Tags: hql Add / Edit Tags
  24. Remote Debugging

    by , 05-21-2011 at 11:31 PM (My Java Tips)
    Ever wanted to launch a Java program from a network computer and debug it from the workstation running the Java platform? Example scenario is that you have an a J2EE application deployed on a dedicated server and you need to do debugging on you machine. This can be done if Java VM that supports this feature.

    To do this, launch the program in debug mode on the remote machine. It means that the program on server will wait for a connection from your debugger. Now start the debugger ...
    Java EE , JBoss
  25. Lazy select fetching for collections

    by , 05-21-2011 at 11:30 PM (My Java Tips)
    Hibernate uses lazy select fetching for collections by default. This behavior makes sense and is used as it is unless you really want to do something different for some reason.

    Hibernate will use the batch fetch optimization for lazy fetching if you set hibernate.default_batch_fetch_size. There is a problem with lazy fetching that should be considered. Remember, you should never access to a lazy association outside of the context of an open Hibernate session otherwise exceptions ...
  26. Sharing setUp() and tearDown() code for all tests - I

    by , 05-21-2011 at 11:29 PM (My Java Tips)
    You may wish to share the code written in setUp() and tearDown() methods of your JUnit tests. This clearly will indicate that you have excessive coupling in your design. Coupling is not bad always but if more tests share the same test fixture state, then this indicates that the classes under test have some undesirable dependencies.

    You may wish to remove these dependencies but its another stories. As I said, coupling or dependencies are not always bad. But if you wish to keep coupling ...
    Tags: setup, teardown Add / Edit Tags
  27. Sharing setUp() and tearDown() code for all tests - II

    by , 05-21-2011 at 11:28 PM (My Java Tips)
    This post presents an example that shows how to use @BeforeClass and @AfterClass annotation.

    Java Code:
        public class SimpleTest {
            private Collection collection;
            public static void oneTimeSetUp() {
                // one-time initialization code        
            public static void oneTimeTearDown() {
                // one-time cleanup code
    Tags: setup, teardown Add / Edit Tags
  28. Running JUnit using Ant

    by , 05-21-2011 at 11:26 PM (My Java Tips)
    You may want to define build script using ant for your application. I will write about how to create ant script to run ant.

    Step 1: define ant properties

    XML Code:
    <property name="src" value="./src" />
    <property name="lib" value="./lib" />
    <property name="classes" value="./classes" />
    <property name="" value="" />
    Tags: ant Add / Edit Tags
  29. java.lang.NoClassDefFound Error: org/apache/log4j/Layout

    by , 05-21-2011 at 11:22 PM (My Java Tips)
    You might have seen the following exception:

    Java Code:
    java.lang.NoClassDefFoundError: org/apache/log4j/*
    It may mean that log4j is not in your class path or you are using some outdated version of log4j.

    Get latest copy of log4j and put it in your class path. If JSP caused this, then put the log4j jar into WEB-INF/lib directory. Restart your application server (say Tomcat) and it should work now.

    Get latest version of log4j from:
    Apache log4j 1.2 - Download Apache log4j 1.2 ...
  30. JNDI - Introduction

    by , 05-21-2011 at 11:20 PM (My Java Tips)
    JNDI is a standard Java API that comes with JDK 1.3 and higher. It provides a common interface to a variety of existing naming services for example DNS, LDAP, Active Directory, RMI registry, COS registry, NIS, and file systems.

    The JNDI API is divided logically into a client API and service provider interface. Client API is used to access naming services and a SPI allows the user to create JNDI implementations for naming services.
    The naming service providers must implement ...
    Tags: jndi Add / Edit Tags
    Java EE , JBoss
Page 14 of 15 FirstFirst ... 412131415 LastLast