Tuesday, 3 July 2012

Java program to read xml using DOM parser


 Download a sample Xml File at http://goo.gl/j8TBO

import java.io.File;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class XMLReader {

 public static void main(String argv[]) {

  try {
  File file = new File("c:\\book.xml");
  DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  DocumentBuilder db = dbf.newDocumentBuilder();
  Document doc = db.parse(file);
  doc.getDocumentElement().normalize();
  System.out.println("Root element " + doc.getDocumentElement().getNodeName());
  NodeList nodeLst = doc.getElementsByTagName("book");
  System.out.println("Information of all books");

  for (int s = 0; s < nodeLst.getLength(); s++) {

    Node fstNode = nodeLst.item(s);
   
    if (fstNode.getNodeType() == Node.ELEMENT_NODE) {
 
           Element fstElmnt = (Element) fstNode;
      NodeList fstNmElmntLst = fstElmnt.getElementsByTagName("author");
      Element fstNmElmnt = (Element) fstNmElmntLst.item(0);
      NodeList fstNm = fstNmElmnt.getChildNodes();
      System.out.println("author : "  + ((Node) fstNm.item(0)).getNodeValue());
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("title");
      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
      System.out.println("title : " + ((Node) lstNm.item(0)).getNodeValue());
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("genre");
      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
      System.out.println("genre : " + ((Node) lstNm.item(0)).getNodeValue());
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("price");
      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
      System.out.println("price : " + ((Node) lstNm.item(0)).getNodeValue());
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("publish date");
      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
      System.out.println("publish date: " + ((Node) lstNm.item(0)).getNodeValue());
      NodeList lstNmElmntLst = fstElmnt.getElementsByTagName("description");
      Element lstNmElmnt = (Element) lstNmElmntLst.item(0);
      NodeList lstNm = lstNmElmnt.getChildNodes();
      System.out.println("description: " + ((Node) lstNm.item(0)).getNodeValue());
    }

  }
  } catch (Exception e) {
    e.printStackTrace();
  }
 }
}


Creating a Java class with Eclipse


Creating a Java class

In this section, you will create a new Java class and add methods using code generation actions.
  1. In the Package Explorer view, select the JUnit project. Click the New Java Package button in the toolbar, or select New > Package from the project's context menu .
  2. In the Name field, type test as the name for the new package. Then click Finish.
  3. In the Package Explorer view, select the new test package and click the New Java Class button in the toolbar.
  4. Make sure that JUnit appears in the Source Folder field and that test appears in the Package field. In the Name field, type MyTestCase.
    Java Class wizard
  5. Click the Browse button next to the Superclass field.
  6. In the Choose a type field in the Superclass Selection dialog, type Test to narrow the list of available superclasses.
    Superclass Selection dialog
  7. Select the TestCase class and click OK.
  8. Select the checkbox for Constructors from superclass.
  9. Click Finish to create the new class.
    Java Class wizard
  10. The new file is opened in the editor. It contains the new class, the constructor and comments.  You can select options for the creation and configuration of generated comments in the Goto the code templates preference page Java > Code Style > Code Templates preference page.
  11. In the Outline view select the new class MyTestCase. Open the context menu and select Source > Override/Implement Methods....
    Context menu of a type
  12. In the Override Methods dialog, check setUp() and tearDown() and click OK. Two methods are added to the class.
    Override Methods dialog
  13. Change the body of setUp() to container= new Vector();
  14. container and Vector are underlined with a problem highlight line as they cannot be resolved. A light bulb appears on the marker bar. Move the mouse over the underlined word Vector. A hover appears that shows the error message and contains quick fixes. Move the mouse into the hover and click Import 'Vector' (java.util). This adds the missing import declaration.
    Correction proposals hover for Vector
    The blinking cursor should still be on the line that contains the error (if not, set it to the end of the line). PressCtrl+1. This lets the cursor jump to the nearest error location and opens the quick fix proposals. ChooseCreate field 'container' to add the new field.
    Correction proposals for container
  15. In the Outline view, select the class MyTestCase. Open the context menu and select Source > Generate Getters and Setters....
    Generate Getter and Setter in context menu
  16. The Generate Getter and Setter dialog suggests that you create the methods getContainer and setContainer. Select both and click OK. A getter and setter method for the field container are added.
    Generate Getter and Setter dialog
  17. Save the file.
  18. The formatting of generated code can be configured in the Goto the code style formatter perference page Java > Code Style > Formatter preference page. If you use a prefix or suffix for field names (e.g. fContainer), you can specify this in the Goto the code style preference page Java > Code Style preference page so that generated getters and setters will suggest method names without the prefix or suffix.

