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)

Sunday, 10 March 2013

java.little.Basic;



What is Java?

Java is a technology from Sun Micro System but over taken by Oracle developed by James Gosling with the name of 'Oak' in 1991.

It was renamed to Java in 1995.

Java Technology is divided in four parts

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

Versions of Java

Java provides two kinds of version

  1. Developer Version
  2. Product Version

Developer version deals with the JDK (Java Development Kit) Software
Ø  1.0
Ø  1.1
Ø  1.2
Ø  1.3
Ø  1.4
Ø  1.5
Ø  1.6
Ø  1.7

Product version denotes the Java Technology and the strength of Java

Ø  1.0
Ø  1.1
Ø  1.2 (Java 2)
Ø  1.3 (Java 2)
Ø  1.4 (Java 2)
Ø  5.0
Ø  6.0
Ø  7.0

Feature of Java

  1. Simple and Sober
  2. Object Oriented
  3. Multi Threaded
  4. Portable
  5. Platform Independent or Write once run anywhere
  6. Secure
  7. Robust
    1. Java provides a big set of built-in classes for almost any purpose
    2. Java provides Garbage Collector to avoid the memory leakage
    3. Java provides exception handling to trap the runtime errors


How Java is Platform Independent?
What makes Java Platform Independent?

Sun provides a software called JRE (Java Runtime Environment) which contains two other softwares JVM (Java Virtual Machine) and GC (Garbage Collector)

JVM again contains other softwares Class Loader, Code Verifier and JIT (Just-in-time) Compiler

.java à JAVAC à .class à JVM (Class Loader à Coder Verifier à JIT) à Binary à Execution

JVM is a machine dependent software that makes the Java platform Independent.

14.02.2011

Writing first Java Program

-          File extension must be .java
-          Every executable class must have an entry point
§  public static void main(String args[])
-          Java provides three built-in static objects named as in, outand errinside the System class
-          in is an static object of InputStream class from java.io package
-          out and err are the static objects of PrintStream class from java.io package

Methods of InputStream class

-          int read()

Methods of PrintStream class
-          printf()
-          print()
-          println()

Syntactical Rules of Java

-          All keywords and package names must be in lower case
-          All class names and interface names starts with capital letter (Pascal Case)
§  Math
§  String
§  BufferedReader
§  InputStreamReader
-          All field and methods names starts with lower letter (camel case)
§  print()
§  readLine()
§  println()
§  substring()

//First.java
class Test
{
            public static void main(String args[])
            {
                        System.out.println("Hello to Java");
            }
}

Compiling a Java Program

Use JAVAC.EXE compiler

JAVAC <programname.java>

Example
JAVAC First.java à Test.class

Note: If getting problems in finding the JAVAC then set the PATH. It is an environmental variable called PATH to lookup the executable files (.exe, .com and .bat). It contains a list of folders

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

It is a temporary setting. To make the permanent setting use

My Computer à Properties à Advanced àEnvironmental Variables à System Variables à Path àEdit… àNow add your folder after semicolon



Running a class

Use JAVA.EXE tool

            JAVA <classname>

Example
JAVA Test


File Naming Rules in Java

  1. A file name can be upto 255 character including spaces and extension
  2. A program can have many classes
  3. All or none of the classes can have the entry point
  4. A program name and class can be same or different except if the class is public then both must be same

Example 2
class Sample
{
            public static void main(String []args)
            {
                        int a=6,b=7;
                        System.out.printf("Product of %d and %d is %d\n",a,b,a*b);
                        System.out.println("Product of "+ a +" and "+ b +" is " + a*b);

            }
}

Using Netbeans 6.9.1 as IDE

-          A tool from Sun for Rapid Application Development (RAD)
-          Start a new Project
§  File àNew Project
·         Java à Java Application
-          Define Project Name, location and your class name


16.02.2011

Data Types in Java

Integrals (All are signed)
  1. byte  - 1 byte
  2. short – 2 bytes
  3. int – 4 bytes
  4. long – 8 bytes
Floating
  1. float – 4  bytes
  2. double – 8 bytes
Booleans
  1. boolean – 2 bytes
Characters
  1. char – 2 byte (Unicode)


Literals

The constant values that we use from our side are called as literals or literal values.

Can be of different types

  1. Integral Literals
  2. Floating Literals
  3. Character Literals
  4. Boolean Literals
  5. String Literals

Integral Literals

-          Having the numbers without decimal point
-          Default is int
§  int num=6;
-          Use l or L with long as suffix
§  long k=5L;

Floating Literals
-          To hold data with decimal points
§  Default is double
§  Use f or F with float as suffix
·         double num=5.6;
·         float k=5.6; //compile time error
·         float k=5.6f; //correct

Example
class LiteralTest
{
            public static void main(String args[])
            {
                        float n=5.6f,p=3.4f;
                        System.out.println(Math.pow(n,p));
                       
            }
}

Character Literals

-          Enclosed in single quotes
§  char ch='A';

String Literals

-          Enclosed in double quotes
-          Managed by Stringclass
§  String name="Vikas";

Boolean Literals
-          Can have trueor false only
§  boolean married=true;

Reading data from Keyboard

When data in typed from keyboard (System.in), it is in binary format. This data get passed to another class InputStreamReader which convert the binary data into character format. These characters are further passed to another class BufferedReader for temporary buffering until we press the Enter key.

To read data from the buffer, BufferedReader class provides readLine() method
            public String readLine() throws IOException

Here InputStreamReader, BufferedReader and IOException are the classes provided in java.iopackage.


Package

A package is a folder containing related set of classes. Java provides many packages for different kinds of classes

  1. java.lang
    1. Default package that provides all commonly used classes
    2. String, Math, System, Float, Double, Integer etc.
  2. java.io
    1. File, FileReader, FileWriter
    2. InputStreamReader, BufferedReader etc.
  3. java.net
  4. java.sql
  5. java.rmi
  6. javax.swing
  7. javax.servlet
  8. javax.servlet.jsp
  9. java.applet
  10. java.util


Importing the Packages

Use importcommand

import packagename.classname;
or
import packagename.*;

Example
import java.io.*;

Example
WAP to input name and email of a person and just show them.

import java.io.*;
public 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 Name : ");
        String name=br.readLine();
        System.out.print("Email : ");
        String email=br.readLine();

        System.out.printf("Name is %s and Email is %s",name,email);

    }
}

18.02.2011

Converting data from string to numeric

Java provides special classes to work with different data types, called as Wrapper Classes.

A wrapper class is a special class corresponding to a data type which provides advance functions on different data types

Data Types     Wrapper Class

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

Example
WAP to convert an int type data into octal, hexa and binary

public class WrapperTest
{
    public static void main(String[] args)
    {
        int num=5678;
        System.out.println(Integer.toBinaryString(num));
        System.out.println(Integer.toHexString(num));
        System.out.println(Integer.toOctalString(num));

        char ch='$';
        if(Character.isDigit(ch))
            System.out.println(ch+" is a digit");
        else if(Character.isLetter(ch))
            System.out.println(ch +" is an alphabet");
        else
            System.out.println(ch+ " is special character");
    }

}

Such classes are also used to convert string kind of data into numeric kind of data.

datatype variable=wrapperclass.parseDatatype(stringdata);


Example
int age=Integer.parseInt(br.readLine());
double basic=Double.parseDouble(br.readLine());

Example

WAP to input name and age of a person and check it to be valid voter.

import java.io.*;
public class Voter
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter Name : ");
        String name=br.readLine();
        System.out.print("Age : ");
        int age=Integer.parseInt(br.readLine());
        if(age>=18)
            System.out.printf("Dear %s you can vote",name);
        else
            System.out.printf("Dear %s you cannot vote", name);
    }
}




Importing Static members of a class

Use import statickeyword

import static <packagename>.<classname>.*;

Example
import static java.lang.System.*;
import static java.lang.Math.*;

Full Code
import static java.lang.System.*;
import static java.lang.Math.*;
import java.io.*;
public class ImportStaticTest
{
    public static void main(String args[]) throws IOException
    {
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        out.print("Enter a number : ");
        double num=Double.parseDouble(br.readLine());
        out.print("Enter the power : ");
        double p=Double.parseDouble(br.readLine());

        double result=pow(num,p);
        out.printf("%.2f to the power %.2f is %.2f",num,p,result);


    }
}

Reading data using Scanner class

A class from java.util package that provides functions to directly read different kind of data without any conversion.

First create an object of Scanner class

Scanner sc=new Scanner(System.in);

Use its methods

  1. String next()
  2. int nextInt()
  3. float nextFloat()
  4. double nextDouble()




import java.util.Scanner;
import static java.lang.System.*;
public class ScannerTest
{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(in);
        out.print("Enter the name : ");
        String name=sc.next();
        out.print("Age : ");
        int age=sc.nextInt();
        if(age>=18)
            out.printf("Dear %s you can vote",name);
        else
            out.printf("Dear %s you can vote",name);
    }
}

Mixing Scanner with BufferedReader

import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;
public class Mix
{
    public static void main(String args[]) throws IOException
    {
        Scanner sc=new Scanner(in);
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        out.print("Name : ");
        String name=br.readLine();
        out.print("Age : ");
        int age=sc.nextInt();
        if(age>=18)
            System.out.printf("Dear %s you can vote",name);
        else
            System.out.printf("Dear %s you cannot vote", name);
    }

}


Creating static objects

import java.io.*;
import java.util.Scanner;
import static java.lang.System.*;
public class MyClass
{
    public static Scanner sc=new Scanner(in);
    public static BufferedReader br=new BufferedReader(new InputStreamReader(in));
}


Using Static Objects


import java.io.*;
import static java.lang.System.*;
public class Mix
{
    public static void main(String args[]) throws IOException
    {
        out.print("Name : ");
        String name=MyClass.br.readLine();
        out.print("Age : ");
        int age=MyClass.sc.nextInt();
        if(age>=18)
            System.out.printf("Dear %s you can vote",name);
        else
            System.out.printf("Dear %s you cannot vote", name);
    }

}


21.02.2011

Operators

Arithmetic
            +
            -
            *
            /           5/2 à 2                       5.0/2 à 2.5
            %

Cast operator

-          Used to convert one kind of data to another kind of data

int a=22,b=7;
double c=(double)a/b;

Relational operators
            ==
     !=
     >
     >=
     <
     <=
     instanceof

Logical operators
     &&
     ||  
     !

Bitwise operators
     &
     |
     ^
     ~
     <<
     >>

Conditional Statements

1.  if statements
2.  switch statement
3.  ternary operator (?:)


Examples of Ternary

WAP to print greatest of three numbers.

int g=a>b?(a>c?a:c): (b>c?b:c);

WAP to get basic of an employee and print the DA as per rules
     80% for basic >=9000
     70% for basic>=7000
     50 for others

double da=basic>=9000? 0.8*basic : basic>=7000? 0.7*basic : 0.5*basic;

Assignment
WAP to get average marks of a student and print the grade as per rules
     A+   for >=90
     A    for >=80
     B+   for >=70
     B    for >=50
     Fail for others

String grade=marks>=90? “A+” : marks>=80? “A” : marks>=70?”B+” : marks>=50? “B” :  “Fail”;




Looping Statements

1.  while
2.  for
3.  do-while
4.  break
5.  continue

