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