Showing posts with label tips. Show all posts
Showing posts with label tips. Show all posts

03 October 2010

Tip for Today

You can write code as anonymous

this code you may writing like....

MyClass mc1 = new MyClass();
mc1.justShow();

you want to just call method of you class need to further requirement. you can write code like this

(new MyClass()).justShow();

01 October 2010

Java Top Tips - 1

1. Flush Streams

This might seem obvious, but it repeatedly kicks my butt. The problem usually appears with two programs on either side of a network socket having some kind of conversation. If you don't flush the output stream every time you say something, the data may not actually get written out to the socket, and the two programs will sit patiently, waiting forever for something to happen.

Typically, you can just call flush() after you write something important:

      // OutputStream out;
      // byte[] data
      out.write(data);
      out.flush();
If you're writing text data, you might use a PrintWriter for output. PrintWriter has a special constructor that lets you specify if the stream should be flushed after every newline:
     PrintWriter out = new PrintWriter(rawOut, true);
A PrintWriter created in this way will automatically flush itself whenever you write a line of text.
==================================================================

2. Use Double Equals for Comparisons

This is a holdover from C. It made its way into C++, and then Java used a lot of C++ syntax. The bug goes like this: Somewhere, you accidentally type a single equals sign instead of a double one when examining a boolean value:

      boolean b = false;
      if (b = true) {
            // Always gets executed.
      }

 
Instead of performing a comparison, as you'd hoped, you're actually assigning true to the variable b. This assignment has an overall value of true, so the if always succeeds.
Some people suggest reversing the order of the comparison, so the literal value always comes first. This generates a compile-time error for if (true = b), so you'll figure out what's wrong and change it to if (true == b). Personally, I don't like how this looks, so I just muddle through the old fashioned way, making darn sure I always use a double equals when I need it.
==================================================================

24 September 2010

Print classpath

import java.net.URL;
import java.net.URLClassLoader;

public class PrintClasspath {
       public static void main(String[] args) {

              //Get the System Classloader
              ClassLoader sysClassLoader = ClassLoader.getSystemClassLoader();

              //Get the URLs
              URL[] urls = ((URLClassLoader)sysClassLoader).getURLs();

              for(int i=0; i< urls.length; i++)
              {
                     System.out.println(urls[i].getFile());
              }

       }
}

Create a Java source dynamically, compile and call

import java.io.*;
import java.util.*;
import java.lang.reflect.*;

public class MakeTodayClass {
       Date today = new Date();
       String todayMillis = Long.toString(today.getTime());
       String todayClass = "z_" + todayMillis;
       String todaySource = todayClass + ".java";

       public static void main (String args[]){
              MakeTodayClass mtc = new MakeTodayClass();
              mtc.createIt();
              if (mtc.compileIt()) {
                      System.out.println("Running " + mtc.todayClass + ":\n\n");
                      mtc.runIt();
                      }
              else
                      System.out.println(mtc.todaySource + " is bad.");
              }

       public void createIt() {
              try {
                     FileWriter aWriter = new FileWriter(todaySource, true);
                     aWriter.write("public class "+ todayClass + "{");
                     aWriter.write(" public void doit() {");
                     aWriter.write(" System.out.println(\""+todayMillis+"\");");
                     aWriter.write(" }}\n");
                     aWriter.flush();
                     aWriter.close();
                     }
              catch(Exception e){
                     e.printStackTrace();
                     }
              }

       public boolean compileIt() {
              String [] source = { new String(todaySource)};
              ByteArrayOutputStream baos= new ByteArrayOutputStream();

              new sun.tools.javac.Main(baos,source[0]).compile(source);
              // if using JDK >= 1.3 then use
              // public static int com.sun.tools.javac.Main.compile(source);
              return (baos.toString().indexOf("error")==-1);
              }

       public void runIt() {
              try {
                     Class params[] = {};
                     Object paramsObj[] = {};
                     Class thisClass = Class.forName(todayClass);
                     Object iClass = thisClass.newInstance();
                     Method thisMethod = thisClass.getDeclaredMethod("doit", params);
                     thisMethod.invoke(iClass, paramsObj);
                     }
              catch (Exception e) {
                     e.printStackTrace();
                     }
              }
}

23 September 2010

Get the user name

public class PrintUserName
{
       public static void main(String args[]) {
              String username;
              username = System.getProperty("user.name");
              System.out.println("User Name : " + username);
       }
}

How can I force garbage collection to take place???

You can't force it but you call System.gc(), which is a "hint" to the runtime engine that now might be a good time to run the GC. But garbage collection using this method is not guaranteed to be done immediately.

A small tip on String to avoid NullPointerException

Problem
======
Sometimes the condition in Java class needs to compare between a constant string and a variable.

For example:
your_string_variable.equals(CONSTANT_STRING);

String str1="ABC";
String str2;
str1.equals("ABC");
str2.equals("ABC"); // this statment thr error


this thing throws NullPointerException if your_variable is not initilized....

Solution
======
To avoid this null pointer exception you can re-write the above statement:

CONSTANT_STRING.equals(your_string_variable);

String str1="ABC";
String str2;
"ABC".equals(str1);
"ABC".equals(str2);