16 October 2010

How every class has top super class is object ???

How every class has top super class is object???


when we create any class implicitly (automatically) it super class is Object class(java.lang.Object) but if create class but it extends its our own class..... let see how that working


 this class list C extend B, B extend A, A extend nothing


class A {
.....
}


class B extends A {
.....
}


class C extends B {
.....
}




But C extending B ... Java inheritance rule. one class can extends only one class. so C extends B,
every class extends Object class ....


Here is C extends B, B extends A, but A extends implicitly Object (which class has no extending any class that class extends Object class)


it means C has properties of Object class because | Object > A > B > C |,  C class has also advance java Object class properties


any class extends any class those class does not extends Object.. actually there is one class which has no explicitly extends so that class extends Object class by compiler

Java 6.0 New Collection APIs an Overview

Java 6.0 New Collection APIs an Overview
The following are the new collection APIs introduced in Java 6.0. I listes them as Interfaces and classes.

  • New Interfaces
  1. Deque
  2. BlockingDeque
  3. NavigableSet
  4. NavigableMap


  • New Classes
  1. ArrayDeque
  2. LinkedBlockingDeque
  3. ConcurrentSkipListSet
  4. ConcurrentSkipListMap
  5. AbstractMap.SimpleEntry
  6. AbstractMap.SimpleImmutableEntry

  • Updated Classes in Java 6.0
  1. LinkedList
  2. TreeSet
  3. TreeMap
  4. Collections

11 October 2010

JLable text Horizontal and Vertical Alignment

Horizontal Alignment 
Text Alignment Rigth
JLabel label1 = new JLabel("BottomRight", SwingConstants.RIGHT);

Text Alignment Left (It is by default)
JLabel label2 = new JLabel("CenterLeft", SwingConstants.LEFT);

Text Alignment Center
JLabel label3 = new JLabel("TopCenter", SwingConstants.CENTER);

Vertical Alignment
Text Alignment Bottom
label1.setVerticalAlignment(SwingConstants.BOTTOM);

Text Alignment Center vertically
label2.setVerticalAlignment(SwingConstants.CENTER);

Text Alignment Top
label3.setVerticalAlignment(SwingConstants.TOP);

10 October 2010

Disable JFram windows maximize button

just writer code

Myframe.setResizable(false);
class MyFrame {

       MyFrame() {
              this.setResizable(false);
       }

}

06 October 2010

(confusion code) check out what the output..???

public class CDummy
{
       static int toto = 7;

       CDummy getDummy() {
              return null; // pay attention here !
       }

       public static void main(String args[])
       {
              System.out.println("CDummy.");

              CDummy dmy = new CDummy();

              System.out.println(dmy.getDummy().toto);
       }
}

can you guess the output of the above code ? (try not to run the code)

plz replay me....

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 - 2

1. Add Application Exit Logic

Swing frame windows (JFrames) automatically close themselves if you click on the close icon (the X in the corner). However, if the JFrame was the main window for your application, the application will not actually quit. After closing the window, users will need to hit Ctrl-C or whatever key sequence stops a running application on their particular platform. Worse, if the application was started with javaw, it will continue to run invisibly. There's an easy fix: shut down the application when the main window closes. It looks like this: 

       // JFrame f;
       f.addWindowListener(new WindowAdapter() {
              public void windowClosing(WindowEvent we) { System.exit(0); }
       });

================================================================== 

2. Use the Main-class JAR Attribute

If you do package up an application in a JAR, there are two ways to run it. The first way is kind of clumsy--you have to add the JAR to your CLASSPATH and you have to know the name of the class to run. Suppose, for example, that I have an application called Shorts, packages in a JAR called Shorts.jar. To run it, I'd do something like this: 

java -cp Shorts.jar Shorts

A much nicer solution is to use the Main-class attribute, which is a way of embedding the name of the class to run inside the JAR. Then you can just run the application (in Java 2, at least) like this:
java -jar Shorts.jar
How do you do it? Normally, you would create the JAR something like this:
jar cvf Shorts.jar *.class
The trick to adding the Main-class attribute is defining an entirely separate file with the attribute definition. For instance, create the following one-line file and save it as extra.mf:
Main-class: Shorts
Now, to create the JAR, use this command line:
jar cvmf extra.mf Shorts.jar *.class
================================================================== 
 

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.
==================================================================

