Aptitude (12) ASP.NET (2) Automata (4) Browser (1) C (5) C# (1) C++ (10) Code (3) CSS (1) Data Structure (1) DATABASE (3) HTML (1) java (43) JSP (1) math (1) MySql (8) other (6) php (3) Servlet (3)

Saturday, 16 March 2013

import.image.BlogHeader;


important.codes.*;



make.Exefile;


 Download this Jar file and run the set fill the minimum  jre version 1.0.0 and convert your executable jar file into .exe file also make it in your  favs icon


Wednesday, 13 March 2013

avl.tree.Rotations;



1. Rotations: How they work
A tree rotation can be an imtimidating concept at first.  You end up in a situation where you're juggling nodes, and these nodes have trees attached to them, and it can all become confusing very fast.  I find it helps to block out what's going on with any of the subtrees which are attached to the nodes you're fumbling with, but that can be hard.

Left Rotation (LL)

Imagine we have this situation:

Figure 1-1
a
 \
  b
   \
    c

To fix this, we must perform a left rotation, rooted at A.  This is done in the following steps:

b becomes the new root.
a takes ownership of b's left child as its right child, or in this case, null.
b takes ownership of a as its left child.

The tree now looks like this:

Figure 1-2
  b
 / \
a   c

Right Rotation (RR)

A right rotation is a mirror of the left rotation operation described above.  Imagine we have this situation:

Figure 1-3
    c
   /
  b
 /
a

To fix this, we will perform a single right rotation, rooted at C.  This is done in the following steps:

b becomes the new root.
c takes ownership of b's right child, as its left child. In this case, that value is null.
b takes ownership of c, as it's right child.

The resulting tree:

Figure 1-4
  b
 / \
a   c

Left-Right Rotation (LR) or "Double left"

Sometimes a single left rotation is not sufficient to balance an unbalanced tree.  Take this situation:

Figure 1-5
a
 \
  c

Perfect. It's balanced.  Let's insert 'b'.

Figure 1-6
a
 \
  c
 /
b


Our initial reaction here is to do a single left rotation.  Let's try that.

Figure 1-7
  c
 /
a
 \
  b

Our left rotation has completed, and we're stuck in the same situation. If we were to do a single right rotation in this situation, we would be right back where we started.  What's causing this?  The answer is that this is a result of the right subtree having a negative balance. In other words, because the right subtree was left heavy, our rotation was not sufficient.  What can we do?  The answer is to perform a right rotation on the right subtree. Read that again. We will perform a right rotation on the right subtree.  We are not rotating on our current root. We are rotating on our right child.  Think of our right subtree, isolated from our main tree, and perform a right rotation on it:

Before:

Figure 1-8
  c
 /
b

After:

Figure 1-9
b
 \
  c

After performing a rotation on our right subtree, we have prepared our root to be rotated left.  Here is our tree now:

Figure 1-10
a
 \
  b
   \
    c

Looks like we're ready for a left rotation.  Let's do that:

Figure 1-11
  b
 / \
a   c

Voila. Problem solved. 



Right-Left Rotiation (RL) or "Double right"

A double right rotation, or right-left rotation, or simply RL, is a rotation that must be performed when attempting to balance a tree which has a left subtree, that is right heavy.  This is a mirror operation of what was illustrated in the section on Left-Right Rotations, or double left rotations. Let's look at an example of a situation where we need to perform a Right-Left rotation.

Figure 1-12
  c
 /
a
 \
  b

In this situation, we have a tree that is unbalanced.  The left subtree has a height of 2, and the right subtree has a height of 0. This makes the balance factor of our root node, c, equal to -2.  What do we do? Some kind of right rotation is clearly necessary, but a single right rotation will not solve our problem. Let's try it:

Figure 1-13
a
 \
  c
 /
b

Looks like that didn't work.  Now we have a tree that has a balance of 2. It would appear that we did not accomplish much.  That is true. What do we do?  Well, let's go back to the original tree, before we did our pointless right rotation:

Figure 1-14
  c
 /
a
 \
  b

The reason our right rotation did not work, is because the left subtree, or 'a', has a positive balance factor, and is thus right heavy.  Performing a right rotation on a tree that has a left subtree that is right heavy will result in the problem we just witnessed.  What do we do?  The answer is to make our left subtree left-heavy.  We do this by performing a left rotation our left subtree.  Doing so leaves us with this situation:

Figure 1-15
    c
   /
  b
 /
a


This is a tree which can now be balanced using a single right rotation.  We can now perform our right rotation rooted at C. The result:

Figure 1-16
  b
 / \
a   c

Balance at last.


2. Rotations, When to Use Them and Why

How to decide when you need a tree rotation is usually easy, but determining which type of rotation you need requires a little thought.

A tree rotation is necessary when you have inserted or deleted a node which leaves the tree in an unbalanced state.  An unbalanced state is defined as a state in which any subtree has a balance factor of greater than 1, or less than -1.  That is, any tree with a difference between the heights of its two subtrees greater than 1, is considered unbalanced.

This is a balanced tree:


Figure 2-1
  1
 / \
2   3


This is an unbalanced tree:


Figure 2-2
1
 \
  2
   \
    3


This tree is considered unbalanced because the root node has a balance factor of 2.  That is, the right subtree of 1 has a height of 2, and the height of 1's left subtree is 0.  Remember that balance factor of a tree with a left subtree A and a right subtree B is

B - A

Simple.

In figure 2-2, we see that the tree has a balance of 2.  This means that the tree is considered "right heavy".  We can correct this by performing what is called a "left rotation".  How we determine which rotation to use follows a few basic rules.  See psuedo code:

IF tree is right heavy
{
  IF tree's right subtree is left heavy
  {
     Perform Double Left rotation
  }
  ELSE
  {
     Perform Single Left rotation
  }
}
ELSE IF tree is left heavy
{
  IF tree's left subtree is right heavy
  {
     Perform Double Right rotation
  }
  ELSE
  {
     Perform Single Right rotation
  }
}



As you can see, there is a situation where we need to perform a "double rotation". A single rotation in the situations described in the pseudo code leave the tree in an unbalanced state.  Follow these rules, and you should be able to balance an AVL tree following an insert or delete every time.

Monday, 11 March 2013

java.little.Basic2;



20.07.2010

What is Java?

Java is a technology from Sun Micro Systems developed by James Gosling in 1991 with initial name ‘Oak’.

It was designed with the goal to work with any kind of device.

It was renamed to Java in 1995.

What are components of Java Technology?

Java is divided in four sub technologies

  1. Java Standard Edition (Java SE)
  2. Java Enterprise Edition (Java EE)
  3. Java Mobile Edition (Java ME)
  4. Java Fx

What are different software used?

  1. Java Development Kit (JDK)
    1. For Java Developers
  2. Java Runtime Environment (JRE)
    1. For clients
  3. Java IDE (Integrated Development Environment)
    1. Kawa
    2. NetBeans
    3. Eclipse
    4. Visual Age
    5. JDeveloper
    6. JCreator
    7. BlueJ
    8. Etc.

From where we can download these softwares?


How Much to Pay?

Nothing
JDK, JRE, NetBean, MySql etc. are Open Source

What is PATH?
PATH is an environmental variable that contains a list of folders to search executable files (.exe, .com, .bat)

PATH can be defined as temporary PATH using DOS prompt

            SET PATH=%PATH%;d:\jdk1.6\bin

PATH can also be defined as permanent setting
            My Computer àProperties àAdvanced àEnvironmental Variables à System Variables à Path àEdit àAdd the path after the semicolon



22.07.2010

Features of Java
  1. Simple and sober
  2. Object Oriented Programming
  3. Multi Threaded
  4. Java is Secure
  5. Java is Portable
  6. Java is Platform Independent or Write Once Run Any where
    1. .java à JAVAC à .class (byte code) à JVM à JIT à Binary à Execution
  7. Java is Robust
    1. Java provides a big set of built-in classes for almost every purpose
    2. Java provides built-in Garbage Collection and no memory leakage can occur
    3. In built-in exception handling features make the programs more authentic and robust

Basic Java Programming Rules

  1. Java is case sensitive
  2. Every Java program must have .java extension
  3. Every executable Java Class must have an entry point main()
    1. public static void main(String args[])
  4. Java follows certain syntactical rules
    1. All keyword must be in lower case
    2. All class names and interface  names must start with capital letter
                                                              i.      Math
                                                            ii.      String
                                                          iii.      BufferedReader
                                                          iv.      InputStreamReader
    1. All method names starts with small letter
                                                              i.      printf()
                                                            ii.      readLine()
                                                          iii.      println()
                                                          iv.      substring()
  1. Java provides a big set of classes categorized under different packages
    1. java.io à File, BufferedReader, InputStreamReader, IOException etc.
    2. java.lang (default) – Math, String, System etc.
    3. java.net à Socket, ServerSocket, DatagramPacket etc.
    4. java.applet à Applet, AudioClip etc.
    5. java.rmi
    6. java.awt à Button, TextField, Checkbox, Menu, PopupMenu etc.
    7. java.util àStack, Queue, LinkedList, Scanner etc.
    8. javax.swing à JFrame, JDialog, JColorChooser etc.
    9. javax.servlet
    10. javax.servlet.jsp
  2. To use the classes form these packages we need to include those classes using import command

Syntax
            import <packagename.classname>;
            or
            import <packagename.*>
                        for all classes
Example
            import java.util.Scanner;
            or
            import java.util.*;


General Input/Output operations

-          Java denotes the machine as system using System class of java.lang package
-          System class provides two built-in objects
o   out (for monitor)
o   in (for keyboard)
-          out is an static object of java.io.PrintStream class
-          in is an static object of java.io.InputStream class