Sunday, 1 July 2012

Net Beans Hello World Tutorials


This tutorial provides a very simple and quick introduction to the NetBeans IDE workflow by walking you through the creation of a simple "Hello World" Java console application. Once you are done with this tutorial, you will have a general knowledge of how to create and run applications in the IDE.
This tutorial takes less than 10 minutes to complete.
After you finish this tutorial, you can move on to the learning trails, which are linked from the Documentation, Training & Support page. The learning trails provide comprehensive tutorials that highlight a wider range of IDE features and programming techniques for a variety of application types. If you do not want to do a "Hello World" application, you can skip this tutorial and jump straight to the learning trails.
Contents
Content on this page applies to NetBeans IDE 6.9 and later
To complete this tutorial, you need the following software and resources.
Software or ResourceVersion Required
NetBeans IDEversion 6.9 and later
Java Development Kit (JDK)version 6 or version 7

Setting Up the Project

To create an IDE project:
  1. Start NetBeans IDE.
  2. In the IDE, choose File > New Project (Ctrl-Shift-N), as shown in the figure below.
    NetBeans IDE with the File > New Project menu item selected.
  3. In the New Project wizard, expand the Java category and select Java Application as shown in the figure below. Then click Next.
    NetBeans IDE, New Project wizard, Choose Project page.
  4. In the Name and Location page of the wizard, do the following (as shown in the figure below):
    • In the Project Name field, type HelloWorldApp.
    • Leave the Use Dedicated Folder for Storing Libraries checkbox unselected.
    • In the Create Main Class field, type helloworldapp.HelloWorldApp.
    • Leave the Set as Main Project checkbox selected.
    NetBeans IDE, New Project wizard, Name and Location page.
  5. Click Finish.
The project is created and opened in the IDE. You should see the following components:
  • The Projects window, which contains a tree view of the components of the project, including source files, libraries that your code depends on, and so on.
  • The Source Editor window with a file called HelloWorldApp open.
  • The Navigator window, which you can use to quickly navigate between elements within the selected class.
  • The Tasks window, which lists compilation errors as well other tasks that are marked with keywords such as XXX and TODO.
NetBeans IDE with the HelloWorldApp project open.

Adding Code to the Generated Source File

Because you have left the Create Main Class checkbox selected in the New Project wizard, the IDE has created a skeleton main class for you. You can add the "Hello World!" message to the skeleton code by replacing the line:
            // TODO code application logic here
        
with the line:
            System.out.println("Hello World!");
        
Save the change by choosing File > Save.
The file should look something like the following code sample.
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package helloworldapp;

/**
 *
 * @author <your name>
 */
public class HelloWorldApp {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
            System.out.println("Hello World!");
    }

}

        

Compiling and Running the Program

Because of the IDE's Compile on Save feature, you do not have to manually compile your project in order to run it in the IDE. When you save a Java source file, the IDE automatically compiles it.
The Compile on Save feature can be turned off in the Project Properties window. Right-click your project, select Properties. In the Properties window, choose the Compiling tab. The Compile on Save checkbox is right at the top. Note that in the Project Properties window you can configure numerous settings for your project: project libraries, packaging, building, running, etc.
To run the program:
  • Choose Run > Run Main Project (F6).
The next figure shows what you should now see.
The program prints Hello World! to the Output window (along with other output from the build script).
Congratulations! Your program works!
If there are compilation errors, they are marked with red glyphs in the left and right margins of the Source Editor. The glyphs in the left margin indicate errors for the corresponding lines. The glyphs in the right margin show all of the areas of the file that have errors, including errors in lines that are not visible. You can mouse over an error mark to get a description of the error. You can click a glyph in the right margin to jump to the line with the error.

Building and Deploying the Application

Once you have written and test run your application, you can use the Clean and Build command to build your application for deployment. When you use the Clean and Build command, the IDE runs a build script that performs the following tasks:
  • Deletes any previously compiled files and other build outputs.
  • Recompiles the application and builds a JAR file containing the compiled files.
To build your application:
  • Choose Run > Clean and Build Main Project (Shift-F11)