Static versus instance initializers blocks of a java class

class Foo {

       /* Static initializer: executes when the class is loaded. */
       static {
              System.out.println("class Foo loaded!");
       }

       /* Instance initializer: excutes when calling new Foo(),
       BEFORE anything inside the Foo constructor */
       {
              System.out.println("new instance of Foo about to be created!");
              // has access to internal Foo methods:
              print("instance initializer has access to internal methods!");
       }

       /* Constructor */
       public Foo() {
              System.out.println("Foo constructor statements!");
       }

       public void print(String msg) {
              System.out.println(msg);
       }


       static public void main(String[] args) {
              new Foo();
              System.out.println(" ");
              new Foo();
       }
}

Generating a javadoc into a target folder

For the whole set of java libraries, into folder 'api':
$ mkdir src
$ mv src.zip src/
$ cd src/
$ unzip src.zip
$ mkdir api
$ javadoc -J-Xmx1000m -d api -subpackages com:java:javax:org:sunw
 

Measure the width and height, in pixels, of a piece of text in a String, for a specific Font

static public Dimension getTextDimensions(String text, Component component, Font font) {
       FontMetrics fm = component.getFontMetrics(font);
       int[] ws = fm.getWidths(); // for the first 256 characters
       int height = fm.getHeight();
       int width = 0;
       for (int i=text.length() -1; i>-1; i--) {
              int c = (int)text.chatAt(i);
              if (c < 256) {
              width += ws[c];
       } // else ignore character
       return new Dimension(width, height);
}


String text = "some text";
Font font = new Font("SansSerif", Font.PLAIN, 12);
Component c = ...; // your window frame, for example, or a JLabel, etc.

Dimension dim = getTextDimensions(text, c, font);

Count the number of CPUs in your system

import java.io.*;

class Test {
       static private boolean isWindows = System.getProperty("os.name").startsWith("Windows");

       static private int n_CPUs = 0;

       static public int getCPUCount() {
              if (n_CPUs > 0) return n_CPUs;
              if (isWindows) return 1; // no clue
              // POSIX systems, attempt to count CPUs from /proc/stat
              try {
                     Runtime runtime = Runtime.getRuntime();
                     Process process = runtime.exec("cat /proc/stat");
                     InputStream is = process.getInputStream();
                     InputStreamReader isr = new InputStreamReader(is);
                     BufferedReader br = new BufferedReader(isr);
                     String line;
                     n_CPUs = 0;
                     // valid cores will print as cpu0, cpu1. cpu2 ...
                     while ((line = br.readLine()) != null) {
                            if (0 == line.indexOf("cpu") && line.length() > 3
                            && Character.isDigit(line.charAt(3))) {
                                   n_CPUs++;
                            }
                     }
                     // fix possible errors
                     if (0 == n_CPUs) n_CPUs = 1;
                     return n_CPUs;
              } catch (Exception e) {
                     //Utils.log(e.toString()); // just one line
                     return 1;
              }
       }

       public static void main(String args[]) {
              System.out.println("No of CPU = "+getCPUCount());
       }
}

Useful Java Utilities and Frameworks


  • XStream “A simple library to serialize objects to XML and back again.”

  • Rome Java tools for parsing, generating and publishing RSS and Atom feeds.

  • Google Collections “a suite of new collections and collection-related goodness for Java 5.0, brought to you by Google. This library is a natural extension of the Java Collections Framework you already know and love. “

  • Google Guice (DI Framework) “Put simply, Guice alleviates the need for factories and the use of new in your Java code. Think of Guice’s @Inject as the new new. You will still need to write factories in some cases, but your code will not depend directly on them. Your code will be easier to change, unit test and reuse in other contexts.”

  • EasyMock “EasyMock provides Mock Objects for interfaces in JUnit tests by generating them on the fly using Java’s proxy mechanism.”

  • Apache Commons Tons of useful utilities for Java that I can’t pick just one.

  • GWT Java-Ajax web framework – very cool

  • JFreeChart “JFreeChart is a free 100% Java chart library that makes it easy for developers to display professional quality charts in their applications.”


  • Lucene “High-performance, full-featured text search engine library written entirely in Java.”

  • Squirrel SQL “Graphical Java program that will allow you to view the structure of a JDBC compliant database, browse the data in tables, issue SQL commands etc,”

  • NIO.2 Ok, technically not an open source framework. This is the new version of NIO that will be included in Java 7. This is what we’ll be using in place of File and many of the other classes in the java.io package. Pretty cool.

Null Layout Manager (swing)

Layout Managers are used in the orginization of Panels and Frames. The proper layout should be chosen to accomodate, frame resizings and use.


Null:
*No Layout, items must be manually positioned and arranged.
This layout should only be used if the window will not and cannot be resized, as the item in the window will stay where they are placed, be that hidden or clumped in one corner of a window.

CODE example:
import java.awt.event.*;
import javax.swing.*;

public class NullLayoutExample extends JFrame {

       public NoLayoutExample(String name) {
              super(name);
              JTextField newItemField;
              JList itemsList;
              JButton addButton;
              JButton removeButton;

              getContentPane().setLayout(null);

              //The text field
              newItemField = new JTextField();
              newItemField.setLocation(12,12);
              newItemField.setSize(150,30);
              getContentPane().add(newItemField);

              //The Add button
              addButton = new JButton(“Add”);
              addButton.setMnemonic(‘A’);
              addButton.setLocation(174, 12);
              addButton.setSize(100,30);
              getContentPane().add(addButton);

              //The List
              itemsList = new JList();
              JScrollPane scrollPane = new JScrollPane(itemsList,
              ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,
              ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
              scrollPane.setLocation(12,45);
              scrollPane.setSize(150,150);
              getContentPane().add(scrollPane);

              //The Remove button
              removeButton = new JButton(“Remove”);
              removeButton.setMnemonic(‘R’);
              removeButton.setLocation(174,45);
              removeButton.setSize(100,30);
              getContentPane().add(removeButton);
       }

       public static void main(String[] args) {
              JFrame frame = new NoLayoutExample(“NULL Example”);
              frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
              frame.setSize(286, 230);
              frame.setResizable(false);
              frame.setVisible(true);
       }
}

28 September 2010

Centering application on the screen

// Get the size of the screen
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
    
// Determine the new location of the window
int w = window.getSize().width;
int h = window.getSize().height;
int x = (dim.width-w)/2;
int y = (dim.height-h)/2;
    
// Move the window
window.setLocation(x, y);


copy to clip board

public static void copyToSystemClipboard(String str) {
    StringSelection ss = new StringSelection(str);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ss, null);
}

Literals

boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
>> You may have noticed that the new keyword isn't used when  initializing a variable of a primitive type.
>> Primitive types are special data  types built into the language; they are not objects created from a class.
>> A  literal is the source code representation of a fixed value;
>> literals  are represented directly in your code without requiring computation
The integral types (byte, short,  int, and long) can be expressed using decimal, octal,  or hexadecimal number systems. 
int decVal = 26;  // The number 26, in decimal
int octVal = 032;  // The number 26, in octal
int hexVal = 0x1a; // The number 26, in hexadecimal
 
 
double d1 = 123.4;
double d2 = 1.234e2;  // same value as d1, but in scientific notation
float f1  = 123.4f;
 
The Java programming language also supports a few special escape sequences  for char and String literals:
\b  (backspace),
\t (tab),
\n (line feed),
\f  (form feed),
\r (carriage return),
\" (double quote), 
\' (single quote),
and \\ (backslash).
 
  
>> There's also a special null literal that can be used as a value  for any reference type. There's also a special null literal that can be used as a value  for any reference type. null may be assigned to any variable,  except variables of primitive types. may be assigned to any variable,  except variables of primitive types.
>> Therefore,  null is often used in programs as a marker to indicate that some  object is unavailable.
>> There's also a special kind of literal called a class  literal, formed by taking a type name and appending ".class";  for example, String.class. This refers to the object (of type  Class) that represents the type itself.  

Default Values of Premitive type

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.



Data Type
Default Value (for fields)
byte
0
short
0
int
0
long
0L
float
0.0f
double
0.0d
char
'\u0000'
String (or any object)
null
boolean
false


Local variables are slightly different; the compiler never assigns a default value to an uninitialized local variable. If you cannot initialize your local variable where it is declared, make sure to assign it a value before you attempt to use it. Accessing an uninitialized local variable will result in a compile-time error.

Unix: Ten Things Every Java Developer Should Know

Unix: Ten Things Every Java Developer Should Know

One of the great things about Java is how multi-platform it really is. While cross platform glitches do occur, they are not really all that common. But since the law of unintended consequences is all pervasive, we now have the common sight of teams of developers building Java programs meant to run on Unix boxes on Windows.
Developing code meant for Unix on Windows does work reasonably well. The trouble is, many those coders slaving away in front of XP have a very limited understanding of their target platform. If that describes you, this following list is meant for you. Without further ado, here are the ten things you really need to know about Unix, in reverse David Letterman order:

10) You need to be special to use some ports