Writing First Java Program
//Test.java
class First
{
            public static void main(String args[])
            {
                        int a=5,b=6;
                        System.out.printf("Product of %d and %d is %d",a,b,a*b);
            }
}

Compiling a Java Program
JAVAC <program name>

Example
JAVAC Test.java à First.class

Running a class

JAVA First

27.07.2010

Data Types in Java

-          Data types are used to define type of data and range of data
-          Can be of two types
o   Primitive types
o   User Defined Types
-          Primitive types are pre-defined types
o   Integrals (All are signed)
§  byte – 1 byte
§  short – 2 byte
§  int – 4 byte
§  long – 8 bytes
o   Floatings
§  float – 4 bytes
§  double – 8 bytes
o   Character
§  char – 2 bytes (Unicode)
o   Boolean
§  boolean – 2 bytes
-          User Defined Types (UDT)
o   Class
o   Interface
o   Enumerator



Passing data to the variables

-          Using Literals
-          Using Keyboard
-          Using command line
-          Using Files

Literals

-          The values that we use from our side are called as literal for assignment or some expression
-          Literals can be of different types
o   Integral literals
§  By default is int
·         int num=67;
§  Use l or L with long as suffix
·         long k=56L;
§  By default is decimal
§  Start an octal number with 0 and hexa decimal number with 0x or 0X
·         int num=072;
·         int k=0xA67F;
o   Floating Literals
§  Default is double
§  Use f or F with float
·         double k=6.8;
·         float p=6.7; // compile time error
·         float p=6.7f; //correct
o   Character Literals
§  Enclosed in single quotes
·         char ch=’A’;
·         char ch=65;
o    Boolean literals
§  Default is false
§  Use true or false only
·         boolean married=true;
o   String literals
§  Enclosed in double quotes
§  Strings are managed by String  class
·         String name="Rakesh";








29.07.2010

Reading Data from Keyboard

-          To read data from keyboard use any of two methods
o   Using Scanner class of java.util package
o   Using BufferedReader class of java.io package

Using Scanner class

-          First of all create an object of Scanner class

Scanner sc=new Scanner(System.in);

-          Scanner class provides different methods to read different kind of data
o   String next()
o   int nextInt()
o   float nextFloat()
o   double nextDouble()

Example 1
Write a program to input name and age of a person and check it to be valid voter.

import java.util.*;
class ReadData
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(System.in); // here sc is a reference
                        System.out.print("Enter your name : ");
                        String name=sc.next();

                        System.out.print("Enter your age : ");
                        int age=sc.nextInt();

                        if(age>=18)
                                    System.out.printf("Dear %s you can vote",name);
                        else
                                    System.out.println("Dear "+name+" you cannot vote");

            }
}


Example 2

Write a program to input a number and its power the produce the result.

import java.util.*;
class ReadData1
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(System.in);
                        System.out.print("Enter the Number : ");
                        double num=sc.nextDouble();
                        System.out.print("Enter the Power : ");
                        double p=sc.nextDouble();
                       
                        System.out.printf("%.2f to the power %.2f is %.2f",num,p,Math.pow(num,p));
            }
}


Getting input using BufferedReader

-          When we press a key from keyboard (System.in), stream of bits get produced and passed to another class InputStreamReader that convert the stream into characters.
-          These characters get collected by another class BufferedReader and placed into temporary buffer area until Enter key is pressed
-          Use readLine() method BufferedReader class to read data from that buffer area
-          The readLine() method throws an exception IOException, if some runtime error has occurred
o   public String readLine() throws IOException
-          This method provides data always in String format
-          To convert the data into numeric format use special classes called as Wrapper classes

What is a wrapper class?

A class corresponding to a data type is called as wrapper class.

Ø  byte àByte
Ø  short àShort
Ø  int àInteger
Ø  long àLong
Ø  float àFloat
Ø  double àDouble
Ø  boolean àBoolean
Ø  char àCharacter

They are mainly used to provide advance functionality on data types like conversion from string into number and other operations.

Conversion formula

datatype variable=wrapperclass.parseDatatype(stringdata);

Example
int age=Integer.parseInt(br.readLine());



import java.io.*;
class ReadData
{
            public static void main(String args[]) throws IOException
            {
                        InputStreamReader isr=new InputStreamReader(System.in);
                        BufferedReader br=new BufferedReader(isr);

                        System.out.print("Enter your name : ");
                        String name=br.readLine();

                        System.out.print("Enter your age : ");
                        int age=Integer.parseInt(br.readLine());

                        if(age>=18)
                                    System.out.printf("Dear %s you can vote",name);
                        else
                                    System.out.println("Dear "+name+" you cannot vote");

            }
}

31.07.2010

Usage of Wrapper classes

Such classes provide advance operations on their data types

Example

Integer class

-          public static String toBinaryString(int num)
-          public static String toOctalString(int num)
-          public static String toHexString(int num)


Example
//Using Integer class
class IntegerTest
{
            public static void main(String args[])
            {
                        int num=4567;
                        System.out.println(Integer.toBinaryString(num));
                        System.out.println(Integer.toOctalString(num));
                        System.out.println(Integer.toHexString(num));                    
            }
}



Problem
Get a character from keyboard and check it to be alphabet, digit or special character

Hint: String class provides a built-in method charAt() to read a character from string

//Character class test
import java.io.*;
class CharacterTest
{
            public static void main(String args[]) throws IOException
            {
                        System.out.print("Enter a character : ");
                        char ch=(char)System.in.read();
                        if(Character.isLetter(ch))
                                    System.out.println(ch+" is an alphabet");
                        else if(Character.isDigit(ch))
                                    System.out.println(ch+" is a digit");
                        else
                                    System.out.println(ch+" is special character");          
            }
}


Using import static command

-          Allows to import static members of a class
-          We can skip the class name with static members

Example
import static java.lang.System.*;

Test Case
import java.io.*;
import static java.lang.System.*;
import static java.lang.Character.*;
class ImportStaticTest
{
            public static void main(String args[]) throws IOException
            {
                        out.print("Enter a character : ");
                        char ch=(char)in.read();
                        if(isLetter(ch))
                                    out.println(ch+" is an alphabet");
                        else if(isDigit(ch))
                                    out.println(ch+" is a digit");
                        else
                                    out.println(ch+" is special character");
            }
}



Using Command Line Arguments

-          When we pass some data to a program while running it from DOS prompt is called as command line input
-          Such data get passed to main() into args variable
-          Each array in Java is treated like Object and provide length property

Test Case

Write a Java class to input some strings, print total number of strings and their position

class CmdTest
{
            public static void main(String args[])
            {
                        System.out.println("Total Arguments : "+args.length);
                        for(int i=0;i<args.length;i++)
                                    System.out.println(i + ": "+ args[i]);
            }
}

Test Case

Write a class to get name and age of a person from command line and check it to be valid voter

class Voter
{
                public static void main(String args[])
                {
                                if (args.length<2)
                                {
                                                System.out.println("Syntax is : Voter <name> <age>");
                                                return;
                                }
                                String name=args[0];
                                int age=Integer.parseInt(args[1]);
                                if(age>=18)
                                                System.out.printf("Dear %s you can vote",name);
                                else
                                                System.out.printf("Dear %s yor cannot vote",name);
                }
}


Class Assignment

  1. Write a program to input two numbers from keyboard and print sum of all numbers in range.
  2. Write a program to input two numbers from command line and print all even numbers in range




03.08.2010
What is a class?

-          A class is a set of specifications about an entity
-          It defines a set of attributes (fields) about an entity along with certain behaviors (methods)
-          Use classkeyword to create a class
-          It is generally used to create similar set of objects

What is an object?

-          An object is the real entity created based on class specifications
-          An object get created using special methods called a constructor
-          Use new keyword along with the constructor to create an object
-          new keyword allocated the memory to the elements inside an object and constructor is used to initialize that memory

classname reference=new constructor(<arguments>);

Example
            Date d=new Date();
            Scanner sc=new Scanner(System.in);

Constructor

-          Special method inside a class having some features
o   Same name as class name
o   No return type
o   Used to initialized fields of a class
o   If we not create any constructor then default constructor is created automatically
o   If create any parameterized constructor then default constructor is not created automatically. We have to create it.

Note: We can pass data to an object using any of two ways
  1. Using Constructor
  2. Using methods


Example
Create a class Number having a field as num of integer type. Create a method setNumber() to pass the number to num. Create a method as SquareRoot() to print square root of that number


Solution 1
class Number
{
            int num;
            public Number()
            {
            }
            public Number(int n)
            {
                        num=n;
            }
           
            public void setNumber(int n)
            {
                        num=n;
            }
            public void squareRoot()
            {
                        System.out.println("Square root of "+num +" is "+Math.pow(num,1.0/2));
            }
            public static void main(String args[])
            {
                        Number x=new Number();
                        x.setNumber(6);
                        x.squareRoot();
                        Number y=new Number();
                        y.setNumber(9);
                        y.squareRoot();          
                        Number z=new Number(10);
                        z.squareRoot();
                                   
            }
}

Note: If the field name and argument names are same then use this keyword to denote the field name of current object


class Number
{
            int num;
            public Number()
            {
            }
            public Number(int num)
            {
                        this.num=num;
            }
           
            public void setNumber(int num)
            {
                        this.num=num;
            }
            public void squareRoot()
            {
                        System.out.println("Square root of "+num +" is "+Math.pow(num,1.0/2));
            }
            public static void main(String args[])
            {
                        Number x=new Number();
                        x.setNumber(6);
                        x.squareRoot();
                        Number y=new Number();
                        y.setNumber(9);
                        y.squareRoot();          
                        Number z=new Number(10);
                        z.squareRoot();
                                   
            }
}

Assignment