Arrays
A variable that can hold multiple values of similar data type in continuous locations.

Each element of array is differentiated by a number called index number.

In Java, arrays are treated like objects created with new keyword. We can define user defined size of array.

int []num=new int[5];

Each array provides lengthproperty


Example
WAP to input some numbers and print biggest and smallest of those numbers.

import java.util.*;
public class ArrayTest
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("How many numbers : ");
        int n=sc.nextInt();
        int num[]=new int[n];
        for(int i=0;i<num.length;i++)
        {
            System.out.printf("Enter No %d: ",i+1);
            num[i]=sc.nextInt();
        }
        int max,min;
        min=max=num[0];
        for(int i=1;i<num.length;i++)
        {
            if(num[i]>max) max=num[i];
            if(num[i]<min) min=num[i];
        }

       System.out.printf("Biggest is %d and Smallest is %d",max,min);
    }

}

Using for-each loop

A loop that works with arrays and collections only without knowing size of array and array index.

Syntax

for(datatype variable : arrayname)
{
     //statement
}

import java.util.*;
public class ForEachTest
{
    public static void main(String[] args)
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("How many numbers : ");
        int n=sc.nextInt();
        int num[]=new int[n];
        for(int i=0;i<num.length;i++)
        {
            System.out.printf("Enter No %d: ",i+1);
            num[i]=sc.nextInt();
        }
        int max,min;
        min=max=num[0];
        for(int x : num)
        {
            if(x>max) max=x;
            if(x<min) min=x;
        }

       System.out.printf("Biggest is %d and Smallest is %d",max,min);
    }
}

Two Dimensional Array

int [][]num=new int[2][3];

Example

WAP to get an array of 3x4 and print the actual array and transpose of it.

import java.util.*;
public class TwoDArray
{
    public static void main(String[] args)
    {
        int [][]num=new int[3][4];
        Scanner sc=new Scanner(System.in);

        for(int i=0;i<3;i++)
            for(int j=0;j<4;j++)
            {
                System.out.printf("Enter number [%d][%d] : ",i,j);
                num[i][j]=sc.nextInt();
            }

        for(int i=0;i<3;i++)
        {
            for(int j=0;j<4;j++)
                System.out.printf("%d\t",num[i][j]);
            System.out.println();
        }
        System.out.println("Transpose is :");
        for(int i=0;i<4;i++)
        {
            for(int j=0;j<3;j++)
                System.out.printf("%d\t",num[j][i]);
            System.out.println();
        }
   }
}


What is OOPs?

OOPs stands for Object Oriented Programming System is a system or methodology used by a programming language for better project management using set of components also called as pillars of OOPs

  1. Encapsulation
  2. Abstraction
  3. Polymorphism
  4. Inheritance

These four components are implemented using three other components

  1. Class
  2. Object
  3. Reference

What is Class?

A class is set of specifications or blueprint defining attributes and behaviors of an entity to create similar type of objects.

Use class keyword to create a class

class <classname>
{
            //members
}


Types of Members inside a class

Members can be of two types
  1. Static or Class members
  2. Non-static or instance members

Non-static or instance members always need an object to use them.

Static or class members do not require an object to use them but they can be used by the object as well. Use static keyword to declare such members.

What is an object?

The real entity created based on class specifications is called as object or instance. Use new keyword to allocate the memory for data members of an object and special method called constructor to initialize data member of the object.

classname referencename=new constructor(arugment);

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

What is a constructor?

Special method inside a class having some features

  1. Same name as class name
  2. No return type
  3. Used to initialize fields of an object
  4. Can be overloaded
  5. if we do not create any constructor then default constructor is created automatically but if we create any parameterized constructor then default constructor is not created automatically but we have to create it.
  6. Constructor can be private as well

Note:

A data fields of an object can be initialized using two ways
  • Using a method
  • Using a constructor

Example 1
Create a class Numberhaving a data member as num. Create a method setNumber() to initialize the value in num. Create a method squareRoot() to return the Square Root of num.

public class Number
{
    int num;
    void setNumber(int n)
    {
        num=n;
    }
    double squareRoot()
    {
        return Math.pow(num,1.0/2);
    }
    public static void main(String args[])
    {
        Number x=new Number();
        Number y=new Number();
        x.setNumber(5);
        y.setNumber(6);
        System.out.println(x.squareRoot());
        System.out.println(y.squareRoot());
    }
}


Note: If the parameter name and field name are same then use thiskeyword to refer the fields of current object.

public class Number
{
    int num;
    void setNumber(int num)
    {
        this.num=num;
    }
    double squareRoot()
    {
        return Math.pow(num,1.0/2);
    }
    public static void main(String args[])
    {
        Number x=new Number();
        Number y=new Number();
        x.setNumber(5);
        y.setNumber(6);
        System.out.println(x.squareRoot());
        System.out.println(y.squareRoot());
    }
}


Example 2

Create a class Num2 having two fields x and y. Create constructor to initialize these fields. Create a method product() to return product of x and y.

Create a method as factorial() that take a number as argument and returns the factorial of given number.

public class Num2
{
    int x,y;
    Num2(int x, int y)
    {
        this.x=x;
        this.y=y;
    }
    int product() //instance member
    {
        return x*y;
    }
    static long factorial(int n) //class member
    {
        if(n==1)
            return 1;
        else
            return n*factorial(n-1);
    }
    public static void main(String args[])
    {
        Num2 p=new Num2(3,4);
        Num2 q=new Num2(5,6);
        System.out.println(p.product());
        System.out.println(q.product());
        System.out.println(Num2.factorial(7));
    }
}


Example 3

Create a class Num3 having three data fields x,y,z. Create a constructor to initialize the  fields. Create a method g3() which returns greatest of three numbers.

Also create a method setData() which initializes these three members.

Create two object p and q where p is initialized using the constructor and q using the method.

public class Num3
{
    int x,y,z;
    Num3()
    {
    }
    Num3(int x, int y, int z)
    {
        this.x=x;
        this.y=y;
        this.z=z;
    }
    void setData(int x, int y, int z)
    {
        this.x=x;
        this.y=y;
        this.z=z;
    }
    int g3()
     {
        return x>y?(x>z?x:z):(y>z?y:z);
     }
    public static void main(String args[])
    {
     Num3 p=new Num3(4,5,6);
     System.out.println(p.g3());
     Num3 q=new Num3();
     q.setData(4, 7, 45);
     System.out.println(q.g3());
    }
}


25.02.2011

Encapsulation

A pillar of OOPs that says that place all the members of a class under one body

class <classname>
{
            //members
}

Abstraction

Java provides four abstraction layers.

  1. private
  2. public
  3. protected
  4. package (default)

private members can be accessed within the class only. Such members can never be used by the object or in inheritance.

public members can be access in same or different package or folder, using the object or in inheritance

protected members can be accesses in same package only by the object and can be inherited in same or different folder.

package members can be accesses in same package only by the object and in inheritance.


public> protected > package > private


What is a package?

A folder containing related set of classes. Difference packages can have the classes with same name.

It works as library of classes for multiple projects. Packages can also be distributes to others as .zip or .jar file.

Example
            java.util.Date class
            java.sql.Date class

Creating a package from Command Prompt

-          First create a folder to hold your packages
-          Decide your package names and create folders with those names
-          Create the classes and place them in corresponding packages
o   Each of such class must have packagecommand on top

Example

Container folder for packages – c:\b13packages

Lets create two packages as first and second. We need to create two sub folders under b13pacakges folder

Lets create two classes MyMath and YourMath having different methods

first package àMyMath à squareRoot()
second package àYourMath àcubeRoot()


package first;
public class MyMath
{
            public static double squareRoot(double num)
            {
                        return Math.pow(num,1.0/2);
            }
}

package second;
public class YourMath
{
            public static double cubeRoot(double num)
            {
                        return Math.pow(num,1.0/3);
            }
}

Javac MyMath.java
Javac YourMath.java


Using a Package a Command Prompt

-          Create a class to use a package and import the package

import first.*;
import second.*;
class PackageTest
{
            public static void main(String args[])
            {
                        System.out.println(MyMath.squareRoot(5.6));
                        System.out.println(YourMath.cubeRoot(5.6));

            }
}

To define the path of the classes in different packages use CLASSPATH command

Set classpath=%classpath%;c:\b13packages;


Distributing the packages

Packages can be distributed as .jar file or .zip file

Use WINZIP tool for .zip file and JAR.exe tool of JDK for .jar files


Example 1: Creating a .zip file

Select all the package names and convert into a zip file e.g. b13packages.zip

Now we can add the .zip file into the classpath

set classpath=%classpath%;d:\b13packages.zip;


Example 2: Creating Java Archive (.jar) files

Use JAR.EXE tool with some options
            c àcreate
            t àtabulate
            x àextract
            v àverbose
            f  à define the file name

Goto the folder having the packages on the command prompt

Now add all the packages in current directory (.) into a jar file


Now this jar file can be used in any project by setting the classpath

set classpath=%classpath%;d:\test.jar;


Create a .jar file from NetBeans

Start the Netbeans and select a new project as Java Class Library

Add the classes and define their packages

Build the project

It creates a .jar file under dist folder


Using Java Class Library (.jar) in Any Project

Start a new project and add the library from Libraries option




04.03.2011

Polymorphism

A concept which allows to perform more than once action by an item. It get implemented by overloading.

Java allows only method overloading.

Method Overloading

Two or more methods having the same name but different number of arguments or type of arguments, is called as method overloading.

Example
Create a class Number having a field as num. Create a function as factorial() of num. Also create another method as factorial() which takes a number as argument.

//Example of method overloading
class Number
 {
    int num;
    public Number(int num)
    {
        this.num=num;
    }
    public long factorial()
    {
        long f=1;
        for(int i=1;i<=num;i++)
            f=f*i;
        return f;
    }
    public static long factorial(int n)
    {
        if(n==1)
            return 1;
        else
            return n*factorial(n-1);
    }
public static void main(String[] args)
    {
        Number x=new Number(6);
        System.out.println("Factorial is "+x.factorial());
        System.out.println("Factorial of 7 is "+x.factorial(7));
    }
}




Inheritance

Most important pillar of OOPs that provides re-usability of code. It helps in decreasing the code size and creating specialized code.

Java allows only single inheritance.

Use extendskeyword to inherit a class into other class.

All Java classes are child of Object class.

Note: Use JAVAP.EXE tool of JDK to view internals of a class

Java provides three layers of classes

  1. child class
  2. super class
  3. parent classes

Example
class A
{
}

class B extends A
{
}

For B, A is a super class and Object is parent class.

Use this keyword to refer object of current class and super keyword to refer object of super class.

Example

Create a class Num2 having two fields a and b. Create a method as p2() which returns product of two numbers.

Create another class Num3 which operators on three numbers. Inherit class Num2 into Num3, pass the data to Num2 and use the p2() into Num3 to return product of three numbers.

Create another class Test to create an object of class Num3, pass three arguments and show the product of those arguments.