On Unix machines, programs run by ordinary mortals cannot use network ports less than 1024. Only the special root user can use these ports. If you do decide that you need to run your server as root, be very careful since a program running as root is all powerful on a Unix machine.

9) There is no magic file locking

Windows has this magic file locking mechanism that prevents people from removing a file while it is open. Thus, on a Windows box the call to delete() in the following code is pretty much sure to fail:
InputStream is = new FileInputStream("foo.txt");
(new File("foo.txt")).delete();
int ch;
while( (ch = is.read()) > 0 )
  System.out.println( "char: " + (char)ch );
is.close();
The delete will fail because someone (our program in fact) has the file open. After we get done printing out its contents, foo.txt will still be there. The kicker is, the delete() will work just fine on any Unix box. Under Unix, the call to delete() will delete the entry for foo.txt out from the file system, but since someone (our program) still has the file open, the bytes will live on, to be read and printed out. Only when we close the stream will the contents of foo.txt follow its name into oblivion.
In exactly the same way, on a Unix box, someone can delete a program's current directory right out from underneath it.

8) Sometimes there is no GUI

People who are used to Windows are sometimes surprised to find their programs running on a Unix box that has no GUI at all. None. Zilch. Nada. In Unix, the GUI is an add on component and it is completely optional. The machine will run fine without it and servers commonly do. Be very careful making calls to those handy java.awt methods -- some of them will fail on a machine with no GUI.
While you are at it, you may want to rethink what you are writing out with System.out. Many severs not only lack a GUI, they are completely headless: no keyboard, no mouse, no screen. If you are deploying into this kind of environment, the log file is your friend, because your program's cries for help are unlikely to be heard anywhere else.