Create a class Customer having fields accno, name and balance. Create a constructor to initialize these fields.

Create three methods deposit(), withdraw() and showBalance() to deposit the money, withdraw the money and show the current balance

Create an object of customer and show usage of customer class

Solution
class Customer
{
            int accno;
            String name;
            double balance;
            public Customer(int accno, String name,double opamt)
            {
                        this.accno=accno;
                        this.name=name;
                        balance=opamt;
            }
            public void deposit(int amount)
            {
                        balance+=amount;
            }
            public void withdraw(int amount)
            {
                        balance-=amount;
            }
            public void showBalance()
            {
                        System.out.printf("Current Balance is %.2f\n",balance);
            }
            public static void main(String args[])
            {
                        Customer c1=new Customer(55,"Rakesh Verma",9000);
                        c1.deposit(6000);
                        c1.showBalance();
                        c1.withdraw(2000);
                        c1.showBalance();
                       
            }
}

05.08.2010

Components of a class

-          A class can have two kind of elements
o   fields
o   methods
-          Fields are used to hold some data and methods are used to performs some action
-          Fields can be of two types
o   Variable
o   Constant
§  To make the constants use final keyword

int num; //variable
final int num=10; //constant

-          Methods can of three types
o   Concrete methods
o   Abstract Methods
o   Final Methods
-          A concrete method is a method having the body contents and that method can be further overridden in child class
-          Abstract methods have the signature but no body contents. Such methods get overridden in child class. Such method are created only for overriding purpose. Use abstractkeyword to declare  a method as abstract
-          Final methods are such methods that can never be overridden. Use final keyword to make a method as final

Types of Class Members

-          Field and method can be of two types
o   Static Members or Class members
o   Non-Static Members or Instance Members
-          Static members can be called with or without object
-          Non-static members always need an object to call them

Example
Create a class as Maths having a field as num. Create two methods to calculate factorial of a number, first one as static and second one as non-static.





10.08.2010

OOPs (Object Oriented Programming System)

-          It is a system or methodology designed to achieve a goal “Better Project Management” using a set of components also known as pillars of OOPs
o   Encapsulation
o   Abstraction
o   Polymorphism
o   Inheritance
-          OOPs get implemented using the concept of class and object

What is class?

-          A set of specifications about an entity. It defines a set of field and methods related with some entity.
-          Use class keyword to create a class

class
{
            //members
}

-          All members must be placed within the pair of braces. It is said to be encapsulation.

Types of class members

  1. Field
    1. To hold data about an object
  2. Method
    1. To perform some action


Types of Members
  1. Static or class members
    1. Can be called directly by the class or by the object
    2. Use static keyword with such members
  2. Non-static or instance members
    1. Always need an object to call such members

Example

Create a class Customer having fields acno, name and balance. Also manage the current FD rate.

Create the methods to enter the data into these fields and method to deposit the money, withdraw the money and show the current balance. Create another method that takes some amount as principle and returns the interest based on given FD rate.

Note: Use thiskeyword to refer current object. If the field name and parameter names get mismatches use this keyword with the field name.


Solution
//OOPSTest.java
class Customer
{
            int acno;
            String name;
            int balance;
            static double fdrate=6.5;
            void setAcno(int num)
            {
                        acno=num;
            }
            int getAcno()
            {         
                        return acno;
            }
            void setName(String name)
            {
                        this.name=name;
            }
            String getName()
            {
                        return name;
            }
            void deposit(int amount)
            {
                        balance+=amount;
            }

            void withdraw(int amount)
            {
                        balance-=amount;
            }
            void showBalance()
            {
                        System.out.printf("Current Balance of %s is  : %d",name,balance);
            }
            static double getInterest(int amount, int p)
            {
                        return (amount*p*fdrate)/100;
            }
}

class SBI
{
            public static void main(String args[])
            {
                        Customer c=new Customer();
                        c.setAcno(900);
                        c.setName("Rahul Kumar");
                        c.deposit(5000);
                        c.withdraw(1300);
                        c.deposit(9000);
                        c.showBalance();
                        System.out.println(Customer.getInterest(9000,4));
            }
}

Running the class

Java SBI

14.08.2010

Abstraction or Data Hiding

-          It controls the accessibility of a class and its members in other classes and other packages.
-          Java provides four accessibility levels
o   Private
o   Public
o   Protected
o   Default or Package

Private means accessible within the same class only. Cannot be accessed using a reference.

Public means anywhere access in same of different folder (package).

Protected means in same class or in child class. Can also be accessed using a reference in same package.

Package or default members can be accessed within the package (folder) and can never be accessed outside the package.


What is a Package?

-          A package a folder that contains related set of classes
-          Packages can be of two types
o   Built-in packages
o   Custom Package



Built-in Packages

Java provides a big set of classes under packages for almost any purpose.

  1. java.lang (default)
  2. java.io
  3. java.sql
  4. java.util
  5. java.awt
  6. javax.swing
  7. javax.servlet
  8. javax.servlet.jsp
etc.

-          Every package provides different set of classes for different purpose
-          All such packages are provided under src.zip file of JDK
-          To use the classes of these packages import them using import keyword

import <packagename>.<classname>;   -- only one class
or
import <packagename>.*;  --- all classes of a package

Example
import java.util.Scanner;
or
import java.util.*;


We can also import static members of a class and use them without class them. Use import staticto import the static members of a class.

Example
Import all the static methods of Math class under java.lang package and use pow() method to calculate power of a given number.

            public static double pow(double number, double power)

Solution

import java.util.Scanner;
import static java.lang.System.*;
import static java.lang.Math.*;
class StaticImportTest
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(in);
                        out.print("Enter a number : ");
                        double num=sc.nextDouble();
                       
                        System.out.print("Enter power  : ");
                        double p=sc.nextDouble();
                       
                        double result=pow(num,p);
                        out.printf("%.2f to the power %.2f is %.2f",num,p,result);
            }
}

Using static blocks

-          Allows to execute some code before main()
-          Can also run a program without main()

Example 1

class StaticBlockTest
{
            static
            {
                        System.out.println("Hi");
            }
            public static void main(String args[])
            {
                        System.out.println("Hello");
            }
            static
            {
                        System.out.println("Welcome");
            }
}

Example 2
class StaticBlockTest
{
            static
            {
                        System.out.println("Hi");
                        System.exit(0);
            }
}

Creating a user define package

-          A package is a folder having related set of classes
-          Two packages can have classes with same name
-          Such packages get placed into some folder on some driver
-          It works as a library for any project

Steps
  1. Create a folder as container of your packages
    1. d:\mypackages
  2. Think your package names and created sub folders with those names under your container folder
    1. E.g. p1 and p2
  3. Create your classes and place them into these folders
    1. Each class must have package command on top

Example
Create a class as General having some general methods like SquareRoot, CubeRoot and place it into p1 package

Create another class as Sample in package p2 having some sample method like Hi(), Hello()

Create a class UsingPackage where input a number from keyboard and print square root and cube root of that number using the class General of p1 package.

Note: To search the classes inside the packages, we need to define the CLASPATH

CLASSPATH is an environment variable to search the class files

For Kawa
            Packages àclasspath àAdd Dir… àSelect the folder name having the packages
            D:\mypackages

For DOS
-          Set the CLASSPATH using
o   SET CLASSPATH=%CLASSPATH%;d:\mypackages;

For NetBeans
-          Select Libraries Properties
§  Add Jar/Dir…


package p1;
public class General
{
            public static double cubeRoot(double num)
            {
                        return Math.pow(num,1.0/3);
            }
            public static double squareRoot(double num)
            {
                        return Math.pow(num,1.0/2);
            }
}


package p2;
class Sample
{
            static void Hi()
            {
                        System.out.println("Hi to all");
            }
            static void Hello()
            {
                        System.out.println("Hello to all");
            }
           
}

import p1.*;
import java.util.*;
class UsingPackage
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(System.in);
                        System.out.print("Enter a number : ");
                        double n=sc.nextDouble();
                        System.out.println("Cube root is : "+General.cubeRoot(n));
                        System.out.println("Square root is : "+General.squareRoot(n));
                       
            }
}


26.08.2010

Method Overloading

-          When two or more methods have the same name but different number of arguments or different type of arguments, is called as method overloading
-          Return type do not participate in method overloading
-          Can be in same class or in child class


public void Area(int side) //Area of Square
{
}

public void Area(double r)      // Area of Circle
{
}

public void Area(int l, int w) //Area of Rectangle
{
}



Inheritance

-          Provides re-usability of code
-          We need to create re-usable classes and inherit those classes into other classes
-          It makes the compact and more manageable code
-          Java allows only single inheritance
-          Use extends keyword to inherit a class into other class
-          All classes in Java are child of java.lang.Object class

class A
{
}

class B extends A
{
}


Note: Use JAVAP.EXE tool to view contents of class file

JAVAP <classname>


The classes get placed in three layers
  1. Parent class
  2. Super class
  3. Derived class

If B is a derived class then A is a super class and Object is parent class.

Note: Use thiskeyword to refer object of current class and super keyword to refer object of super class.


class Num2
{
            int a,b;
            public Num2(int a, int b)
            {
                        this.a=a;
                        this.b=b;
            }
            public int g2()
            {
                        return a>b?a:b;
            }
            public int p2()
            {
                        return a*b;
            }
}

class Num3 extends Num2
{
            int c;
            public Num3(int a,int b, int c)
            {
                        super(a,b);
                        this.c=c;
            }
            public int g3()
            {
                        return g2()>c?g2():c;
            }
            public int p3()
            {
                        return p2()*c;
            }
}

class InheritanceTest
{
            public static void main(String args[])
            {
                        Num3 x=new Num3(5,6,7);
                        System.out.println(x.p3());
                        System.out.println(x.p2());
            }
}