You can view the build outputs by opening the Files window and expanding the HelloWorldApp node. The compiled bytecode file HelloWorldApp.class is within the build/classes/helloworldapp subnode. A deployable JAR file that contains the HelloWorldApp.class is within the dist node.
Image showing the Files window with the nodes for the HelloWorldApp expanded to show the contents of the build and dist subnodes.
For information on how to run the application from the command line for your operating system, see the "The "Hello World" Application" lesson of the Java Tutorials.

Tuesday, 6 March 2012

Fibonacci series

class Fibonacci
{
public static void main(String args[])
{
int prev, next, sum, n;
prev=next=1
for(n=1;n<=10;n++)
{
System.out.println(prev);
sum=prev+next;
prev=next;
next=sum;
}
}
}

Prime Number or Not

import java.util.*;
class Prime
{
public static void main(String args[])
{
int n, i, res;
boolean flag=true;
Scanner scan= new Scanner(System.in);
System.out.println("Please Enter a No.");
n=scan.nextInt();
for(i=2;i<=n/2;i++)
{
res=n%i;
if(res==0)
{
flag=false;
break;
}
}
if(flag)
System.out.println(n + " is Prime Number");
else
System.out.println(n + " is not Prime Number");
}
}

Install Java On Linux

Steps

Manual Method

This is the 'generic' variant that also works with GNU/Linux clones that do not support RPM. It does not require administrator rights and allows to install multiple java versions on the same computer.

1
Download the JDK from Sun[1].
2
Click on the "Download" link in the JDK 6 section.
3
Accept the license and continue.
4
Under the "Linux Platform", select "self-extracting file".
5
Download this .bin file and save it to your GNU/Linux machine.
6
Once it has been downloaded, switch to the directory where you saved the file. You do not need to be a root and only must have the write access to the folder where you wish to install java. If your administrator is not supportive, you may need to place java into your home folder or even better on some shared network location.
7
Type sh name_of_the_downloaded_file, for instance sh jdk-6u2-linux-i586.bin. There is no need to make this file executable.
8
The license agreement should start appear on the screen. Scroll to the end of it with 'Enter' and type yes.
9
This installer will create its installation in the same folder, where the downloaded file was placed and from where you have started the installation script. But the installed java jre is rather independent and can be easily moved into another place just by copying all its files.
10
You can install multiple different jre's this way: they coexist together and can be used if some software requires the older version to run.
11
The java executable you need to launch is located in a subfolder, called 'bin'. This way of installation will not configure a default 'java' command for you: you must do this manually or always include the full path in your startup script.

Manual RPM Method

This seems a 'more civilized' way to install java: it allows the installer to check the dependencies on some system libraries that may be missing. However it does not support versioning easily and may fail even in some systems that do support RPMs. The current java installations are rather self-dependent and the required minimal requirements are usually satisfied anyway.

1
Download the JDK from Sun[2].
2
Click on the "Download" link in the JDK 6 section.
3
Accept the license and continue.
4
Under the "Linux Platform", select "RPM in self-extracting file".
5
Download this .bin file and save it to your GNU/Linux machine.
6
Once it has been downloaded, login as root and switch to the directory where you saved the file.
7
Execute './filename', where filename is the name of the file that you downloaded. The filename might be very similar to jdk-6-linux-i586-rpm.bin depending on what the latest version is. You may have to make the file executable by executing the 'chmod +x filename.bin' command.
8
You will get a license, press space bar a bunch of times until you are prompted to enter yes or no. Type in yes and hit enter.
9
This will place an .rpm file in the same directory as your .bin file with the same name (minus the .bin part).
10
Install the rpm file by executing 'rpm -i filename.rpm', where filename is the name of your .rpm file. (Such as jdk-6-linux-i586.rpm).
11
Now, if you want to be able to execute this version of Java interpretor or compiler from any directory on your GNU/Linux system you will have to create a few symbolic links:
ln -s /usr/java/jdk1.6.0/bin/java /usr/bin/java
ln -s /usr/java/jdk1.6.0/bin/javac /usr/bin/javac
12
You are done!

Monday, 5 March 2012

public class StaticMethodExample {

public static void main(String[] args) {

int result = MathUtility.add(1, 2);
System.out.println("(1+2) is : " + result);
}

}

class MathUtility{
public static int add(int first, int second)
{
return first + second;
}

}