7) In Unix, there is no registry...

... but if there was, it would be a plain text file. Unix systems have no central place like the Windows registry for storing configuration information. Instead, Unix configuration is spread over a fair number of different files. Many of these files live in a directory called /etc : the list of users is in a file called /etc/passwd, while the name of the machine is typically found in /etc/host.
I guess if you are a Windows user that is the bad news. Here is the good news: most, if not all of the configuration files are plain text files. You can look at them with any old text editor. A further bit of good news is that all modern Unix like systems come with GUIs to edit the configuration files.

6) Forward slashes are your friend

This one is really more about Java on Windows than it is about Unix, but useful anyway. Just about everyone knows that Unix uses forward slashes to separate the bits of a path: /etc/passwd, while Windows uses backslashes: c:\Program Files\Windows. What a disturbing number of folks don't realize is that forward slashes work just fine on in Java on Windows too. On a Windows box, Java is smart enough to translate /a/b/c/foo.txt to something like C:\a\b\c\foo.txt.
Should you rely on this for production? No. If you are really coding cross platform Java, you need know about File.pathSeparator and the various File constructors. But if you are coding stuff that is only meant for Unix, and you just want to test it on your windows box, knowing that the forward slashes work in both places can save a lot of agony.

5) Our services are just programs

In Windows, system services are special programs, written to a particular service API. On Unix, services are provided by pretty ordinary programs that do service like things.
Typically, a Unix service consists of the useful program and a script which starts the program in the background when the system starts up and may shut it down again when the system is halting. Many Unix systems keep these scripts in the /etc/init.d directory.

4) Environment variables are hard to change

Windows programmers sometimes cook up little batch files that set the environment variables they want. Perhaps you need to roll back to an old version of Java and Ant. You might write a batch file that looks something like:
set JAVA_HOME=C:\java1.4.1_05
set ANT_HOME=C:\apache-ant-1.6.1
They can then run the batch file:
c:\> setenv.bat
and have the environment that you need. If you try to translate this directly into Unix-land, you get a script that looks not too different:
#!/bin/sh