Method Overriding

-          A method from parent or super class re-written in child class with same signature and different body contents, is called as method overriding
-          While overriding, we can increase scope of overridden method but cannot decrease it

class Num2
{
            int a,b;
            public Num2(int a, int b)
            {
                        this.a=a;
                        this.b=b;
            }
            public int greatest()
            {
                        return a>b?a:b;
            }
            public int product()
            {
                        return a*b;
            }
}

class Num3 extends Num2
{
            int c;
            public Num3(int a,int b, int c)
            {
                        super(a,b);
                        this.c=c;
            }
            public int greatest()
            {
                        return super.greatest()>c?super.greatest():c;
            }
            public int product()//Method Overriding
            {
                        return super.product()*c;
            }
}

class InheritanceTest
{
            public static void main(String args[])
            {
                        Num3 x=new Num3(5,6,7);
                        System.out.println(x.product());
            }
}

Golden Rule of Inheritance

-          A parent can hold reference to its childs can invoke all those methods of child whose signature is provided from parent to the child
-          Overridden method can be used in Dynamic method dispatch or Runtime Polymorphism where reference of parent class can be re-used to hold address of child classes

class A
{
            public void show()
            {
                        System.out.println("Calling from A");
            }
}

class B extends A
{
            public void show() //Overriding
            {
                        System.out.println("Calling from B");
            }
            public void hi()
            {
                        System.out.println("Hi to all");
            }
}

class C extends B
{
            public void show() //Overriding
            {
                        System.out.println("Calling from C");
            }
}

class DMDTest //Dynamic Method Dispatch
{
            public static void main(String args[])
            {
                        A p; //runtime polymorphism
                        p=new A();
                        p.show();
                        p=new B();
                        p.show();
                        p=new C();
                        p.show();
            }
}


31.08.2010

Types of Methods
Types of classes
Interfaces

Types of Methods

  1. Concrete method
    1. A method having the signature and body contents and can be overridden by child class
  2. Abstract methods
    1. A method having the signature but no body contents
    2. Such methods can be declared at two places
                                                              i.      Abstract class
                                                            ii.      Interface
    1. If declared inside an abstract class then use abstract keyword with the methods
    2. If declared inside an interface, no keyword is required, since all methods inside an interface are public and abstract by default
    3. Such methods are always overridden by child class
  1. Final methods
    1. A method that can never be overridden is called as final method
b.      Use final keyword to declare such methods


Types of classes

  1. Concrete class
    1. A class that can be instantiated and can also be inherited
  2. Abstract class
    1. A class that can never be instantiated
    2. Such classes are always used for inheritance purpose only
    3. Use abstract keyword with such class
    4. Abstract class may or may not have any abstract method but if a class contains any abstract method, the class must be declared as abstract.
  3. Final class
    1. A class that can be instantiated but can never be inherited is called as final class
    2. Use final keyword with such class

final class A
{
}

class B extends A //error
{
}

Test Case

Create a set of classes for college management

  1. Student
    1. Enquiry
    2. Current
    3. Alumni
  2. Faculty           
    1. Permanent
    2. Visiting
    3. Guest

Common (Abstract)
            name,email,mobile
Student (Concrete)
            Rollno, course
Faculty (Concrete)
            empid
            subject


import java.util.Scanner;
import static java.lang.System.*;
abstract class Common
{
            String name,email,mobile;
            public Common()
            {
            }         
            public Common(String name, String email, String mobile)
            {
                        this.name=name;
                        this.email=email;
                        this.mobile=mobile;
            }
            public String getName()
            {
                        return name;
            }
            public void setName(String name)
            {         
                        this.name=name;
            }
            public String getEmail()
            {
                        return email;
            }
            public void setEmail(String email)
            {
                        this.email=email;
            }
            public String getMobile()
            {
                        return mobile;
            }
            public void setMobile(String mobile)
            {
                        this.mobile=mobile;
            }
}

class Student extends Common
{
            int rollno;
            String course;
            public Student(int rollno, String name, String email, String mobile, String course)
            {
                        super(name,email,mobile);
                        this.rollno=rollno;
                        this.course=course;
            }         
            public int getRollno()
            {
                        return rollno;
            }
            public String getCourse()
            {
                        return course;
            }
}

class College
{
            public static void main(String []args)
            {
                        Scanner sc=new Scanner(System.in);
                        out.print("Enter roll no : ");
                        int rollno=sc.nextInt();
                        out.print("Name : ");
                        String name=sc.next();
                        out.print("Email : ");
                        String email=sc.next();
                        out.print("Mobile : ");
                        String mobile=sc.next();
                        out.print("Course : ");
                        String course=sc.next();
                        Student s=new Student(rollno,name,email,mobile,course);

                        out.printf("%s is doing %s course",s.getName(),s.getCourse());
            }
}

What is an Interface?

-          A user define data type very similar to class that contain all abstract methods  and final fields
-           All methods are public and abstract by default
-          All fields are public and final by default
-          A class can inherit any number of interfaces using implements keyword
-          Using interfaces we can implement multiple inheritance
-          Can never be instantiated but can have the reference


Test Case

Create an ERP software to implement the modules Hr, Finance and Sales.
interface Hr
{
            void salaryInfo();
}
interface Finance
{
            void budgeting();
}
interface Sales
{
            void forecasting();
}

class ERP implements Hr,Finance,Sales
{
            public void salaryInfo()
            {
                        System.out.println("Salary will be given on every 7th");
            }
            public void budgeting()
            {
                        System.out.println("Budget will be doubled this year");
            }
            public void forecasting()
            {
                        System.out.println("Sale will be double this year");  
            }
}

class AbcIndia
{
            public static void main(String args[])
            {
                        Hr h=new ERP();
                        h.salaryInfo();
                        h.forecasting();           
            }
}

04.09.2010

What is the different between method overloading and overriding?

-          Method overloading means multiple methods with same name but different number of argument or type of argument that can be in same class or in child class while method overriding means methods with same signature in parent class and in child class. Can only be in child class.
-          In case of overloading scope can be increased or declared while in case of overriding, we can increase the scope of overridden method but cannot decrease it

What is final?

-          final is a keyword used with three type of items
o   Field
o   Method
o   Class
-          If used with fields, makes the constant
-          If used with method, do not allow overriding of method
-          If used with class, cannot inherit such class

What is abstract?

-          Can be used with a class or method
-          Abstract methods having the signature but no body contents. Such methods are always created for overriding purpose only.
-          Abstract class is used for inheritance purpose only

Different between interface and abstract class?

-          An abstract class may or may not have any abstract method but interface contains all abstract methods only
-          We can inherit only one abstract class but many interfaces

What is need of method overriding?

-          When we want to allows runtime polymorphism then overriding is required

class Maths
{
                public double area(double r)
                {
                                return 3.14*r*r;
                }
}

class Sample
{
                public void show(Maths m)
                {
                                System.out.println("Area is : "+m.area(5.0));
                }
}

class NewMath extends Maths
{
                public double area(double r) //Method overriding
                {
                                return Math.PI*r*r;
                }
               
}
class Test
{
                public static void main(String args[])
                {
                                Sample s=new Sample();
                                Maths m=new NewMath();
                                s.show(m);
                }             
}




Abstract Window ToolKit (AWT)

-          A set of classes for GUI Programming provided under java.awt package
-          GUI Applications can be of two types
o   Desktop based application or Java Application
o   Web based application or Java Applet
-          To call a class as Java Application, it be must inherit from java.awt.Frame class
-          To call a class as Java Applet, it must inherit from java.applet.Applet class
-          AWT provides a set of classes categorized in three main categories
o   Containers
o   Components
o   Supporting classes
-          Containersmeans to hold the components
o   Frame, Applet, Dialog, Window, Panel etc.
-          Componentsare used to provide the user interaction
o   Button, TextField, Label, Menu, PopupMenu etc.
-          Supporting classes are additional classes that support the components and containers
o   Color, Font, Dimension etc.
-          All components and containers are inherited from Component class. It is abstract class that provide common method to all component and containers.
o   void setSize(int w, int h)
o   void setVisible(boolean b)
o   void setEnabled(boolean b)
o   void setForeground(Color c)
o   void setBackground(Color c)
o   void setLocation(int x, int y)

Example
Create a desktop application having frame with size 300x300 and background color as Red.

Color class

-          Provides a set of colors
o   red
o   green
o   blue
o   etc.
-          Use as Color.red, Color.green etc.
-          Create a color using constructor
o   Color(int red, int green, int blue)
o   Minimum value can be 0 and Maximum as 255


Object à Component àContainer àWindow à  Frame

Methods of Frameclass

-          setTitle(String title)
-          setResizeable(boolean value)




Example 1
import java.awt.*;
class FirstApp extends Frame
{
            public FirstApp()
            {
                        setSize(300,300);
                        setBackground(Color.red);
                        setTitle("First Application");
                        setLocation(200,200);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new FirstApp();
            }
}

General component classes

  1. Label for static text
  2. Button for push button
  3. TextField for single line text and password field
  4. TextArea for multi line text
  5. Choice for drop down list
  6. List for multiple selection
  7. Checkbox for check box and radio buttons
  8. Menu for drop down menu
  9. PopupMenu
  10. MenuItem for items in Menu or PopupMenu
  11. MenuBar

Label class
-          To create a fixed text
o   Label()
o   Label(String text)
o   void setText(String text)
o   String getText()

TextField class
-          To create single line text box and password field
o   TextField()
o   TextField(int columns)
o   void setText(String text)
o   String getText()
o   void setEditable(boolean value)
o   void setEchoChar(char ch)
§  To set character for password


Button class
-          To create a push button
o   Button(String label)
o   void setLabel(String label)
o   String getLabel()