Solution
class Num2
{
    int a,b;
    public Num2(int a, int b)
    {
        this.a=a;
        this.b=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 p3()
    {
        return p2()*c;
    }

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

Method Overriding

A method of parent class, re-written in child class with same signature and different body contents is called as method overriding.

While overriding we can increase the scope of the methods but we cannot decrease it.

class Num2
{
    int a,b;
    public Num2(int a, int b)
    {
        this.a=a;
        this.b=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 product() //method overriding
    {
        return super.product()*c;
    }

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


Types of Classes

Java provides three kinds of classes

  1. Concrete class
  2. Abstract class
  3. Final class

A class that can be instantiates and can also be inherited is called as concrete class. All classes are by default concrete.

Example

class A
{
}

A class than can never be instantiated but can be inherited, is called as abstract class. Such classes must have abstract keyword associate with them.

abstract class X
{
}

class that can never be inherited but can be instantiated is called as final class. Use final keyword to make such class.

final class Y
{
}


Types of methods

  1. Concrete methods
  2. Abstract methods
  3. Final methods

A method that can be used in child class and can also be overridden is called as concrete method. By default all methods are concrete.

A method having the signature but no body contents is called as abstract method.  Such methods can be declared at two places.

  1. Abstract class
  2. Interface

If declared inside an interface no keyword is required but if declared inside an abstract class then abstract keyword is required. All methods inside an interface are abstract by default.

Final methods is a method than can be used in child class but can never be overridden. Use final keyword with such methods.


07.03.2011

What are the finals?

final is a keyword used with field, method and class.

If used with field, makes the constant
If used with method, do not allow to override
If used with class, do not allow to inherit

Can we de-compile class file?

Yes, Using Java Decompilers

What is the difference between overloading and overriding?

In case of overloading, signatures must be different while in case of overriding signature must be same.

Overloading can be in same class or in child class while overriding can only be in child class.

While overloading we can increase or decrease the scope while overriding we can increase the scope but cannot decrease it.
Golden of rule of Inheritance

A parent can hold reference to its childs and can invoke only those methods of child whose signature is provided from parent to the child. Only overridden method can be accessed using reference of parent.

Runtime Polymorphism

When a reference of a parent is re-used to hold reference of multiple childs, it is called runtime polymorphism.

class A
{
            void show()
            {
                        System.out.println("Calling from A");
            }
}
class B extends A
{
            void show()
            {
                        System.out.println("Calling from B");
            }
            void test()
            {
                        System.out.println("Testing Hello");
            }
}

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

class RuntimePolymorphism
{

            public static void main(String args[])
            {
                        A x; //Runtime Polymorphism
                        x=new A();
                        x.show();
                        x=new B();
                        x.show();
                        x=new C();
                        x.show();
            }
}

Using Abstract class

It is mainly used to divide the data into multiple re-usable classes. An abstract class can never be instantiated but can have the reference.

Such classes are used for inheritance purpose only.

 Example

Create three classes for different entities like Vendor, Customer and Employee. Create a Common class having common fields of all three entities and mark it as abstract then use the class in other three classes.

abstract class Common
{
            String name, email, mobile;
            public Common(String name, String email, String mobile)
            {
                        this.name=name;
                        this.email=email;
                        this.mobile=mobile;
            }
            public Common()
            {
            }
            public void setName(String name)
            {
                        this.name=name;
            }
            public String getName()
            {
                        return name;
            }
            public void setEmail(String email)
            {
                        this.email=email;
            }
            public String getEmail()
            {
                        return email;
            }
            public void setMobile(String mobile)
            {
                        this.mobile=mobile;
            }
            public String getMobile()
            {
                        return mobile;
            }
}


class Vendor extends Common
{
            int vcode;
            public Vendor()
            {
            }         
            public Vendor(int vcode, String name, String email, String mobile)
            {
                        super(name,email,mobile);
                        this.vcode=vcode;
            }
            public void setVcode(int vcode)
            {
                        this.vcode=vcode;
            }
            public int getVcode()
            {
                        return vcode;
            }
}

class AbstractTest
{
            public static void main(String args[])
            {
                        Vendor v=new Vendor();
                        v.setVcode(678);
                        v.setName("Rahul");
                        v.setMobile("89898989");
                        v.setEmail("rahul@yahoo.com");

                        System.out.printf("Name is %s and Vender code %d",v.getName(), v.getVcode());
           
            }
}



09.03.2011

Interfaces

A user defined data type very similar to classes but contains all abstract methods and final fields.

All methods are public and abstract by default.
All fields are public and final by default.

It allows to implements the multiple inheritances.

A class can inherit any number of interfaces using implementskeyword.

An interface can also inherit other interfaces using extends keyword.

Can never be instantiated but can have the reference.

It is mainly used for division of work.

interface <interfacename>
{
     //methods and fields
}

Example
Create an application to manage activities of a business having different departments like Sales and Production etc.

public interface Common
{
    void leaveInfo();
}

public interface Sales extends Common
{
    void forecasting();
}

public interface Production extends Common
{
    void schedule();
}

public class ERP implements Production,Sales
{
    public void forecasting()
    {
        System.out.println("Sales will be doubled this year");
    }
    public void schedule()
    {
        System.out.println("Morning shipt will be closed");
    }
    public void leaveInfo()
    {
        System.out.println("Leaves will be 5EL, 6CL, 2 ML etc.");
    }
}

public class InterfaceTest
{

    public static void main(String[] args)
    {
        Sales s=new ERP();
        s.forecasting();
        s.leaveInfo();

    }

}

Review of OOPs

  1. this keyword
  2. super keyword
  3. abstract keyword
  4. interface keyword
  5. final keyword
  6. implements  keyword
  7. extends keyword


Using AWT (Abstract Window Toolkit)

A collection of classes under java.awt package for GUI programming. The classes are categorized in three categories

  1. Containers
  2. Components
  3. Supporting Classes

Each container is a class used to hold the components and other containers. Example
Frame, Dialog, Panel, Applet etc.

Each component is again a class used to interact with the user. Examples

Button, TextField, TextArea, Checkbox, Choice, Menu, PopupMenu etc.

Supporting classes are used to support the components and containers like

Color, Font, Dimension etc.

All containers and components are child of Component class which provides common methods application to all the components and containers. It is an abstract class.

  • public void setSize(int w, int h)
  • public void setVisible(boolean value)
  • public void setBackground(Color c)
  • public void setLocation(int x, int y)
  • public void setBounds(int x, int y, int w, int h)

All containers are child of Container class. It provides common methods for all the containers.

  • public void add(Component c)


Frame class

A class that provides a window for your applications.

  • Frame()
  • Frame(String title)
  • public void setTitle(String title)
  • public String getTitle()


Example 1
Create a window of 300x300 with blue background

import java.awt.*;
class MyWindow
{
            public static void main(String args[])
            {
                        Frame f=new Frame();
                        f.setSize(300,300);
                        f.setBackground(Color.blue);
                        f.setVisible(true);
            }

}

Example 2

Create a class and inherit it from Frame class and create the new frame of size 200x200 at location 50x50.



import java.awt.*;
class TestWindow extends Frame
{
            public TestWindow()
            {
                        super("First App");
                        setSize(300,300);
                        setBackground(Color.blue);
                        setLocation(50,50);
                        TextArea ta=new TextArea();
                        add(ta);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new TestWindow();
            }

}

AWT Classes to Study

  1. Label
  2. TextField
  3. TextArea
  4. Button
  5. Choice
  6. Checkbox
  7. Menu
  8. MenuItem
  9. PopupMenu
  10. Dialog
  11. FileDialog


23.03.2011

Label class
-          To place some text
o   Label()
o   Label(String text)
o   public void setText(String text)
o   public String getText()


Button class
-          Used to create a push button
o   Button()
o   Button(String label)
o   Void setLabel(String label)
o   String getLabel()

TextField class

To create single line text box and password field

-          TextField()
-          TextField(int columns)
-          void setText(String text)
-          String getText()
-          void setEchoChar(char ch)
-          char getEchoChar()
-          void setEditable(boolean value)

TextArea class

To create multi line text

-          TextArea(int rows, int cols)
-          void setText(String text)
-          String getText()
-          void setEditable(boolean value)



Choice class
-          to create drop down list to select only one item
o   Choice()
o   void add(String item)
o   String getSelectedItem()

List class

-          To create a list box to select one or more items
o   List(int size)
o   List(int size, boolean multiple)
o   String getSelectedItem()
o   String[] getSelectedItems()

Checkbox class

-          To create checkbox and radio buttons
o   To create the checkbox (to select none or all)
§  Checkbox(String text)
§  Checkbox(String text, boolean state)
§  boolean getState()
o   To create the radio button (to select only one from group)
§  Each radio button is placed under a group created with CheckboxGroup
§  Checkbox(String text,CheckboxGroup cg, boolean state)
§  boolean getState()




Example

Create a window form having following controls on it

Login – Label, TextField
Password – Label, TextField

Name - Label, TextField
Email - Label, TextField
Mobile - Label, TextField
Address - Label, TextArea

Gender – Label, Radio Buttons (Male, Female)
Country – Label, Choice

Subjects – Label, List

Agree to Terms and Conditions – Checkbox

Continue – Button

Naming Convention of Controls

-          Use 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
o   Label àlbl
o   TextField àtxt
o   Checkbox àchk
o   Etc.

Adding Controls to a Frame

When controls get added to the frame, they get placed into the container using special kind of classes called Layout Managers.

  1. BorderLayout – default for Frame and Dialog
  2. FlowLayout – default for Applet
  3. GridLayout
  4. GridBagLayout
  5. CardLayout

To change the layout use setLayout() method of a container

Example
setLayout(new FlowLayout());
setLayout(new GridLayout(3,4));



Placing controls at Desired Position

-          First remove the current layout manager
o   setLayout(null);
-          Use setBounds() method to define the starting point and the size of controls
o   public void setBounds(int x, int y, int w, int h)


import java.awt.*;
class SampleApp extends Frame
{
            Label lblNumber,lblResult;
            TextField txtNumber,txtResult;
            Button cmdSquare,cmdCube;

            public SampleApp()
            {
                        lblNumber=new Label("Number");
                        lblResult=new Label("Result");

                        txtNumber=new TextField();
                        txtResult=new TextField();
                        txtResult.setEditable(false); //read only

                        cmdSquare=new Button("Square");
                        cmdCube=new Button("Cube");

                        setLayout(null);

                        lblNumber.setBounds(30,50,60,20);txtNumber.setBounds(100,50,100,20);
                        lblResult.setBounds(30,90,60,20);txtResult.setBounds(100,90,100,20);
                        cmdSquare.setBounds(60,130,60,20);cmdCube.setBounds(130,130,60,20);

                        add(lblNumber);add(txtNumber);
                        add(lblResult);add(txtResult);
                        add(cmdSquare);add(cmdCube);
                       

                        setSize(250,250);
                        setResizable(false);
                        setVisible(true);
                       
            }
            public static void main(String args[])
            {
                        new SampleApp();
            }
}



Introduction to Events in Java

Each event in Java is an abstract method defined in some interface. Such interfaces are called as listeners.

-          ActionListener
o   For Button, MenuItem etc.
-          MouseListener
o   Any control
-          MouseMotionListener
o   Any control
-          KeyListener
o   For TextField, TextBox etc.
-          ItemListener
o   For Choice, List, Checkbox etc.
-          WindowListener
o   For Frame and Dialog
-          AdjustmentListener

All such interfaces are provided under java.awt.event package. All such interfaces provides a pre-defined set of abstract method that we need to override to define the functioning on different controls

Such system is known as Event Delegation Model.

Examples of methods

ActionListener interface
            public void actionPerformed(ActionEvent e)

            Methods of ActionEvent class
                        public Object getSource()
                        public String getActionCommand()

ItemListener interface
            public  void itemStateChanged(ItemEvent e)


Placing a delegate on the controls

Use addXXXListener() method on the control by defining the object of the class where the corresponding method is overridden.

cmdSquare.addActionListener(this);
cmdCube.addActionListener(this);


import java.awt.*;
import java.awt.event.*;
class SampleApp extends Frame implements ActionListener
{
            Label lblNumber,lblResult;
            TextField txtNumber,txtResult;
            Button cmdSquare,cmdCube;

            public SampleApp()
            {
                        lblNumber=new Label("Number");
                        lblResult=new Label("Result");

                        txtNumber=new TextField();
                        txtResult=new TextField();
                        txtResult.setEditable(false); //read only

                        cmdSquare=new Button("Square");
                        cmdCube=new Button("Cube");

                        cmdSquare.addActionListener(this);
                        cmdCube.addActionListener(this);
                       

                        setLayout(null);

                        lblNumber.setBounds(30,50,60,20);txtNumber.setBounds(100,50,100,20);
                        lblResult.setBounds(30,90,60,20);txtResult.setBounds(100,90,100,20);
                        cmdSquare.setBounds(60,130,60,20);cmdCube.setBounds(130,130,60,20);

                        add(lblNumber);add(txtNumber);
                        add(lblResult);add(txtResult);
                        add(cmdSquare);add(cmdCube);
                       

                        setSize(250,250);
                        setResizable(false);
                        setVisible(true);
                       
            }
            public static void main(String args[])
            {
                        new SampleApp();
            }
            public void actionPerformed(ActionEvent e)
            {
                        double num=Double.parseDouble(txtNumber.getText());
                        double result=0.0;
                        if(e.getSource()==cmdSquare)
                                    result=num*num;
                        else
                                    result=num*num*num;

                        txtResult.setText(Double.toString(result));
                       
            }
}


28.03.2011

Example
Create a window application to show the current mouse position when we move the mouse pointer on the form

Control: Frame
Listener: MouseMotionListener

Methods to override

            public void mouseMoved(MouseEvent e)
            public void mouseDragged(MouseEvent e)

            Methods of MouseEvent
                        int getX()
                        int getY()
                        boolean isPopupTrigger()


Solution

import java.awt.*;
import java.awt.event.*;
class EventTest extends Frame implements MouseMotionListener
{
            public EventTest()
            {
                        addMouseMotionListener(this);
                        setSize(300,300);
                        setVisible(true);
            }
            public void mouseMoved(MouseEvent e)
            {
                        String s=e.getX()+","+e.getY();
                        setTitle(s);
            }
            public void mouseDragged(MouseEvent e){}

            public static void main(String args[])
            {
                        new EventTest();
            }

}

Different places for implementing the interfaces

  1. Same class
  2. Inner class
  3. Outer class
  4. Anonymous class

Using Inner class

A class within a class is called as Inner class. It can access all the members of containing class.

Example

Create a window to close the application when x button is clicked

Control: Frame
Listener: WindowListener

Solution

import java.awt.*;
import java.awt.event.*;
class InnerTest extends Frame
{
            public InnerTest()
            {
                        addMouseMotionListener(new ME());
                        addWindowListener(new WE());
                        setSize(300,300);
                        setVisible(true);
            }

            public static void main(String args[])
            {
                        new InnerTest();
            }

            class ME implements MouseMotionListener
            {
                        public void mouseMoved(MouseEvent e)
                        {
                                    String s=e.getX()+","+e.getY();
                                    setTitle(s);
                        }
           
                        public void mouseDragged(MouseEvent e){}

            }

            class WE implements WindowListener
            {
                        public void windowActivated(WindowEvent e){}
                        public void windowDeactivated(WindowEvent e){}
                        public void windowOpened(WindowEvent e){}
                        public void windowClosed(WindowEvent e){}
                        public void windowIconified(WindowEvent e){}
                        public void windowDeiconified(WindowEvent e){}
                        public void windowClosing(WindowEvent e)
                        {
                                    System.exit(0);
                        }
            }
}


Using Adapter classes

Special classes corresponding to listeners having pre-overridden methods with blank body. We can inherit these classes and further override those methods as per needs.

            WindowListener àWindowAdapter
            KeyListener àKeyAdapter

Note: All those listener who have only on method, do not provided any adapter

They are best used in combination of Inner classes

Solution

import java.awt.*;
import java.awt.event.*;
class AdapterTest extends Frame
{
            public AdapterTest()
            {
                        addMouseMotionListener(new ME());
                        addWindowListener(new WE());
                        setSize(300,300);
                        setVisible(true);
            }

            public static void main(String args[])
            {
                        new AdapterTest();
            }

            class ME extends MouseMotionAdapter
            {
                        public void mouseMoved(MouseEvent e)
                        {
                                    String s=e.getX()+","+e.getY();
                                    setTitle(s);
                        }
           
            }

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

            }

}


Case 3: Using Outer class

import java.awt.*;
import java.awt.event.*;
class OuterTest extends Frame
{
            public OuterTest()
            {
                        addMouseMotionListener(new ME(this));
                        addWindowListener(new WE());
                        setSize(300,300);
                        setVisible(true);
            }

            public static void main(String args[])
            {
                        new OuterTest();
            }
}

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

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

Using Anonymous class

When we override the methods of a listener while registering the events then a class get created automatically as $1, $2. Such classes are called as anonymous class

They are kind of inner classes.

import java.awt.*;
import java.awt.event.*;
class AnonymousTest extends Frame
{
            public AnonymousTest()
            {
                        addMouseMotionListener(new MouseMotionAdapter()
                        {
                                    public void mouseMoved(MouseEvent e)
                                    {
                                                String s=e.getX()+","+e.getY();
                                                setTitle(s);
                                    }
                        });

                        addWindowListener(new WindowAdapter()
                        {
                                    public void windowClosing(WindowEvent e)
                                    {         
                                                System.exit(0);
                                    }
                                   
                        });
                        setSize(300,300);
                        setVisible(true);
            }

            public static void main(String args[])
            {
                        new AnonymousTest();
            }

}


Assignment

1.  Create a form for following fields
a.  User Id
b.  Password
c.  Ret Type Password
d.  User Name
e.  Email
f.  Mobile
g.  Gender (Radio Button)
                       i.   Male/Female
h.  Question (Choice)
                       i.   Mother's Maiden Name
                     ii.   Your favorite person
i.  Answer
j.  Terms and Conditions
                       i.   Multiline text
k.  Agree to Terms and Conditions
                       i.   Checkbox
l.  Continue
                       i.   Button

Initially the buttons should be disabled. When we check the checkbox of Agree to Terms and conditions then enable the button.

2.  Create a form having a button on it as Colors…
a.  On click on the button invoke another form having four radio buttons and one Close Button
                       i.   Red, Green, Blue and Yellow
b.  When we click on any of radio button the background color will be applied to previous form
c.  On click on the button close the current form.

Note: To close the current form only use dispose() method of the Frame class




01.04.2011

Applets

Special Java classes which get merged into HTML and provide dynamicity into HTML

A class to be called as Java Applet must be inherited from java.applet.Appletclass

Applet class provide pre-defined method that we need to override

1.  public void init()
2.  public void paint(Graphics g)
3.  public void showStatus(String s)
a.  To show the message on status bar of the Web Browser
4.  public URL getCodeBase()
5.  public URL getDocumentBase()
6.  pubic Image getImage(URL path, String filename)

The class get loaded into browser and execute at the client side so it must be declared as public.

Example
Write an applet to input a number and print cube root it on status bar of the browser.

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class FirstApplet extends Applet
{
     Button b;
     TextField t;
     Label l;
     public void init()
     {
           t=new TextField(10);
           l=new Label("Number");

           b=new Button("Cube Root");

           b.addActionListener(new ActionListener()
           {
                public void actionPerformed(ActionEvent e)
                {
                     double num=Double.parseDouble(t.getText());
                     double cb=Math.pow(num,1.0/3);
                     showStatus("Cube root is "+cb);
                }
           });
           add(l);add(t);add(b);

     }
}




Creating HTML Code

Merge the Applet into an HTML using <applet></applet> tag

<applet></applet> tag provides various attributes

     code="classname"
     width="x"
     height="y"
     codebase="foldername"
     archive="jar file name"

Example: FirstApplet.htm

<applet code="FirstApplet" width="200" height="200">
</applet>

Running the Applet

Applet can run using any of two methods

1.  Using AppletViewer tool of JDK
2.  Use Web Browser
a.  To use the web browser, the browser must be Java Enabled


Example

appletviewer FirstApplet.htm




Placing class files in different folder

When HTML and class files are in different folder then we need to define the folder name having the class files. Use codebase attribute of <applet></applet> tag to define the folder name having the class files

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

Placing the classes into JAR files

Create a jar file and place all the files into .jar file

JAR cvf test.jar *.class

Now provide the information about the .JAR file to <applet> using archive attribute

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


Using Text into Applet

Applets are GUI based and everything is drawn on the applet. Graphics class provides built-in methods for drawing

     public void drawString(String s, int x, int y)

To print the string in different colors use method
     public void setColor(Color c)

Drawing lines and shapes

Use methods like drawLine() and drawEllipse() method


Example

import java.applet.*;
import java.awt.*;
public class GraphicsTest extends Applet
{
     public void paint(Graphics g)
     {
           g.setColor(Color.blue);
           g.drawString("Welcome to Applet",20,20);
     }
}

<applet code="GraphicsTest" width="300" height="200">
</applet>


Using Images into Applets

Load the image into memory using getImage() method of Applet class
     public Image getImage(URL path, String filename)

To get the URL of the website use methods of Applet class
     public URL getCodeBase()
           returns the path of folder having class file
     public URL getDocumentBase()
           returns the path of folder having HTML file


To draw the image onto the applet use method of Graphics class

public void drawImage(Image img, int x, int y, ImageObserver or)

public void drawImage(Image img, int x, int y, int w, int h, ImageObserver or)


Here ImageObserver is an interface. We can draw image on all the components which are inherited from ImageObserver interface

Applet is a child of ImageObserver and can be used to draw the images

Example

import java.awt.*;
import java.applet.*;
public class ImageApplet extends Applet
{
     Image img;
     public void init()
     {
           img=getImage(getDocumentBase(),"images/6.jpg");
     }   
     public void paint(Graphics g)
     {   
           g.drawImage(img,0,0,this);
     }
}

<applet code="ImageApplet" width="400" height="400">
</applet>




04.04.2011

Passing parameters to the applets

We can pass parameters to the applets using <param> sub tag of <applet> tag. It provides two attributes

Name=”parameter name”
Value=”parameter value”

<param name=”parameter name” value=”param value”>

To read the data inside an applet use getParameter() method of Applet class
            String getParameter(String paramname)

Example
Create an applet to pass the image name as parameter and show that image

<applet code="ParamApplet" width="300" height="300">
            <param name="filename" value="images/file2.jpg">
</applet>

import java.awt.*;
import java.applet.*;

public class ParamApplet extends Applet
{
            Image img;
            public void init()
            {
                        String fname=getParameter("filename");
                        img=getImage(getDocumentBase(),fname);
            }
            public void paint(Graphics g)
            {
                        Dimension d=getSize();
                        g.drawImage(img,0,0,d.width,d.height,this);
            }
}

What is repaint()?

A method that can call the paint() method again. It first calls another method called update() and then update internally calls the paint()

            public void repaint()
            void update(Graphics g)




Example
Create an applet to show the current mouse position on the tip of the mouse pointer

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class RepaintApplet extends Applet
{
            int x,y;
            public void init()
            {
                        addMouseMotionListener(new MouseMotionAdapter()
                        {
                                    public void mouseMoved(MouseEvent e)
                                    {
                                                x=e.getX();
                                                y=e.getY();
                                                repaint();
                                    }
                        });
            }         
            public void paint(Graphics g)
            {
                        String s="Mouse is on : "+x+","+y;
                        g.drawString(s,x-50,y);
            }
            public void update(Graphics gr)
            {
                        int r=(int)(Math.random()*255);
                        int g=(int)(Math.random()*255);
                        int b=(int)(Math.random()*255);
                        Color c=new Color(r,g,b);
                        showStatus(r+","+g+","+b);
                        setBackground(c);
            }
}

<applet code="RepaintTest" width="300" height="300">
</applet>


Creating Menus

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

Drop down menus are shown in the frame . They follow some hierarchy

MenuBar
            Menu
                        MenuItem

Create a menu bar

            MenuBar mb=new MenuBar();

Create a Menu
            Menu m=new Menu(“File”);

Create a MenuItem
            MenuItem mi=new MenuItem(“New”);
MenuItem mi=new MenuItem(“Open…”);

When using a dialog use ellipses (…)

Note:
  1. use ActionListener to write a program code
  2. To show the menu bar on the frame use setMenuBar() method of Frame

setMenuBar(mb);

Example

import java.awt.*;
import java.awt.event.*;
class MenuTest extends Frame implements ActionListener
{
            MenuBar mb;
            Menu mFile;
            MenuItem miOpen,miSave,miExit;
            public MenuTest()
            {
                        mb=new MenuBar();
                        mFile=new Menu("File");
                        miOpen=new MenuItem("Open...");
                        miSave=new MenuItem("Save As...");
                        miExit=new MenuItem("Exit");
                       
           
                        miOpen.addActionListener(this);
                        miSave.addActionListener(this);
           

                        miExit.addActionListener(new ActionListener()
                        {
                                    public void actionPerformed(ActionEvent e)
                                    {
                                                System.exit(0);
                                    }         
                        });

                        mFile.add(miOpen);
                        mFile.add(miSave);
                        mFile.add("-");
                        mFile.add(miExit);
           
                        mb.add(mFile);

                        setMenuBar(mb);

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

            public void actionPerformed(ActionEvent e)
            {
                        FileDialog f;
                        if(e.getSource()==miOpen)
                                    f=new FileDialog(this,"Open a file",FileDialog.LOAD);
                        else
                                    f=new FileDialog(this,"Save a file",FileDialog.SAVE);
                        f.setVisible(true);
            }         
           
}


Creating Popup Menu

To create a menu when a right click on a control. Use PopupMenu class to define a popup menu.

Add Menu and MenuItem inside the popup menu

To show a popup menu on current control and on the current location use the following method

     public void show(e.getComponent(), e.getX(), e.getY())

Use MouseListener or MouseAdapter and override mouseReleased event

     public void mouseReleased(MouseEvent e)

To trap the right click use isPopupTrigger() method of MouseEvent class

     public boolean isPopupTrigger()

Example

import java.awt.*;
import java.applet.*;
import java.awt.event.*;

class PopupMenuTest extends Frame implements ActionListener
{
     PopupMenu pm;
     MenuItem red,green,blue;
     public PopupMenuTest()
     {
           pm=new PopupMenu();
           red=new MenuItem("Red");
           green=new MenuItem("Green");
           blue=new MenuItem("Blue");
           red.addActionListener(this);
           green.addActionListener(this);
           blue.addActionListener(this);


           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 void actionPerformed(ActionEvent e)
     {
           String s=e.getActionCommand();
           if(s.equals("Red"))
                setBackground(Color.red);
           else if(s.equals("Green"))
                setBackground(Color.green);
           else
                setBackground(Color.blue);
     }
     public static void main(String args[])
     {
           new PopupMenuTest();
     }
}




Exception Handling

An exception is a runtime error that can be trapped at run time. It is a system to send an error message from the place an error has occurred to the place a method get called.

Java provides five keyword for exception handling

1.  try
2.  catch
3.  throw
4.  throws
5.  finally

try-catch is block of statements to execute some statements and trap the runtime errors.
try
{
     statements
}catch(classname refname)
{
     decision
}
One try can have many catch statements.

finally is again a block to always execute some code irrespective to some runtime error.


Every exception is a class inherited from Exception class and have Exception word associated with it.

Examples
     IOException
     NumberFormatException
     Etc.

Exception class provides some common methods for all the exception classes

     String getMessage()
     String toString()
     void printStackTrace()


Test Example

Write a program to input two numbers and print division of those numbers.

import java.io.*;
class Divide
{
     public static void main(String args[])    
     {
           BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
           try
           {
                System.out.print("Number 1 : ");
                int a=Integer.parseInt(br.readLine());

                System.out.print("Number 1 : ");
                int b=Integer.parseInt(br.readLine());
    
                int c=a/b;
                System.out.println("Dividion is : "+c);

           }
          
           catch(IOException ex)
           {
                System.out.println("Error Found : "+ex.getMessage());
           }
           catch(ArithmeticException ex)
           {
                System.out.println("Sorry! Denominator cannever be zero");
           }   
           catch(NumberFormatException ex)
           {
                //System.out.println(ex.getMessage());    
                //System.out.println(ex.toString());
                //System.out.println(ex); 
                //ex.printStackTrace();
                System.out.println("Sorry! Wrong Number");
           }
           catch(Exception ex)
           {
                System.out.println("Some error occured call on 989898998");         
                //ex.printStackTrace();
           }
           finally
           {   
                System.out.println("Thanks for using our system");
           }

     }
}


Note: If System.exit() is invoked then finally will not execute


throwstatement is used to throw an object of some exception kind of class.

Use throwskeyword to mark that a method throws some exception



Creating Custom Exceptions

Every exception is a class inherited from Exception class. Create your own class as exception class and inherit Exception class into it. Override the getMessage() and toString() methods


Example
Create an exception class as LowBalanceException to give a message as Sorry! Low Balance. Unable to withdraw.


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


Create a Customer class and create deposit() and withdraw() method. Throw an exception as LowBalanceException if the amount asked is more than balance.



class Customer
{
            int cid;
            String name;
            int balance;
            public Customer(int cid, String name, int opamount)
            {
                        this.cid=cid;
                        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;
            }
            void showBalance()
            {
                        System.out.println(balance);
            }
}

class SBI
{
            public static void main(String args[])
            {
                        Customer c=new Customer(555,"Rakesh",5000);
                        c.deposit(4000);
                        try
                        {
                                    c.withdraw(15000);
                        }catch(LowBalanceException ex)
                        {
                                    System.out.println(ex.getMessage());
                        }
                        c.showBalance();
            }
}


08.04.2011

Java Database Connectivity (JDBC)

Java is a front-end that can be connected with any kind of back-end like Oracle, MySql, MS Access etc.

Java provides all related classes and interfaces in java.sql package

Different classes and interfaces used for database programming are

1.  java.lang.Class class
2.  java.lang.System clas
3.  java.sql.DriverManager class
4.  java.sql.Connection interface
5.  java.sql.Statement interface
6.  java.sql.PreparedStatement interface
7.  java.sql.CallableStatement interface
8.  java.sql.ResultSet interface
9.  java.sql.ResultSetMetaData class

Generally Used databases

1.  MS Access
2.  Oracle
3.  MySql
4.  MS SQL Server

Steps to use the JDBC

1.  Create a database e.g. MS Access
a.  Batch13.mdb
or
b.  Batch13.accdb
2.  Create your tables
a.  Employee
                       i.   empid – Numeric – Primary Key
                     ii.   name - text
                    iii.   email - text
3.  Java provides a default driver to work with MS Access called as JDBC-ODBC Bridge
a.  sun.jdbc.odbc.JdbcOdbcDriver
4.  Open Database Connectivity (ODBC) is a Software from Microsoft to hide the database information from a Java Program
a.  It is provided under control panel
b.  To use a database using ODBC we need to create a Data Source Name (DSN)
5.  To use the MS Access as database with Java, we need to create a data source name (DSN) from control panel, administrative tools, odbc
a.  Select System DSN
b.  Add…
c.  Select Driver as Microsoft Access Driver (*.mdb)
d.  Select your database with Select… button
e.  Define the DSN Name e.g. batch13access
6.  Create a data entry form to save the data
7.  Create INSERT Command and test it

String sql="INSERT INTO employee VALUES("+txtEmpid.getText()+",'"+txtName.getText()+"','"+txtEmail.getText()+"')";     
System.out.println(sql);
8.  Load the Driver into memory
a.  Use any of three methods
                       i.   Class.forName(“drivername”);
                     ii.   System.setProperty(“jdbc.drivers”,”drivername”);
                    iii.   DriverManager.registerDriver(new drivername());
b.  Example
                       i.   Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
9.  Try to connect with database and get reference of it using getConnection() method of DriverManager class. It returns the reference as Connection type interface
a.  Connection cn=DriverManager.getConnection(“uri”,”login”,”password”);
b.  Example
                        i.   Connection cn=DriverManager.getConnection("jdbc:odbc:batch13access");
10. Create an object to run the statement pass the reference to some Statement type interface. Use createStatement() method of Connection reference.
a.  Statement st=cn.createStatement();
11. Execute the methods of Statement based on type of it
a.  executeUpdate(sql)
                        i.   for all NON-SELECT commands
b.  executeQuery(sql)
                        i.   for SELECT command only
12. Close the connection
a.  cn.close()

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class SaveEmployee extends Frame implements ActionListener
{
      Label lblEmpid,lblName,lblEmail;
      TextField txtEmpid,txtName,txtEmail;
      Button cmdSave;
      public SaveEmployee()
      {
            lblEmpid=new Label("Emp Id");
            lblName=new Label("Name");
            lblEmail=new Label("Email");
     
            txtEmpid=new TextField(20);
            txtName=new TextField(20);
            txtEmail=new TextField(20);

            cmdSave=new Button("Save");
            cmdSave.addActionListener(this);
           

            setLayout(new FlowLayout());
            add(lblEmpid);add(txtEmpid);
            add(lblName);add(txtName);
            add(lblEmail);add(txtEmail);
            add(cmdSave);

            setSize(250,200);
            setVisible(true);

      }
      public static void main(String args[])
      {

            new SaveEmployee();
      }
      public void actionPerformed(ActionEvent e)
      {
            String sql="INSERT INTO employee VALUES("+txtEmpid.getText()+",'"+txtName.getText()+"','"+txtEmail.getText()+"')";  
            //System.out.println(sql);
            try
            {
                  Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                  Connection cn=DriverManager.getConnection("jdbc:odbc:batch13access");
                  Statement st=cn.createStatement();
                  st.executeUpdate(sql);
                  cn.close();
                  System.out.println("Record Saved");
            }catch(Exception ex)
            {
                  System.out.println(ex.getMessage());     
            }    
     
      }
}    


Using MySql as Database

Install the software. It is a client/server database software placed on port number 3306 on current machine (localhost)

User Name: root
Password: pass

Create the database
            CREATE DATABASE batch13;

Make the database as current database
            USE batch13;

View the tables in MySql
            Show tables;

Create your tables
CREATE TABLE employee (empid int, name varchar(50), email varchar(50));

View Structure of the table

DESC employee

Load the Driver as
            com.mysql.jdbc.Driver

Create a URL to connect with database
            jdbc:mysql://localhost:3306/batch13

Using the driver we need the .jar file provided from mysql.com
We need to set a classpath



Example

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class SaveToMySql extends Frame implements ActionListener
{
            Label lblEmpid,lblName,lblEmail;
            TextField txtEmpid,txtName,txtEmail;
            Button cmdSave;
            public SaveToMySql ()
            {
                        lblEmpid=new Label("Emp Id");
                        lblName=new Label("Name");
                        lblEmail=new Label("Email");
           
                        txtEmpid=new TextField(20);
                        txtName=new TextField(20);
                        txtEmail=new TextField(20);

                        cmdSave=new Button("Save");
                        cmdSave.addActionListener(this);
                       

                        setLayout(new FlowLayout());
                        add(lblEmpid);add(txtEmpid);
                        add(lblName);add(txtName);
                        add(lblEmail);add(txtEmail);
                        add(cmdSave);

                        setSize(250,200);
                        setVisible(true);

            }
            public static void main(String args[])
            {

                        new SaveToMySql();
            }
            public void actionPerformed(ActionEvent e)
            {
                        String sql="INSERT INTO employee VALUES("+txtEmpid.getText()+",'"+txtName.getText()+"','"+txtEmail.getText()+"')";    
                        //System.out.println(sql);
                        try
                        {
                                    Class.forName("com.mysql.jdbc.Driver");
                                    Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/batch13","root","pass");
                                    Statement st=cn.createStatement();
                                    st.executeUpdate(sql);
                                    cn.close();
                                    System.out.println("Record Saved");
                        }catch(Exception ex)
                        {
                                    System.out.println(ex.getMessage());
                        }         
           
            }
}         

Using Parameter or place holders in SQL Statements

-          We can pass ? in place of the data and provide the data later on
-          Use setter methods to pass data later on
o   setXXX(column index, data)
-          Example
o   setInt()
o   setString()
o   setFloat()
o   setDouble()
o   setDate()
o   etc
-          Statement do not support the place holders
-          We need to use another interfaces PreparedStatement and CallableStatement
-          Use prepareStatement()and prepareCall() methods

PreparedStatement ps=cn.prepareStatement(sql);
ps.executeUpdate();




import java.awt.*;
import java.awt.event.*;
import java.sql.*;
class SaveToMySql extends Frame implements ActionListener
{
            Label lblEmpid,lblName,lblEmail;
            TextField txtEmpid,txtName,txtEmail;
            Button cmdSave;
            public SaveToMySql ()
            {
                        lblEmpid=new Label("Emp Id");
                        lblName=new Label("Name");
                        lblEmail=new Label("Email");
           
                        txtEmpid=new TextField(20);
                        txtName=new TextField(20);
                        txtEmail=new TextField(20);

                        cmdSave=new Button("Save");
                        cmdSave.addActionListener(this);
                       

                        setLayout(new FlowLayout());
                        add(lblEmpid);add(txtEmpid);
                        add(lblName);add(txtName);
                        add(lblEmail);add(txtEmail);
                        add(cmdSave);

                        setSize(250,200);
                        setVisible(true);

            }
            public static void main(String args[])
            {

                        new SaveToMySql();
            }
            public void actionPerformed(ActionEvent e)
            {
                        String sql="INSERT INTO employee VALUES(?,?,?)";

                        int empid=Integer.parseInt(txtEmpid.getText());
                        //System.out.println(sql);
                        try
                        {
                                    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
                                    Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/batch13","root","pass");
                                    PreparedStatement st=cn.prepareStatement(sql);
                                    st.setInt(1,empid);
                                    st.setString(2,txtName.getText());
                                    st.setString(3,txtEmail.getText());
                                    st.executeUpdate();
                                    cn.close();
                                    System.out.println("Record Saved");
                        }catch(Exception ex)
                        {
                                    System.out.println(ex.getMessage());
                        }         
           
            }
}         


13.04.2011

Reading data from database

-          Create a select command and use executeQuery() method
-          Pass the reference of the result into some ResultSet interface
-          To move the record pointer use the following methods
o   boolean first()
o   boolean last()
o   boolean next()
o   boolean previous()
-          To read data from current record use getter methods
o   getInt(column no or column name)
o   getString()
o   getFloat()
o   getDouble()
o   etc.

Example 1

WAP to read all the records in the employee table of mysql database on command prompt.

package batch13_1304;
import java.sql.*;
public class Main
{
    public static void main(String[] args) throws Exception
    {
        DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        String sql="Select * from employee";
        Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/batch13","root","pass");
        PreparedStatement ps=cn.prepareStatement(sql);
        ResultSet rs=ps.executeQuery();
        while(rs.next())
        {
            System.out.println(rs.getString(1)+","+rs.getString(2)+","+rs.getString(3));
        }
        cn.close();


    }

}

Example 2

WAP to read a record for given employee id, in the employee table of mysql database on command prompt.

import java.sql.*;
import java.util.Scanner;
public class ReadSingleRecord
{
    public static void main(String args[]) throws Exception
    {
        Scanner sc=new Scanner(System.in);
        System.out.print("Employee Id : ");
        int empid=sc.nextInt();

        System.setProperty("jdbc.drivers","com.mysql.jdbc.Driver" );

        String sql="Select * from employee where empid=?";
        Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/batch13","root","pass");
        PreparedStatement ps=cn.prepareStatement(sql);
        ps.setInt(1,empid);
        ResultSet rs=ps.executeQuery();
        if(rs.next())
            System.out.printf("Record found : name %s and email %s",rs.getString(2),rs.getString(3));
        else
            System.out.println("Sorry! Record Not found");
       cn.close();
    }
}

Example 3

Write a program to show records in GUI Application using four buttons First, Last, Prev, Next

import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class ReadDataGUI extends Frame implements ActionListener
{
    TextField t1,t2,t3;
    Button cmdFirst,cmdLast,cmdPrev, cmdNext;
    ResultSet rs;
    public ReadDataGUI()
    {
        t1=new TextField(20);
        t2=new TextField(20);
        t3=new TextField(20);

        cmdFirst=new Button("First");
        cmdLast=new Button("Last");
        cmdPrev=new Button("Prev");
        cmdNext=new Button("Next");

        cmdFirst.addActionListener(this);;
        cmdLast.addActionListener(this);;
        cmdPrev.addActionListener(this);;
        cmdNext.addActionListener(this);;


        try
        {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
            String sql="Select * from employee";
            Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/batch13","root","pass");
            PreparedStatement ps=cn.prepareStatement(sql);
            rs=ps.executeQuery();
            if(rs.next())
            {
                t1.setText(rs.getString(1));
                t2.setText(rs.getString(2));
                t3.setText(rs.getString(3));

            }
        }catch(Exception ex)
            {
                System.out.println(ex.getMessage());
            }

        setLayout(new FlowLayout());
        add(t1);add(t2);add(t3);
        add(cmdFirst);add(cmdLast);
        add(cmdPrev);add(cmdNext);
        setSize(300,300);
        setVisible(true);
    }
    public static void main(String args[])
    {
        new ReadDataGUI();
    }
    public void actionPerformed(ActionEvent e)
    {
        Button b=(Button)e.getSource();
        try
        {
            if(b==cmdFirst)
                rs.first();
            else if(b==cmdLast)
                rs.last();
            else if(b==cmdPrev)
                rs.previous();
            else
                rs.next();

            t1.setText(rs.getString(1));
            t2.setText(rs.getString(2));
            t3.setText(rs.getString(3));

        }catch(Exception ex)
        {
            System.out.println(ex.getMessage());
        }

    }
}




RelationTypes
  1. rtcode – Auto Number - PK
  2. rtname

Relatives
  1. rcode – Auto Number -PK
  2. rname
  3. email
  4. mobile
  5. rtcode - FK

Case 1: Using MS Access
import java.awt.*;
import java.awt.event.*;
import java.sql.*;

class RelationTypes extends Frame implements ActionListener
{

            Label lblRTName;
            TextField txtRTName;
            Button cmdSave;
            public RelationTypes()
            {
                        lblRTName=new Label("Relation Type");
                        txtRTName=new TextField(20);
                        cmdSave=new Button("Save");
                        cmdSave.addActionListener(this);
                       
                        setLayout(new FlowLayout());
                        add(lblRTName);add(txtRTName);
                        add(cmdSave);
                        setSize(200,200);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new RelationTypes(); 
            }
            public void actionPerformed(ActionEvent e)
            {
                        try
                        {

                                    System.setProperty("jdbc.drivers","sun.jdbc.odbc.JdbcOdbcDriver" );
                        String sql="INSERT INTO relationtypes(rtname) VALUES(?)";
                                    Connection cn=DriverManager.getConnection("jdbc:odbc:sample");
                        PreparedStatement ps=cn.prepareStatement(sql);
                                    ps.setString(1,txtRTName.getText());

                                    ps.executeUpdate();
                                    cn.close();
                                    javax.swing.JOptionPane.showMessageDialog(this,"Record has been Saved");
                                    txtRTName.setText("");
                                    txtRTName.requestFocus();//to set focus
                        }catch(Exception ex)
                        {
                                    javax.swing.JOptionPane.showMessageDialog(this,ex.getMessage());
                                   
                        }

            }
                       
}



import java.awt.*;
import java.awt.event.*;
import java.sql.*;

class Relatives extends Frame implements ActionListener
{

            Label lblRName,lblEmail,lblMobile,lblRelation;
            TextField txtRName,txtEmail,txtMobile;
            Choice cboRelation;
            Button cmdSave;
            public Relatives()
            {
                        lblRName=new Label("Name");
                        lblEmail=new Label("Email");
                        lblMobile=new Label("Mobile");
                        lblRelation=new Label("Relation");
                       
                       
                        txtRName=new TextField(20);
                        txtEmail=new TextField(20);
                        txtMobile=new TextField(20);
                        cboRelation=new Choice();
                       
                        try
                        {
                                    System.setProperty("jdbc.drivers","sun.jdbc.odbc.JdbcOdbcDriver" );
                        String sql="select * from relationtypes";
                                    Connection cn=DriverManager.getConnection("jdbc:odbc:sample");
                        PreparedStatement ps=cn.prepareStatement(sql);
                                    ResultSet rs=ps.executeQuery();
                                    while(rs.next())
                                    {
                                                cboRelation.add(rs.getString(2));
                                    }
                                    cn.close();
                        }catch(Exception ex)
                        {
                                    javax.swing.JOptionPane.showMessageDialog(this,ex.getMessage());
                        }
                       

                        cmdSave=new Button("Save");
                        cmdSave.addActionListener(this);
                       
                        setLayout(new FlowLayout());
                        add(lblRName);add(txtRName);
                        add(lblEmail);add(txtEmail);
                        add(lblMobile);add(txtMobile);
                        add(lblRelation);add(cboRelation);
                        add(cmdSave);
                        setSize(200,300);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new Relatives();         
            }
            public void actionPerformed(ActionEvent e)
            {
                        try
                        {
                                    System.setProperty("jdbc.drivers","sun.jdbc.odbc.JdbcOdbcDriver" );
                                    String sql="INSERT INTO relatives(rname,email,mobile,rtcode) VALUES(?,?,?,?)";
                                    Connection cn=DriverManager.getConnection("jdbc:odbc:sample");
                                    PreparedStatement ps=cn.prepareStatement(sql);
                                    ps.setString(1,txtRName.getText());
                                    ps.setString(2,txtEmail.getText());
                                    ps.setString(3,txtMobile.getText());
                                    ps.setInt(4,getRTCode(cboRelation.getSelectedItem()));
                                    ps.executeUpdate();
                                    cn.close();
                                   
                                    javax.swing.JOptionPane.showMessageDialog(this,"Record Saved");
                                   
                        }catch(Exception ex)
                        {
                                    javax.swing.JOptionPane.showMessageDialog(this,ex.getMessage());
                                   
                        }

            }

            int getRTCode(String RTName)
            {
                        int result=0;
                        try
                        {
                                    System.setProperty("jdbc.drivers","sun.jdbc.odbc.JdbcOdbcDriver" );
                        String sql="select rtcode from relationtypes where rtname=?";
                                    Connection cn=DriverManager.getConnection("jdbc:odbc:sample");
                        PreparedStatement ps=cn.prepareStatement(sql);
                                    ps.setString(1,RTName);
                                    ResultSet rs=ps.executeQuery();
                                   
                                    if(rs.next())
                                    {
                                                result=rs.getInt(1);
                                    }
                                    cn.close();
                                   
                        }catch(Exception ex)
                        {
                                    javax.swing.JOptionPane.showMessageDialog(this,ex.getMessage());
                        }
                        return result;
            }
}



Creating executable JAR

We need a file called manifest file (.mft) by defining the startup class using an entry

Main-Class: <classname>

Now use the JAR tool to create the .jar file using cvmf options

JAR cvmf filename.mft filename.jar <files to merge>
JAR cvfm filename.jar filename.mft <files to merge>




20.04.2011

What is Swing?

A Java API (javax.swing) which provided advance classed for GUI operations

It provides a collection of classes which are part of Java Foundation Class (JFC) hence most of the GUI classes starts with J

  1. JFrame
  2. JDialog
  3. JApplet
  4. JButton
  5. JTextField
  6. etc

Such control provide some additional features

  1. Multiple look and feels
  2. Using Hot keys
  3. Allows shortcut keys or KeyStroke
  4. Using Tooltips
  5. Using Images

Place the hot key

-          Use the setMnemonic() method
o   setMnemonic(char ch)
o   setMnemonic(int virtualkey)
-          Virtual keys are pre-defined constants under KeyEvent class
o   VK_A
o   VK_B
o   VK_1
o   VK_F1
o   VK_ENTER

Example

            JButton b=new JButton("Save");

            b.setMnemonic('S');
            or
            b.setMnemonic(KeyEvent.VK_S);

Placing the tooltips

Use setToolTipText() method

void setToolTipText(String text)

Placing Images

Use ImageIcon() class

Example
            JLabel l=new JLabel(new ImageIcon("filename.jpg"));
            JButton b=new JButton("Save", new ImageIcon("filename.jpg”));


Closing JFrame without event handling

JFrame class provides a method
            setDefaultCloseOperation(int operationtype)
                        JFrame.EXIT_ON_CLOSE
                        SwingConstants.HIDE_ON_CLOSE
                       

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class SwingTest extends JFrame
{         
            JLabel l1,l2;
            JButton b1, b2;
            public SwingTest()
            {
                        l1=new JLabel("Katrina");
                        l2=new JLabel(new ImageIcon("images/4.jpg"));
                        b1=new JButton("Delete",new ImageIcon("images/delete.gif"));
                        b2=new JButton("Save",new ImageIcon("images/save.gif"));
                       
                        b1.setToolTipText("Delete a record");
                        b2.setToolTipText("Save a record");

                        b1.setMnemonic('D');
                        b2.setMnemonic(KeyEvent.VK_S);

                        setLayout(new FlowLayout());
                        add(l1);add(l2);
                        add(b1);add(b2);
                       
                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        setSize(300,300);
                        setVisible(true);

            }
            public static void main(String args[])
            {
                        new SwingTest();
            }

}


Advancement to in Menus

-          We can apply the keystrokes
-          Use KeyEvent class to provide the key combination along with masking keys (Shift, Ctrl, Alt) provided in Event class
o   SHIFT_MASK
o   CTRL_MASK
o   ALT_MASK

Example

Make a keystroke for Ctlr+Shift+F9

KeyStroke k=KeyStroke.getKeyStroke(KeyEvent.VK_F9, Event.CTRL_MASK+Event.SHIFT_MASK);

Attach the keystroke to a menu item mnuSave



26.04.2011

About the swing containers

Every swing container is made of different layers like

  1. Root Pane
  2. Glass Pane
  3. Content Pane

All items in a container get placed on the Content Pane.

To get reference of the content pane use getContentPane()method

Using some dialogs in Swings

  1. JColorChooser
  2. JFileChooser
  3. JOptionPane


JColorChooser class
-          Allows to select a color
o   public static Color showDialog(parent, caption,default color)

Example

Color c=JColorChooser.showDialog(this,"Select a new Color",Color.white);

JFileChooser class

A class which allows to select a file to open or save

Note: While using dialogs on button or menus use … (ellipses) to indicate a dialog

JFileChooser jc=new JFileChooser();


int showDialog(parent)
int showDialog(parent, text on approve button)

It returns a value which can be

APPROVE_OPTION
CANCEL_OPTION
ERROR_OPTION

Example
public void actionPerformed(ActionEvent e)
    {
        JFileChooser jc=new JFileChooser();
        if(e.getSource()==open)
        {
           int ans= jc.showDialog(this,"Open");
           if(ans==JFileChooser.APPROVE_OPTION)
           {
                JOptionPane.showMessageDialog(this, jc.getSelectedFile());
           }
        }
        else
            jc.showDialog(this,"Save");
    }


JOptionPane class

To show a dialog for message, input or confirmation



import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import static javax.swing.JOptionPane.*;
class JOptionPaneTest extends JFrame implements ActionListener
{
            JButton b1,b2,b3;
            JOptionPaneTest()
            {
                        b1=new JButton("Message");
                        b1.setBounds(20,50,100,50);
                        b1.setToolTipText("Click Me for Message");
                        b2=new JButton("Input");
                        b2.setBounds(20,120,100,50);
                        b2.setToolTipText("Click Me for Input");
                        b3=new JButton("Confirmation");
                        b3.setBounds(20,200,100,50);
                        b3.setToolTipText("Click Me to confirm");

                        Container cn=getContentPane();
                        cn.setLayout(null);
                        cn.add(b1);
                        cn.add(b2);
                        cn.add(b3);
                        b1.addActionListener(this);
                        b2.addActionListener(this);
                        b3.addActionListener(this);

            }
            public void actionPerformed(ActionEvent e)
            {
                        JButton b=(JButton)e.getSource();
                        if(b==b1)
                        {
                                    //showMessageDialog(this,"Welcome to Dialogs","Impeccable",INFORMATION_MESSAGE );
                                    showMessageDialog(this,"Welcome to Dialogs","Impeccable",PLAIN_MESSAGE,new ImageIcon("images/book.gif"));
                        }
                        else if(b==b2)
                        {
                                    String s[]={"TV","VCR","CAR","MOBILE"};
                                    //String name=(String)showInputDialog(this,"Select an item","Items",PLAIN_MESSAGE, new ImageIcon("images/book.gif"),s,"CAR");
                                    String name=(String)showInputDialog(this,"Type name of an item","Items",INFORMATION_MESSAGE);

                                    showMessageDialog(this,"You selected "+name);
                        }
            else
            {
                        int choice=showConfirmDialog(this,"Are you adult","Query",OK_CANCEL_OPTION,QUESTION_MESSAGE);
                        if(choice==OK_OPTION)
                                    showMessageDialog(this,"You can join us");
                        else
                                    showMessageDialog(this,"Sorry! You can't join us");
            }
            }
            public static void main(String args[])
            {
                        JOptionPaneTest jpt=new JOptionPaneTest();
                        jpt.setSize(300,300);
                        jpt.setVisible(true);
            }
}


Creating a Toolbar

Use JToolBar class

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
class JToolBarTest extends JFrame
{
            public JToolBarTest()
            {
                        JToolBar jt=new JToolBar();
                        JButton b1=new JButton(new ImageIcon("images/yellow-ball.gif"));
                        JButton b2=new JButton(new ImageIcon("images/red-ball.gif"));
                        JButton b3=new JButton(new ImageIcon("images/blue-ball.gif"));
                        JButton b4=new JButton(new ImageIcon("images/exit.gif"));                                             
                        b4.addActionListener(new ActionListener()
                        {
                                    public void actionPerformed(ActionEvent e)
                                    {
                                                System.exit(0);
                                    }
                                   
                        });
                       
                       
                        b1.setToolTipText("Yellow");
                        jt.add(b1);
                        jt.add(b2);
                        jt.add(b3);
                        jt.add(b4);
                       
                        add(jt,"North");
                        setSize(300,300);
                        setVisible(true);
            }
            public static void main(String args[])
            {
                        new JToolBarTest();
            }
}

Using Multiple Look and Feels

Swing provides default look and feel as Metal along with two other look and feels Window and Motif.

Use UIManager class to define a look and feel with setLookAndFeel() method

Use SwingUtilities class to apply the style using updateComponentTreeUI() method

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class LookAndFeel extends JFrame implements ActionListener
{
            JMenuBar mb;
            JMenu mnuChangeLook;
            JMenuItem miWindow,miMotif,miMetal;
            JTextField t1,t2,t3;
            JButton b1,b2,b3;
            public LookAndFeel()
            {
                        mb=new JMenuBar();
                        mnuChangeLook=new JMenu("ChangeLook");
                        miWindow=new JMenuItem("Window");
                        miMotif=new JMenuItem("Motif");
                        miMetal=new JMenuItem("Metal");
                        mnuChangeLook.add(miWindow);
                        mnuChangeLook.add(miMotif);
                        mnuChangeLook.add(miMetal);
                        mb.add(mnuChangeLook);

                        miWindow.addActionListener(this);
                        miMetal.addActionListener(this);
                        miMotif.addActionListener(this);

                        t1=new JTextField(10);
                        t2=new JTextField(10);
                        t3=new JTextField(10);
                        b1=new JButton("First");
                        b2=new JButton("Second");
                        b3=new JButton("Third");

                        setLayout(new FlowLayout());
                        add(t1);add(t2);add(t3);
                        add(b1);add(b2);add(b3);

                        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                        setJMenuBar(mb);
                        setSize(300,300);
                        setVisible(true);

            }

            public void actionPerformed(ActionEvent e)
            {
                        try
                        {
                                    if(e.getSource()==miWindow)
                                                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                                    else if(e.getSource()==miMetal)
                                                UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
                                    else
                                                UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
           
                                    SwingUtilities.updateComponentTreeUI(getContentPane());
                        }catch(Exception ex)
                        {
                                    JOptionPane.showMessageDialog(this,ex.getMessage());
                        }
            }
            public static void main(String args[])
            {         
                        new LookAndFeel();
            }

}

String Handling
File Handling
Networking or Socket Programming
Multi Threading
Utilities


String Handling

To manage the string Java provides three classes

  1. String
  2. StringBuilder class
  3. StringBuffer class

String class is immutable and StringBuffer and StringBuilder classes are mutable.

StringBuffer and StringBuilder classes allows to append the data in same location without wasting the memory space.

            public void append()

String class provides commonly used methods on the strings

  1. String toUpperCase()
  2. String toLowerCase()
  3. boolean equals(String s)
  4. boolean startsWith(String s)
  5. boolean endsWith(String s)
  6. int indexOf(String s)
    1. Returns the position in the string or -1 if not found
  7. char charAt(int index)


StringBuilder or StringBuffer class

-          Both classes provide append() method to append kind of data without wasting the memory
-          They also provide reverse()method

class StringBuilderTest
{
            public static void main(String args[])
            {
                        StringBuilder sb=new StringBuilder();
                        sb.append("Amit ");
                        sb.append("Kumar");

                        System.out.println(sb);
                        System.out.println(sb.reverse());
            }
}


Collections
Generic
Auto Boxing and Auto un-boxing

Collections

Special type of classes to manage dynamic set of objects. Java provides two kinds of collections

Legacy collections
Framework based collections

All collections are provided under java.util package.

Legacy classes are provided from Java 1.0 and have their own pre-defined methods

  1. Vector class
  2. Hashtable class
  3. Enumeration interface

Using Vector class

To manage single set of dynamic objects.

            Vector()
            void addElement(Object x)
            Object elementAt(int index)
            int size()
           

Example
Create a Vector to hold multiple kind of data

import java.util.*;
class VectorTest
{
            public static void main(String args[])
            {
                        Vector v=new Vector();
                        v.addElement(new Integer(56));
                        v.addElement(new String("Hello"));
                        v.addElement(new Double(4.5));
                        v.addElement(new Date());
                       
                        System.out.println("Total elements : "+v.size());
                        for(int i=0;i<v.size();i++)
                                    System.out.println(v.elementAt(i));
            }
}

Example 2

Show only Integer type data

Note: Use instanceofoperator

 import java.util.*;
class VectorTest2
{
            public static void main(String args[])
            {
                        Vector v=new Vector();
                        v.addElement(new Integer(56));
                        v.addElement(new String("Hello"));
                        v.addElement(new Double(4.5));
                        v.addElement(new Date());
                        v.addElement(new Integer(34));
                       
                        System.out.println("Total elements : "+v.size());
                        for(int i=0;i<v.size();i++)
                        {
                                    if(v.elementAt(i) instanceof Integer)
                                                System.out.println(v.elementAt(i));
                        }
            }
}

Example 3

Show the numbers. Also show the sum of numbers

import java.util.*;
class VectorTest3
{
            public static void main(String args[])
            {
                        Vector v=new Vector();
                        v.addElement(new Integer(56));
                        v.addElement(new String("Hello"));
                        v.addElement(new Double(4.5));
                        v.addElement(new Date());
                        v.addElement(new Integer(34));
                       
                        System.out.println("Total elements : "+v.size());
                        int sum=0;
                        for(int i=0;i<v.size();i++)
                        {
                                    if(v.elementAt(i) instanceof Integer)
                                    {
                                                System.out.println(v.elementAt(i));
                                                Integer ig=(Integer) v.elementAt(i);
                                                sum=sum+ig.intValue();
                                    }
                        }
                        System.out.println("Sum is :" +sum);
            }
}




Generics

Special collection classes which allow to hold different kind of data by different objects of same class.

Examples
ArrayList
LinkedList
HashMap
HashSet

Using ArrayList class

Allows to work as generic and non-generic

Non-Generic Type

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


import java.util.*;
class ArrayListTest
{
            public static void main(String args[])
            {
                        ArrayList v=new ArrayList();
                        v.add(new Integer(56));
                        v.add(new String("Hello"));
                        v.add(new Double(4.5));
                        v.add(new Date());
                        v.add(new Integer(34));
                       
                        System.out.println("Total elements : "+v.size());
                        int sum=0;
                        for(int i=0;i<v.size();i++)
                        {
                                    if(v.get(i) instanceof Integer)
                                    {
                                                System.out.println(v.get(i));
                                                Integer ig=(Integer) v.get(i);
                                                sum=sum+ig.intValue();
                                    }
                        }
                        System.out.println("Sum is :" +sum);
            }
}


Generic Style

import java.util.*;
class GenericTest
{
            public static void main(String args[])
            {
                        ArrayList<Integer> v=new ArrayList<Integer>(); //type-safe
                        v.add(new Integer(56));
                        v.add(new Integer(34));
                       
                        System.out.println("Total elements : "+v.size());
                        int sum=0;
                        for(int i=0;i<v.size();i++)
                        {
                                   
                                                System.out.println(v.get(i));
                                                sum=sum+v.get(i).intValue();
                                   
                        }
                        System.out.println("Sum is :" +sum);
            }
}


Auto Boxing and Auto UnBoxing

Auto boxing means conversion from value type to reference type and auto unboxing means conversion from reference type to value

Integer x=56; // auto boxing

int y=x+6; // auto unboxing


import java.util.*;
class BoxingUnboxig
{
            public static void main(String args[])
            {
                        ArrayList<Integer> v=new ArrayList<Integer>();
                        v.add(56); //auto boxing
                        v.add(34);
                       
                        System.out.println("Total elements : "+v.size());
                        int sum=0;
                        for(int i=0;i<v.size();i++)
                        {
                                   
                                                System.out.println(v.get(i));
                                                sum=sum+v.get(i); //auto unboxing
                                   
                        }
                        System.out.println("Sum is :" +sum);
            }
}


Using Hashtable class


A class to manage key/value pairs

            Hashtable()
            void put(Object key, Object value)
            Object get(Object key)
            Enumeration keys()

Enumeration interface

An interface used to hold reference of some keys

            boolean hasMoreElements()
            Object nextElement()


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

                        System.out.println(t.get("pk"));

                        Enumeration e=t.keys();
                        while(e.hasMoreElements())
                        {
                                    Object key=e.nextElement();
                                    System.out.println(key+"/"+t.get(key));
                        }
            }
}








28.04.2011

Framework based collections

A set of collections introduced in Java 1.2

All such collections are inherited from Collection interface. It has three child interfaces

1.      List interface
a.       Single set of elements with duplicate allowed
2.      Set interface
a.       Single set of element but not allow duplicates
3.      Map interfere
a.       To manage key/value pairs


LinkedList class

-          A class which provide additional methods single set of operations

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 class

To manage the values on stack. Provides three methods

1.      push()
2.      pop()
3.      peek()

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

            }
}


Using HashMap class as Generic

import java.util.*;
class HashMapTest
{
            public static void main(String args[])
            {
                        HashMap<String,String> t=new HashMap<String,String>();
                        t.put("in","India");
                        t.put("ch","China");
                        t.put("pk","Pakistan");

                        System.out.println(t.get("pk"));
           
            }
}


Multi Threading

A thread is a light weight process within a process. Java provides Thread class and Runnable interface to implement the multi Threading.

Runnable interface provides a run() method to define the working of a thread

All Java classes are single threaded by default. One thread is always present called as main thread.


Methods of Thread class

            Thread(Runnanble r)
            Thread(Runnanble r,String threadname)

            Thread currentThread()
            String getName()
            int getPriority()
            void start()  à to send a thread in thread queue
            void sleep(int ms) throws InterruptedException
            void sleep(int ms, int ns) throws InterruptedException



Example 1

class ThreadTest
{
            public static void main(String args[])
            {
                        Thread t=Thread.currentThread();
                        if(t!=null)
                                    System.out.println("Thread found : "+t.getName());
                        else
                                    System.out.println("No thread found");
                                   
            }
}


Life Cycle of Thread

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

Creating threads without any name

class MyThread implements Runnable
{
            public MyThread()
            {
                        Thread t=new Thread(this);
                        t.start();
            }
            public void run()
            {
                        String s=Thread.currentThread().getName();
                        for(int i=1;i<=10;i++)
                                    System.out.println(s+" : "+i);
            }
            public static void main(String args[])
            {
                        new MyThread();
                        new MyThread();
                        new MyThread();
            }
}

Creating Thread with name

class MyThread implements Runnable
{
            public MyThread(String tname)
            {
                        Thread t=new Thread(this,tname);
                        t.start();
            }
            public void run()
            {
                        String s=Thread.currentThread().getName();
                        for(int i=1;i<=10;i++)
                                    System.out.println(s+" : "+i);
            }
            public static void main(String args[])
            {
                        new MyThread("Pepsi");
                        new MyThread("Coke");
                        new MyThread("Fanta");
            }
}

Providing Different task for different threads

class MyThread implements Runnable
{
            public MyThread(String tname)
            {
                        Thread t=new Thread(this,tname);
                        t.start();
            }
            public void run()
            {
                        String s=Thread.currentThread().getName();
                        if(s.equals("Pepsi"))
                        {
                                    for(int i=1;i<=10;i++)
                                                System.out.println(s+" : "+i);
                        }
                        else if(s.equals("Coke"))
                        {
                                    for(char ch='A';ch<='Z';ch++)
                                                System.out.println(s+" : "+ch);
                       
                        }
                        else
                        {
                                    for(int n=5;n<=100;n+=5)
                                                System.out.println(s+" : "+n);
                        }
            }
            public static void main(String args[])
            {
                        new MyThread("Pepsi");
                        new MyThread("Coke");
                        new MyThread("Fanta");
            }
}


Using sleep time

class MyThread implements Runnable
{
            public MyThread(String tname)
            {
                        Thread t=new Thread(this,tname);
                        t.start();
            }
            public void run()
            {
                        String s=Thread.currentThread().getName();
                        if(s.equals("Pepsi"))
                        {
                                    for(int i=1;i<=10;i++)
                                    {
                                                System.out.println(s+" : "+i); 
                                                try{Thread.sleep(5);}catch(Exception ex){}
                                    }
                        }
                        else if(s.equals("Coke"))
                        {
                                    for(char ch='A';ch<='Z';ch++)
                                    {
                                                System.out.println(s+" : "+ch);
                                                try{Thread.sleep(1);}catch(Exception ex){}
                                    }
                       
                        }
                        else
                        {
                                    for(int n=5;n<=100;n+=5)
                                    {
                                                System.out.println(s+" : "+n);
                                                try{Thread.sleep(6);}catch(Exception ex){}
                                    }
                        }
            }
            public static void main(String args[])
            {
                        new MyThread("Pepsi");
                        new MyThread("Coke");
                        new MyThread("Fanta");
            }
}

No comments:

Post a Comment