JAVA_HOME=/usr/java1.4.1_05
export JAVA_HOME

ANT_HOME=/usr/apache-ant-1.6.1
export ANT_HOME
So you try out your new script...
$ setenv.sh
...and it does nothing. The trouble is that the Unix shell runs scripts by creating a copy of itself and running the script in the new shell. This new shell will read in the script, set all the environment variables and then exit, leaving the original shell and its environment unchanged. I hate when that happens. Changing directories works pretty much the same way: if you do a cd in an ordinary shell script, it will change the directory for that second shell, which may or may not be what you want.
If what you want is to change things in your current shell, you need to have the current shell read in the script directly, without starting a new shell to do the job. You can do this with by using the dot command:
. setenv.sh
Life will be good as your environment variables change.
I should mention that there are several different shells available in Unix. Which one you use is mostly a matter of taste, either yours or the person who set up your account. The commands above will work with many of the common Unix shells, but if you happen to be running the C shell (note the pun), then your little script will need to look something like:
setenv JAVA_HOME /usr/java1.4.1_05
setenv ANT_HOME /usr/apache-ant-1.6.1
You also need a different command to read the script in:
source setenv.csh

3) We don't like spaces in our file names

Okay, this one probably has more to do with Unix users and sys admins than the OS itself, but the fact is, we don't like spaces in our paths. Oh it is perfectly possibly to have spaces in Unix file names. In fact you can put darn near anything in a Unix file name: /tmp/:a,*b%c is actually the name of a directory on the system that I am using to write this.
But can and should are two different things. Unix users spend much of their time using the command line and Unix command line utilities are not crazy about paths with stars, question marks and especially spaces. The Unix guy can always find a way, but if you insist on putting strange characters like spaces in your file names, you are just finding a way to annoy your local Unix guy.

2) There is no carriage to return

If I had just one magic lighting bolt to hurl at one person, I think I would pick the guy who decided to use different line terminating characters on the two major OS's. I suspect we would have hyper intelligent computers by now were it not for all the time wasted trying to figure out why my file looks funny on your OS.
In a plain text file, Windows typically uses a carriage return followed by a newline character to mark the end of a line. Unix dispenses with the carriage return and makes due with the single newline character. Although the tools are getting better, Unix style files may show up as one long line in Windows -- not a single carriage return/newline pair in that file, must be a single line. Likewise, Windows style files will sometimes show up on Unix with garbage characters at the end of a line -- that extra carriage return is meaningless under the Unix convention.
This doesn't matter much for Java files -- it's all white space to the Java compiler. But some native Unix programs care passionately about those funny characters at the end of a line. In particular if you use a Windows based tool to edit a Unix script and your tool adds carriage returns to the script file, you have screwed it up. The script will no longer run. Worse, since many Unix editors do now handle the carriage returns, you could look at the broken script and see nothing wrong.

1) You need a Linux box

If you are doing significant development for Unix, you owe it to yourself and your customers to know something about Unix. If all else fails, get yourself an old PC and some of that free Linux. Or get yourself one of the many bootable Linux-on-a-CD distributions and try it out on any machine. Java is nearly platform independent, but not quite. It is up to you to make up the difference.

27 September 2010

Swing Components look,feel like other OS components

system default:
javax.swing.UIManager.setLookAndFeel(javax.swing.UIManager.getSystemLookAndFeelClassName());

windows:
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");

motif:
javax.swing.UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");

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);

A program to print limits of the primitive types

public class PrintLimits
{

       public PrintLimits(){
       }

       public static void main(String args[]) {

              System.out.println("Min byte value = " + Byte.MIN_VALUE);
              System.out.println("Max byte value = " + Byte.MAX_VALUE);
              System.out.println("Min short value = " + Short.MIN_VALUE);
              System.out.println("Max short value = " + Short.MAX_VALUE);
              System.out.println("Min int value = " + Integer.MIN_VALUE);
              System.out.println("Max int value = " + Integer.MAX_VALUE);
              System.out.println("Min float value = " + Float.MIN_VALUE);
              System.out.println("Max float value = " + Float.MAX_VALUE);
              System.out.println("Min double value = " + Double.MIN_VALUE);
              System.out.println("Max double value = " + Double.MAX_VALUE);
       }
}