Note:
  1. One more class called as Container provides all common method for all the containers

            public void add(Component c)

  1. To set the layout of components inside a container use special classes called layout managers
    1. public void setLayout(LayoutManager lm)
                                                              i.      BorderLayout – default for Frame and Panel
                                                            ii.      FlowLayout – default for Applet
                                                          iii.      GridLayout
                                                          iv.      GridBagLayout
                                                            v.      CardLayout

Example
            setLayout(new FlowLayout());


07.09.2010
Event Handing in Java

-          An event is a moment generated using keyboard, mouse or some system activity
-          All events are implemented as abstract method inside some interfaces known as listeners
o   ActionListener
o   MouseListener
o   MouseMotionListener
o   KeyListener
o   WindowListener
o   AdjumstmentListener
o   ItemListener
o   Etc.
-          All such interfaces are provided under java.awt.event package
-          ActionListeners
o   Generally used with Button, MenuItem etc.
-          MouseListener
o   Generally work on any control when mouse is pressed or released
-          MouseMotionListener
o   Used when moving a mouse pointer on some control simply or dragging and item
-          KeyListener
o   Use with key functions
-          AdjustmentListener
o   Use with Scrollbars and Sliders
-          ItemListener
o   used when an item get selected like Checkbox, Radio button, List etc.

All such interfaces provides fixed set of abstract methods

ActionListener
            public void actionPerformed(ActionEvent e)

KeyListener
            public void keyTyped(KeyEvent e)
            public void keyPressed(KeyEvent e)
            public void keyReleased(KeyEvent e)

Java uses Event Delegation Model for Event Handling.

Note: Here ActionEvent, KeyEvent etc. are the classes that called as delegates. They provides built-in method to find the current control on which an activity has done or some additional information.

Example
            ActionEvent class provides methods
                        Object getSource()
                        String getActionCommand()
            MouseEvent class provides methods
                        int getX()  - to get x coordinate
                        int getY() – to get y coordinate
                        boolean isPopupTrigger()  - to trap the right click
            KeyEvent class provides methods
                        char getKeyChar() – to get a typed character
                        void consume()
                                    To don’t display the input character in text box
                       
First we need to register an event on a control using addXXXListener() name

            Controlname.addActionListener(object of the class having overridden method);




09.09.2010

Different places to implement the methods of listeners

  1. Same class
  2. Inside an inner class
  3. Inside an external class
  4. Inside Anonymous class

Method 1
Same class means implement the listener in same class and override the methods in same class.

Test Case
Create a class Sample having a frame and show the current mouse position top of the form by implementing the MouseMotionListener in same class.

Delegate : MouseEvent
Methods :
            public void mouseMoved(MouseEvent e)
            public void mouseDraged(MouseEvent e)

Method of MouseEvent class
int getX()  - to get x coordinate
            int getY() – to get y coordinate
            boolean isPopupTrigger()  - to trap the right click


Program Code
import java.awt.*;
import java.awt.event.*;
class Sample extends Frame implements MouseMotionListener
{
            public Sample()
            {                     

                        addMouseMotionListener(this);

                        setSize(300,300);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new Sample();
            }
            public void mouseMoved(MouseEvent e)
            {
                        setTitle(e.getX()+","+e.getY());         
            }
            public void mouseDragged(MouseEvent e)
            {
            }
}


Using an Inner class

-          A class within a class is called as inner class
-          It can access all the member of containing class but containing class cannot access members of inner class
-          It is best used for categorization of information

import java.awt.*;
import java.awt.event.*;
class Sample extends Frame
{
            public Sample()
            {                     

                        addMouseMotionListener(new Events());

                        setSize(300,300);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new Sample();
            }
           
            class Events implements MouseMotionListener
            {
                        public void mouseMoved(MouseEvent e)
                        {
                                    setTitle(e.getX()+","+e.getY());         
                        }
                        public void mouseDragged(MouseEvent e)
                        {
                        }
            }
}

Using Adapter classes

-          Special classes corresponding to listeners
-          Listeners having only one method do not have their adapter classes
o   MouseAdapter
o   MouseMotionAdapter
o   KeyAdapter
o   WindowAdapter
-          They have pre-overridden methods of child a listener with blank body
-          We can override only those method that we need and no need to override all methods of a class
-          They are best used with inner classes

import java.awt.*;
import java.awt.event.*;
class Sample extends Frame
{
            public Sample()
            {                     

                        addMouseMotionListener(new Events());
                        addWindowListener(new WindowEvents());

                        setSize(300,300);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new Sample();
            }
           
            class Events extends MouseMotionAdapter
            {
                        public void mouseMoved(MouseEvent e)
                        {
                                    setTitle(e.getX()+","+e.getY());         
                        }
            }
            class WindowEvents extends WindowAdapter
            {
                        public void windowClosing(WindowEvent e)
                        {
                                    System.exit(0);
                        }         
            }
}


Using Listeners/Adapters in External class

-          If using external class some times we need to pass reference of current frame or some other control

import java.awt.*;
import java.awt.event.*;
class Sample extends Frame
{
            public Sample()
            {                     

                        addMouseMotionListener(new Events(this));//reference
                        addWindowListener(new WindowEvents());

                        setSize(300,300);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new Sample();
            }
           
           
           
}

class Events extends MouseMotionAdapter
            {
                        Frame f;
                        public Events(Frame f) //reference
                        {         
                                    this.f=f;
                        }
                        public void mouseMoved(MouseEvent e)
                        {
                                    f.setTitle(e.getX()+","+e.getY());      
                        }
            }

class WindowEvents extends WindowAdapter
            {
                        public void windowClosing(WindowEvent e)
                        {
                                    System.exit(0);
                        }         
            }


Anonymous class

-          A class without any name is called as anonymous class
-          Such classes get created while implementing a method during registration of a listener

import java.awt.*;
import java.awt.event.*;
class Sample extends Frame
{
            public Sample()
            {                     

                        addMouseMotionListener(new MouseMotionAdapter()
                        {
                                    public void mouseMoved(MouseEvent e)
                                    {
                                                setTitle(e.getX()+","+e.getY());         
                                    }
           
                        });
                        addWindowListener(new WindowAdapter()
                        {
                                    public void windowClosing(WindowEvent e)
                                    {
                                                System.exit(0);
                                    }                     
                        });


                        setSize(300,300);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new Sample();
            }
           
           
           
}

Best combination is Inner class with Adapter or Anonymous class with adapter


TextArea class
-          To create multi-line text box
o   TextArea(int rows, int columns)
o   void setText(String text)
o   String getText()

Choice class
-          To create a drop down list
o   Choice()
o   void add(String s)
o   String getSelectedItem()
o   int getSelectedIndex()

Checkbox class
-          To create a checkbox and a radio button
-          For Checkbox: To select none or all
o   Checkbox(String text)
o   Checkbox(String text, boolean selected)
-          Listener
o   ItemListener
§  public void itemStateChanged(ItemEvent e)
·         Method of ItemEvent
o   boolean getState()



Creating Radio Buttons

-          To select only one item from Group
-          Use CheckboxGroup class to make groups
o   Checkbox(String text, CheckboxGroup cg, boolean selected)


Example
CheckboxGroup gender=new CheckboxGroup();
Checkbox male=new Checkbox("Male",gender,true);
Checkbox female=new Checkbox("Female",gender,false);

List class

-          Allows to select one or more item
o   List()
o   List(int size)
o   List(int size, boolean multiple)
o   void add(String item)
o   String [] getSelectedItems()

Creating Menus

Can be of two types
  1. Drop down menu
  2. Popup Menu

Drop Menu Menu
            Menubar àMenu  à MenuItem

Menu class
-          To create a menu
o   Menu(String text)
o   void add(Menu m)
o   void add(MenuItem m)

MenuItem class
-          To create a menu item
o   MenuItem(String text)

Using setMenuBar() methof Frame class to add a menu

Example
                        Menu file=new Menu("File");
                        Menu edit=new Menu("Edit");
                        MenuItem minew=new MenuItem("New");
                        MenuItem misave=new MenuItem("Save");
                        MenuItem micut=new MenuItem("Cut");
                        MenuItem micopy=new MenuItem("Copy");
                        MenuItem mipaste=new MenuItem("Paste");
                       
                        file.add(minew);file.add(misave);
                        edit.add(micut);edit.add(micopy);edit.add(mipaste);
                       
                        MenuBar mb=new MenuBar();
                        mb.add(file);mb.add(edit);
                        setMenuBar(mb);


Creating PopupMenu

-          Use PopupMenu class
-          First create a popup menu and add into a frame
-          Trap the right click on a control to show the popup menu
o   Use isPopupTrigger() method of MouseEvent class to trap the right click
§  public boolean isPopupTigger()
-          If right click pressed then show the popup menu at the location where mouse was pressed
o   show(Component c, int x, int y)

import java.awt.*;
import java.awt.event.*;
class PopupMenuTest extends Frame
{
            PopupMenu pm;
            public PopupMenuTest()
            {
                        pm=new PopupMenu();
                        MenuItem red=new MenuItem("Red");
                        MenuItem blue=new MenuItem("Blue");
                        MenuItem green=new MenuItem("Green");
           
                        pm.add(red);
                        pm.add(green);
                        pm.add(blue);

                        add(pm);
                        addMouseListener(new MouseAdapter()
                        {
                                    public void mouseReleased(MouseEvent e)
                                    {
                                                if(e.isPopupTrigger())
                                                {
                                                            pm.show(e.getComponent(),e.getX(), e.getY());       
                                                }
                                    }         
                        }
                        );
                       
                        setSize(300,300);
                        setVisible(true);
                                   
            }
            public static void main(String args[])
            {
                        new PopupMenuTest();
            }
}

Placing controls at specified positions

-          First remove the layout manager
o   setLayout(null);
-          Define the location and size of controls using setBounds() method
o   void setBounds(int x, int y, int w, int h)


import java.awt.*;
class TestWindow extends Frame
{
            Label l1;
            TextField t1;
            Button b1;
            public TestWindow()
            {
                        l1=new Label("Number");
                        t1=new TextField(10);
                        b1=new Button("Square");
                       
                        l1.setBounds(20,50,80,20);
                        t1.setBounds(110,50,100,20);
                        b1.setBounds(110,80,80,20);

                        setLayout(null);
                        add(l1);add(t1);add(b1);
                        setSize(250,200);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new TestWindow();
            }
}

Note: While using big projects it is very difficult to remember the simple control names like b1, b2 etc.
Better to use the Hungarian Notation given by Charles Simony of Hungary. It states that use three character prefix to define the type of control along with purpose of control.

            Button àcmd
            TextField àtxt
            Checkbox àchk


Java Database Connectivity (JDBC)

-          Java is a front-end that can be connected to any back-end
-          To connect with database we need to some classes and interfaces provided under java.sql and javax.sql package
-          To connect with some database with special classes called as drivers
o   For example
§  JDBC-ODBC Bridge driver for any database
·         sun.jdbc.odbc.JdbcOdbcDriver
§  My Sql Driver
·         com.mysql.jdbc.Driver
-          First we need to load a driver
o   Use any of three methods
§  Class.forName("classsname");
§  DriverManager.registerDriver(new classname());
§  System.setProperty("jdbc.drivers","classname");
-          Define the URL to reach the database along with some login and password and get reference of that database. Reference get managed by an interface Connection
o   Connection cn=DriverManager.getConnection("url","login","password");
-          Create the SQL Statement to be executed
o   String sql=”INSERT INTO tablename VALUES(…)”;
-          To execute the commands three interface help us
o   Statement
o   PreparedStatement
o   CallableStatement

14.09.2010

Test Software: Blood Bank Management System
  1. Blood Groups
    1. bgid – Numeric – Auto Generated - PK
    2. bgname - Text
  2. Donors
    1. did – Numeric – Auto Generated
    2. dname
    3. demail
    4. dmobile
    5. bgid - FK
    6. dunits
  3. Patients
    1. Pid
    2. pname
    3. pname
    4. pmobile
    5. cunits
  4. Hospitals
  5. Doctor

Example
Using MS Access as Database

-          First create a database file
o   E.g. batch27db.mdb
-          Create your tables
-          Setting the relationship for primary and foreign key
o   Tools àRelationship
-          Create Data entry form for Blood Group
-          Create a DSN (Data Source Name) for your database file
o   Control Panel àAdministrative Tools à ODBC à System DSN
o   Add… àMicrosoft Access Driver (*.mdb) for 2003 or Microsoft Access Driver (*.mdb;*.accdb) for 2007 and 2010
o   Select your database and give some DSN name
§  E.g. b27access



Now create the SQL Statement to insert the blood group

String sql="INSERT INTO bloodgroups(bgname) VALUES('"+txtBGName.getText()+"')";

Load the Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Establish the connection
           
Connection cn=DriverManager.getConnection("jdbc:odbc:b27access");

Create an object to execute the SQL Command and give reference to Statement interface
Statement st=cn.createStatement();

Execute the SQL Command using Statement reference
-          Use methods depending on type of SQL Statement to be SELECT or NON-SELECT
o   executeUpdate()
o   executeQuery()


Example
st.executeUpdate(sql);

Close the connection


16.09.2010

Using PreparedStatement

-          Use prepareStatement() method of Connection interface

PreparedStatement ps=cn.prepareStatement(sql);

-          The SQL statement can be of two types
o   SELECT based
o   NON-SELECT based
-          To run the SELECT command use executeQuery() method
-          To run the NON-SELECT command use executeUpdate() method
-          To hold reference of records use ResultSet interface
o   ResultSet executeQuery()
o   int executeUpdate()
-          Use methods of ResultSet to get the result
o   boolean first()
o   boolean last()
o   boolean previous()
o   boolean next()
-          To read the values from current record use getter methods
o   getString()
o   getInt()
o   getDouble()
o   getDate()
-          Pass the column index or column name to get the data
o   Start the column index from 1 rather than 0


Using Place Holders in SQL Statements

-          Use ? in place of data
-          Provide the data later on using setter methods
o   setInt(columno,data)
o   setString()
o   setFloat()
o   setDouble()
o   setDate()



21.09.2010

Java Applets

-          A Java class that resides on some web server and can be accessed anywhere using a web browser
-          To run the Java applet the browser must be Java-enabled
-          Each Java class to be called as Applet must inherit from Applet class of java.appletpackage
-          No entry point or constructor required
-          Applet class provides its own method to be overridden
o   public  void init()
§  Executes only for once for initialization
o   public void paint(Graphics g)
§  To drawing string, shapes and image on applet
§  Use Graphics of java.awt package for all the operations
-          It must be declared as public
-          To merge the Java Applets into HTML code use <APPLET> tag
-          <APPLET></APPLET> provides some attributes
o   code="classname"
o   width="x"
o   height="y"
o   codebase="folder name having class f iles"
o   archive="JAR file name"
-          It also provides a sub tag <PARAM> to pass parameters to the applet
-          It has two attributes   
o   name=”parameter name”
o   value=”parameter value”

Working with Graphics class

            public void drawString(String s, int x, int y)
            public void drawLine(int x1, int y1, int x2, int y2)
            public void drawImage(Image img, int x, int y, reference of applet)
            public void drawImage(Image img, int x, int y, int w, int h, reference of applet)


Creating First Applet

Create an applet having a number and result text boxes with a button Square.

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class FirstAppletTest extends Applet
{
            Label l1,l2;
            TextField t1,t2;
            Button b1;
            public void init()
            {
                        l1=new Label("Number");
                        l2=new Label("Result");
                        t1=new TextField(10);
                        t2=new TextField(10);
                        b1=new Button("Square");

                        b1.addActionListener(new ActionListener()
                        {
                                    public void actionPerformed(ActionEvent e)
                                    {
                                                int num=Integer.parseInt(t1.getText());
                                                int sq=num*num;
                                                t1.setText(Integer.toString(sq));
                                    }
                        });

                        add(l1);add(t1);
                        add(l2);add(t2);
                        add(b1);
                       
            }
}


Creating the HTML file (FirstAppletTest.htm)

<applet code="FirstAppletTest" width="200" height="150">
</applet>

Running the Applet

-          Use any of two methods
o   Using Browser
-          Using AppletViewer tool of JDK

AppletViewer FirstAppletTest.htm

Placing class files in separator folder

-          Create a folder to contain the class files e.g. classes
-          Use CODEBASE attribute

<applet code="FirstAppletTest" width="200" height="150" codebase="classes">
</applet>

Creating JAR (Java Archive) files

Use JAR.EXE tool with options

            c àcreate
            v àverbose
            x àextract
            t àTabulate
            m àManifest file
            f àFile name

To create a JAR file
            JAR cvf test.jar *.class

To view contents inside a JAR file
            JAR tvf test.jar

To extract a JAR file
            JAR xvf test.jar


Using JAR file with <APPLET> Tag

-          Use ARCHIVE attribute of <APPLET> tag

<applet code="FirstAppletTest" width="200" height="150" codebase="classes" archive="test.jar">
</applet>

-          It is also called Applet Optimization

Using Graphics class

-          Create an applet to draw string message on applet


import java.awt.*;
import java.applet.*;
public class GraphicsApplet extends Applet
{
            public void paint(Graphics g)
            {         
                        setBackground(Color.blue);
                        g.setColor(Color.white);
                        g.drawString("Hi to all",20,20);
            }
}
           

Passing Parameters to Applets

-          Use <PARAM> tag with attributes NAME and VALUE to pass data to some applet
-          Use getParameter() method of Applet class to read the data send by <PARAM> tag
o   String getParameter(String parametername)



<applet code="GraphicsApplet" width="100" height="100">
            <param name="message" value="Kaise Ho">
</applet>


Using Images into Applets

-          Get an image from the server folder into memory using getImage() method of Applet class
o   Image getImage(URL path, String filename)
-          To make the URL use any of two methods of Applet class
o   URL getCodeBase()
§  Returns the path of the folder containing the class files
o   URL getDocumentBase()
§  Returns the path of folder containing the HTML files


import java.awt.*;
import java.applet.*;
public class ParamApplet extends Applet
{
            Image img;
            public void init()
            {
                        String fname=getParameter("photo");
                        img=getImage(getDocumentBase(),   fname);           
            }
            public void paint(Graphics g)
            {         
                        g.drawImage(img,0,0,this);                
            }
}
           


25.09.2010
Working with repaint()

-          A method that calls paint() again
-          Another method works behind the scene called as update()

Example
Create an applet to show the current mouse position with the pointer


Multi Threadings

A light weight process within a process is called as thread. It utilize the resources of main process.

A thread has its own life cycle

  1. Born State
  2. Ready State
  3. Running State
  4. Block State
  5. Dead State

Use Thread class to create a thread and use run() method of Runnableinterface to provide working to the thread

All Java program are Single threaded by default. One thread is always present called as main thread


Use currentThread()method of Thread class to get reference of currently thread

Methods of Thread class

            Constructors
                        Thread(Runnable r)
                        Thread(Runnable r, String name)

                        static Thread currentThread()
                       
                        String getName()
                        void setName(String s)
                        int getPriority()
                        void setPriority(int n)
                                    Min is 1 and Max is 10 Default is 5

                        public void start() – to send the thread in thread queue
                        public void sleep(int ms) throws InterruptedException
                        public void sleep(int ms,int ns) throws InterruptedException

Testing for main thread

class ThreadTest
{
                public static void main(String args[])
                {
                                Thread t=Thread.currentThread();
                                System.out.println("Current Thread Name : "+t.getName());
                                System.out.println("Prioirty : "+t.getPriority());
                }
}
                                           

Creating Multiple Threads with different functionalities

//Assigning different task for different threads for different timing
class MyThread implements Runnable
{

            public MyThread(String name)
            {
                        Thread t=new Thread(this,name);
                        t.start();
            }


            public void run()
            {
                        String s=Thread.currentThread().getName();
                        if(s.equals("Vikas"))
                        {

                                    for(int i=1;i<=10;i++)
                                    {
                                                System.out.println(s+" : "+i);
                                                try
                                                {
                                                            Thread.sleep(2);
                                                }catch(InterruptedException ex)
                                                {         
                                                }
                                    }
                        }
                        else if(s.equals("Amit"))
                        {
                                    for(int i=10;i<=100;i+=5)
                                    {
                                                System.out.println(s+" : "+i);
                                                try
                                                {
                                                            Thread.sleep(1);
                                                }catch(InterruptedException ex)
                                                {         
                                                }
                                    }
           
                        }
                        else
                        {
                                    for(char ch='A';ch<='Z';ch++)
                                    {
                                                System.out.println(s+" : "+ch);
                                                try
                                                {
                                                            Thread.sleep(1);
                                                }catch(InterruptedException ex)
                                                {         
                                                }
                                    }
                        }
            }

            public static void main(String args[])
            {
                        MyThread t1=new MyThread("Vikas");
                        MyThread t2=new MyThread("Amit");
                        MyThread t3=new MyThread("Neeraj");
            }
}


Applications of Threading

It is mainly used to setup some task to be executed after fix interval of time.

Example
Create an applet to show the images after 1 second.


import java.awt.*;
import java.applet.*;
public class ThreadApplet extends Applet implements Runnable
{
            int i;
            public void init()
            {
                        Thread t=new Thread(this);
                        t.start();          
                        i=1;
            }
            public void run()
            {
                        for(;;)
                        {
                                    try
                                    {
                                                Thread.sleep(1000);
                                    }catch(InterruptedException ex)
                                    {
                                                System.out.println("error : "+ex);
                                    }
                                    repaint();
                                   
                        }                     
            }
            public void paint(Graphics g)
            {
                        String imgname="images/"+i+".jpg";
                        Image img=getImage(getDocumentBase(),imgname);
                        g.drawImage(img,0,0,this);
                        i++;
                        if(i==7) i=1;
            }
}


Exception Handling

-          Each exception is a class inherited from Exception class that is used to handle the runtime errors
-          It is a system to send an error message from the place an error has occurred to the place a method get called

Object à Throwable à Exception, Error

-          Exception class provides common methods for all exception kind of classes
1.      String getMessage()
1.      Only Message
2.      String toString()
1.      Message with exception class name
3.      void printStackTrace()
1.      Full stack of exceptions

-          Java provides five keywords for exception handling
1.      try
2.      catch
3.      finally
4.      throw
5.      throws
-          try-catch is a block of statements to try the commands and trap the runtime errors
-          finally is again a block to always execute some code irrespective of an error
-          A try can have many catch statements but only one finally block

Example
Write a program to input two numbers and print division that numbers.

import java.io.*;
class ExpTest
{
            public static void main(String args[])
            {
                        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        try
                        {
                                    System.out.print("Enter two numbers : ");
                                   
                                    int a=Integer.parseInt(br.readLine());
                                    int b=Integer.parseInt(br.readLine());
                                    int c=a/b;
                                    System.out.println("Division is "+c);
                        }catch(IOException ex)
                        {
                                    System.out.println("Error : "+ex.getMessage());
                        }
                        catch(NumberFormatException ex)
                        {
                                    System.out.println("Sorry! Only numbers are allowed");
                        }
                        catch(ArithmeticException ex)
                        {
                                    System.out.println("Sorry! Denominator cannot be zero");
                        }
                        catch(Exception ex)
                        {
                                    System.out.println("Sorry! Some error has occured. Call on 898989888");
                                    //ex.printStackTrace();
                        }         
                        finally
                        {
                                    System.out.println("Bye Bye");
                        }
            }
}


throw keyword is used to throw an object of some exception kind of class.
throws keyword is used to indicate the compiler that a method throws some exception


Creating our own exceptions

-          Create an exception kind of class and inherit this class with Exception class
1.      Override getMessage() and toString() methods
-          When some kind of error occurs, throw an object of such class using throw keyword and indicate it using throws keyword
-          Use try-catchat the place such method get used



class LowBalanceException extends Exception
{
            public String getMessage()
            {
                        return "Sorry! Low Balance.... Unable to withdraw";           
            }
            public String toString()
            {
                        return "LowBalanceException: Sorry! Low Balance.... Unable to withdraw";
            }
}

class Customer
{
            int acno,balance;
            String name;
            public Customer(int acno, String name, int opamount)
            {
                        this.acno=acno;
                        this.name=name;
                        this.balance=opamount;
            }
            public void deposit(int amount)
            {
                        balance+=amount;
            }
            public void withdraw(int amount) throws LowBalanceException
            {
                        if(amount>balance)
                                    throw new LowBalanceException();

                        balance-=amount;
            }
            public void showBalance()
            {
                        System.out.println("Current Balance is "+balance);
            }
}

class SBI
{
            public static void main(String args[])
            {
                        Customer c=new Customer(124,"Rajesh Sharma",9000);
                        c.showBalance();
                        c.deposit(4000);
                        c.showBalance();
                        try
                        {
                                    c.withdraw(70000);
                        }catch(LowBalanceException ex)
                        {
                                    System.out.println(ex.getMessage());
                        }
                        c.showBalance();
            }
}



String Handling

-          A system to manage the strings
-          Strings can be of two types
1.      Mutable or Expandable
2.      Immutable or Fixed size
-          Immutable strings are managed by String class and mutable strings are managed by StringBuffer and StringBuilder class
-          StringBuffer manages strings with serialization while StringBuilder do not
-          Immutable String can be create using two methods
1.      Using Literal
1.      String name="Vikas";
2.      Using Object
1.      String name=new String("Vikas");


Example 1 : Value Comparison

class StringTest
{
            public static void main(String args[])
            {
                        String x="Vikas";
                        String y="Vikas";
                        if(x==y)
                                    System.out.println("Both are equal");
                        else
                                    System.out.println("They are different");
            }
}

Example 2: Address Comparison
class StringTest
{
            public static void main(String args[])
            {
                        String x=new String("Vikas");
                        String y=new String("Vikas");
                        if(x==y)
                                    System.out.println("Both are equal");
                        else
                                    System.out.println("They are different");
            }
}

Example 3: Value at the address comparison

-          To get value from an address use Equals() method of Strings



class StringTest
{
            public static void main(String args[])
            {
                        String x=new String("Vikas");
                        String y=new String("Vikas");
                        if(x.equals(y))
                                    System.out.println("Both are equal");
                        else
                                    System.out.println("They are different");
            }
}


String class provides various methods

-          int length()
1.      returns length of string
-          String toUpperCase()
-          String toLowerCase()
-          int indexOf(String s)
1.      To search a string into another string
2.      Returns -1 if not found
-          String substring(int start, int end)
1.      return end-start number of characters
-          char charAt(int index)
1.      To get a character from given index

Example
class StringMethods
{
            public static void main(String args[])
            {
                        String name="Vikas Verma";
                        System.out.println("Length is "+name.length());
                        System.out.println("Upper case : "+name.toUpperCase());
                        System.out.println("Lower Case : "+name.toLowerCase());
                        int n=name.indexOf("Verma");
                        System.out.println("Position of verma is : "+n);
                        System.out.println("1 to 4 is : "+name.substring(1,4));
            }
}


Using StringBuffer/StringBuilder classes

-          Both of the classes provide append() to append the data in same memory space without losing any memory
-          It also allows to reverse the data using reverse() method




class StringBuilderTest
{
      public static void main(String args[])
      {
                  StringBuilder sb=new StringBuilder();
                  sb.append("Vikas ");
                  sb.append("Kumar");
                  String s=sb.reverse().toString();
                  System.out.println(s);
     
      }
}


05.10.2010

Collections and Utilities
Generics
Auto Boxing and Unboxing
File Input/Output

Collections

-          Special classes that allows to hold dynamic set of objects
-          All such classes are provided under java.util package
-          Collections are of two types
o   Legacy Collections
o   Framework based collections

Legacy collections

-          Classes provided from Java 1.0
-          Every class has its own set of field and methods
o   Vector class
§  A set of objects
o   Hashtable class
§  A set of key/value pairs
o   Enumeration interface

Framework based collection

-          framework based collections follow the hierarchy and rules
-          Provided from 1.2 version
o   Collection interface
§  List interface
·         Allows duplicate value
§  Set interface
·         Never allows duplicate values
§  Map interface
·         Holds key/value pair
-          Examples
o   ArrayList, LinkedList
o   HashSet
o   HashMap



Vector class

-          To manage a set of objects
o   Vector()
o   void addItem(Object x)
o   Object elementAt(int index)
o   int size()


import java.util.*;
class VectorTest
{
            public static void main(String args[])
            {
                        Vector v=new Vector();
                        v.addElement(new Integer(56));
                        v.addElement(new Float(4.5f));
                        v.addElement(new Double(4.8));
                        v.addElement("Hi to all");
                       
                        for(int i=0;i<v.size();i++)
                        {
                                    System.out.println(v.elementAt(i));
                        }
            }
}


Note: To read specific kind of elements from a collection use instanceof operator to compare type of element.

import java.util.*;
class VectorTest
{
            public static void main(String args[])
            {
                        Vector v=new Vector();
                        v.addElement(new Integer(56));
                        v.addElement(new Integer(33));
                        v.addElement(new Float(4.5f));
                        v.addElement(new Double(4.8));
                        v.addElement("Hi to all");
                       
                        //to print only Integer type elements
                        for(int i=0;i<v.size();i++)
                        {
                                    if(v.elementAt(i) instanceof Integer)
                                                System.out.println(v.elementAt(i));
                        }
            }
}


Note: if reading value from an object, first convert data from object type to some other type then read the value from that class type.

Write a program to manage dynamic number of integers and print sum of those number

import java.util.*;
class DynamicNumbers
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(System.in);
                        Vector v=new Vector();
                        String ans;
                        System.out.println("Enter some numbers : ");
                        while (true)
                        {
                                    int num=sc.nextInt();
                                    v.addElement(new Integer(num));
                                    System.out.print("Add More [y/n] : ");
                                    ans=sc.next().toUpperCase();
                                    if(ans.equals("N"))
                                                break;
                        }
                        int s=0;
                        for(int i=0;i<v.size();i++)
                        {
                                    Integer x=(Integer)v.elementAt(i);
                                    s=s+x.intValue();
                        }
                       
                        System.out.println("Sum is "+s);
                       
                       
                       
            }
}


Hashtable class

-          To manage key/value pairs
o   Hashtable()
o   void put(Object key, Object value)
o   Object get(Object key)
o   Enumeration keys()

Enumerationinterface

-          An interface to hold reference of some keys
o   boolean hasMoreElements()
o   Object nextElement()

import java.util.*;
class HashtableTest
{
            public static void main(String args[])
            {
                        Hashtable t=new Hashtable();
                        t.put("in","India");
                        t.put("pk","Pakistan");
                        t.put("ch","China");
                       
                        System.out.println(t.get("pk"));
            }
}


import java.util.*;
class HashtableTest
{
            public static void main(String args[])
            {
                        Hashtable t=new Hashtable();
                        t.put("in","India");
                        t.put("pk","Pakistan");
                        t.put("ch","China");
                       
                        Enumeration e=t.keys();
                        while (e.hasMoreElements())
                        {
                                    Object key=e.nextElement();
                                    System.out.println(key+"="+t.get(key));
                        }
            }
}


Generics

-          A collection of classes that define the type of element inside an object while creating an object
-          Example
o   ArrayList
o   LinkedList
o   Etc.



ArrayList class

-          ArrayList()
-          void add(Object x)
-          Object get(int index)
-          int size()

import java.util.*;
class ArrayListTest
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(System.in);
                        ArrayList <Integer> v=new ArrayList<Integer>();
                        String ans;
                        System.out.println("Enter some numbers : ");
                        while (true)
                        {
                                    int num=sc.nextInt();
                                    v.add(new Integer(num));
                                    System.out.print("Add More [y/n] : ");
                                    ans=sc.next().toUpperCase();
                                    if(ans.equals("N"))
                                                break;
                        }
                        int s=0;
                        for(int i=0;i<v.size();i++)
                        {
                                    s=s+v.get(i).intValue();
                        }
                       
                        System.out.println("Sum is "+s);
            }
}


Auto Boxing and Unboxing

-          Gives automatic conversion from value type to reference type and vice versa

Integer x=5; // auto boxing – conversion from value type to reference type

int k=6+x; // auto un-boxing – conversion from reference type to value type



import java.util.*;
class AutoBoxingUnBoxing
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(System.in);
                        ArrayList <Integer> v=new ArrayList<Integer>();
                        String ans;
                        System.out.println("Enter some numbers : ");
                        while (true)
                        {
                                    int num=sc.nextInt();
                                    v.add(num); //auto boxing
                                    System.out.print("Add More [y/n] : ");
                                    ans=sc.next().toUpperCase();
                                    if(ans.equals("N"))
                                                break;
                        }
                        int s=0;
                        for(int i=0;i<v.size();i++)
                        {
                                    s=s+v.get(i); // auto unboxing
                        }
                       
                        System.out.println("Sum is "+s);
            }
}


Using for-each loop

-          A new loop to work with a array and collection without knowing size of array and collection
-          Here we do not need any array indexing


for(datatype variable : array or collection name)
{
            //statements
}


Example 1
class ForEachTest
{
            public static void main(String args[])
            {
                        int []ar={6,7,8,3,55,7,23,5};
                        int s=0;
                        for(int n : ar)
                        {
                                    s+=n;
                                    System.out.println(n);
                        }
                        System.out.println("Sum is : "+s);
            }
}

Example 2

import java.util.*;
class ArrayListTest
{
            public static void main(String args[])
            {
                        Scanner sc=new Scanner(System.in);
                        ArrayList <Integer> v=new ArrayList<Integer>();
                        String ans;
                        System.out.println("Enter some numbers : ");
                        while (true)
                        {
                                    int num=sc.nextInt();
                                    v.add(num);
                                    System.out.print("Add More [y/n] : ");
                                    ans=sc.next().toUpperCase();
                                    if(ans.equals("N"))
                                                break;
                        }
                        int s=0;
                        for (int x : v)
                        {
                                    s=s+x;
                        }
                        System.out.println("Sum is "+s);
            }
}


LinkedList

import java.util.*;
class LinkedListTest
{
            public static void main(String args[])
            {
                        LinkedList <String>l=new LinkedList<String>();
                        l.add("Amit");
                        l.add("Vikas");
                        System.out.println(l);
                        l.addFirst("Neeraj");
                        l.addLast("Rahul");
                        System.out.println(l);
                        l.set(3,"Keshav");
                        System.out.println(l);
                        Collections.sort(l);
                        System.out.println(l);
            }
}

Stack

-          To manage data in LIFO method
o   push(Object x)
§  To add items
o   Object pop()
§  To read and delete the topmost item
o   Object peek()
§  To read the topmost item but don’t delete


import java.util.*;
public class StackTest{
            public static void main(String args[])
            {
                        Stack st=new Stack();
                        st.push(new Date());
                        st.push(new Integer(5));
                        st.push(new Float(67.55));
                        System.out.println(st.toString());
                        System.out.println(st.pop());
                        System.out.println(st.toString());
                        System.out.println(st.peek());
                        System.out.println(st.toString());

            }
}


Working with Files

-          Allows to work with files and folder
-          Also allows to create new files

File class
-          To work with existing files and folders
-          Allows to create, rename, remove the folders
-          Allows to rename and remove the files
-          Allows to view contents inside a folder

File(String filename with path)
File(String folder, String filename)

boolean exists()
boolean isFile()
boolean isFolder()
long length()
long lastModified()
String []list()
boolean mkdir() – to create a single folder
boolean mkdirs() – to create a folder as tree or single folder


import java.io.*;
import java.util.*;
class FileTest
{
            public static void main(String args[])
            {
                        File f=new File("F:/Batches2010/27");
                        if(f.exists())
                        {
                                    System.out.println("Found");
                                    if(f.isFile())
                                    {
                                                System.out.println("It is a file");        
                                                System.out.println("Size : "+f.length());
                                                System.out.println("Last Modified : "+ new Date(f.lastModified()));
                                    }
                                    else
                                    {
                                                System.out.println("It is a folder");
                                                String []s=f.list();
                                                for(String x : s)
                                                            System.out.println(x);
                                    }
                       
                        }
                        else
                        {
                                    System.out.println("Not found");
                        }
                       
            }
}


File Operations can be of two types
  1. Text mode
  2. Binary Mode



Working with text files

Using classes
  1. FileWriter
    1. To save the file
  2. FileReader
    1. To read the file

//Writing contents to a file
import java.io.*;
class SaveTextFile
{
            public static void main(String args[]) throws Exception
            {
                        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        FileWriter fw=new FileWriter("mydata.txt");
                        String s;
                        for(;;)
                        {
                                    System.out.println("Add a string ('done' when finished) : ");
                                    s=br.readLine();
                                    if (s.equals("done"))
                                    {
                                                fw.close();
                                                break;
                                    }
                                    fw.write(s+"\n");
                        }
                       
            }
}

//Reading contents of a flie
import java.io.*;
class ReadTextFile
{
            public static void main(String args[]) throws Exception
            {
                        FileReader fr=new FileReader("mydata.txt");
                        BufferedReader br=new BufferedReader(fr);
                        String s;
                        while ((s=br.readLine())!=null)
                        {
                                    System.out.println(s);
                        }
                        fr.close();
            }
}


Working with Binary Mode

-          Use classes
o   FileOutputStream
o   FileInputStream
-          Before writing string data to a file, it must be converted to byte array
-          Use getBytes()  method of String class to convert data into byte array
o   byte [] getBytes()

//Writing contents to a file
import java.io.*;
class SaveTextFile
{
            public static void main(String args[]) throws Exception
            {
                        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
                        FileOutputStream fw=new FileOutputStream("mydata.dat");
                        String s;
                        for(;;)
                        {
                                    System.out.println("Add a string ('done' when finished) : ");
                                    s=br.readLine();
                                    if (s.equals("done"))
                                    {
                                                fw.close();
                                                break;
                                    }
                                    s=s+"\n";
                                    fw.write(s.getBytes());
                        }
                       
            }
}

//Reading data from a binary file
import java.io.*;
class ReadBinaryData
{
            public static void main(String args[]) throws Exception
            {
                        FileInputStream f=new FileInputStream("mydata.dat");
                        int ch;
                        while ((ch=f.read())!=-1)
                        {
                                    System.out.print((char)ch);
                        }
                        f.close();
            }
}