• No results found

Java

N/A
N/A
Protected

Academic year: 2021

Share "Java"

Copied!
118
0
0

Loading.... (view fulltext now)

Full text

(1)

12.02.2010

What is Java?

Java is a technology from Sun overtaken by Oracle developed by James Gosling in 1991 with initial name ‘Oak’ with the goal to work with any kind of device.

It was renamed to Java in 1995. It is divided in four sub-technologies

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

Resource

http://java.sun.com Tools Required

1. JDK (Java Development Kit) 2. JRE (Java Runtime Environment)

3. IDE (Integrated Development Environment) a. NetBeans b. Eclipse c. Visual Age d. JDeveloper e. JCreator f. Etc. Versioning in Java

Java provides two kinds of version 1. Product Version 2. Developer Version Developer Version Deals with JDK  1.0  1.1  1.2  1.3  1.4  1.5

(2)

1.6

1.7 Product Version

Product version deals with Java as product which shows the reliability, scalability and strength of Java.  1.0  1.1  1.2 (Java 2)  1.3  1.4  5.0  6.0  7.0 Rules in Java

1. Java is case sensitive 2. File extension will be .java 3. Compiler used is JAVAC.EXE Introduction to PATH

PATH is an environmental variable used to hold list of folders to search an executable file (.exe, .com, .bat) in given folders.

Setting temporary PATH

SET PATH=%PATH%;C:\jdk1.6\bin Set Permanent Path

My Computer  Properties  Advanced  Environmental Variables  System Variables  PATH  Edit…  Add your path

Syntactical Rules in Java

1. All keyword and package names must be in lower case

2. All class and interface names starts with upper case. (PascalCase) a. Math, System, BufferedReader, InputStreamReader 3. All fields and methods starts with lower case (camelCase)

a. length(), parseInt() Features of Java

(3)

2. Secure 3. Object Oriented 4. Multi Threaded 5. Portable 6. Platform Independent 7. Robust

a. Java provides a big set of libraries for almost any purpose

b. Java provides built-in garbage collector for automatic memory management c. Java provides in-built features exception handling to trap the runtime errors 13.02.2011

What makes Java Platform Independent? Is JVM is platform Independent?

Java provides a software called JRE (Java Runtime Environment) which contains sub softwares like Java Virtual Machine (JVM) and Garbage Collector.

JVM contains other software like Class Loader, Code Verifier and Just-in-time compiler (JIT)

.java  JAVAC  .class (byte code language)  JVM (Class Loader  Coder Verifier  JIT  Binary Code)  Execution

JVM is a machine dependent software but makes the Java platform Independent. Writing First Java Program

1. File Name must be .java

2. Every executable class must have an entry point called main() a. public static void main(String args[])

Hierarchy in Java

JAR File  package  class  field, methods and static objects

JAR is Java Archive. It is a compressed file created from JAR.EXE tool. It contains a set of packages.

A package is a collection of related set of class.  java.lang

o A package that provides commonly used classes

o Math, String, System, Integer, Float, Double, Character etc. o It is by default

 java.io  java.util  java.awt  java.awt.event

(4)

 javax.swing  java.sql  javax.servlet  javax.servlet.jsp  javax.servlet.jsp.tagext  etc.

Working with General Input/Output Operations - Java provides in-built object inside System class

o in o out o err

- in is a 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 PrintStream class

- print() - println() - printf() //First.java class Sample {

public static void main(String args[]) {

System.out.printf("Hello to Java"); }

}

Compiling the Program JAVAC <programname.java> Example

JAVAC First.java  Sample.class Running a class

Use JAVA.EXE tool JAVA <classname> Example

JAVA Sample

(5)

1. A file name can be upto 255 characters including space and extension 2. A program can have many classes

3. All or none of the classes can have the main()

4. Program name and class name can be same or different except if the class is public then both must be same

Using NetBeans 6.9.1 public class Sample {

public static void main(String[] args) {

int a=5,b=6;

System.out.printf("Product of %d and %d is %d",a,b,a*b); }

}

Data Types in Java

Special keyword used to define type of data and range of data. Can be of two types

1. Primitive Types 2. User Defined Types Primary Types can be Integrals (All are signed)

1. byte – 1 byte 2. short – 2 byte 3. int - 4 bytes 4. long - 8 bytes Floating 1. float - 4 bytes 2. double - 8 bytes Characters

1. char - 2 bytes (Unicode) Booleans

1. boolean – 2 bytes Literals or Constant Values

The values that we use from our side for assignment or some expression are called as literals.

Integrals

- Default is int

(6)

o int num=10; o long p=5L; Floatings

- Default is double

o Use f or F with floats o double num=5.6;

o float k=5.6; //compile time error o float k=5.6F; //compile time error Character Literals

- Enclosed in single quotes o char ch=’A’; String Literals

- All strings are Managed by String class - Enclosed in double quotes

(7)

19.02.2011

Using classes from different packages Use import command

To import specific class

import <packagename.classname>; To import all classes of a package

import <packagenme.*>; Example

import java.io.*;

import java.util.Scanner;

Using Scanner class of java.util package to read the data from Keyboard Create an object of Scanner class

Scanner sc=new Scanner(System.in); Different methods of Scanner class

String next() int nextInt() float nextFloat() double nextDouble() Example

WAP to input name and age of a person and check it to be valid voter. import java.util.Scanner;

class Voter {

public static void main(String args[]) {

Scanner sc=new Scanner(System.in); System.out.print("Name : ");

String name=sc.next(); System.out.print("Age : "); int age=sc.nextInt(); if(age>=18)

System.out.printf("Dear %s you can vote",name); else

System.out.println("Dear "+name+" you cannot vote"); }

(8)

Importing the static members of the class Use import static keyword

Example

import static java.lang.System.*; import static java.lang.Math.*; Full Code

import static java.lang.System.*; import java.util.Scanner;

public class Voter {

public static void main(String[] args) {

Scanner sc=new Scanner(in); out.print("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 cannot vote",name); }

}

Reading data using BufferedReader class of java.io package

When we input data from keyboard (System.in), a stream of bits get passed and provided to object of another class InputStreamReader which convert the bit pattern into a character. These characters get buffered into memory space using another class BufferedReader. Use readLine() method of BufferedReader class to read the data.

public String readLine() throws IOException

Wrapper Classes

Special classes under java.lang package, corresponding to some data type which provides advance functionality on data types as well conversion from String type to numeric types.

(9)

Data Type Wrapper Class byte Byte short Short int Integer long Long float Float double Double char Character boolean Boolean Example

WAP to input a number and convert into octal, hexa decimal and binary. Check a character to be alphabet, digit and special character.

public class WrapperTest {

public static void main(String args[]) { int num=3456; 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"); }

}

Conversion from String type to numeric type

datatype variable=wrapperclass.parseDatatype(stringdata); Example

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

double basic=Double.parseDouble(br.ReadLine()); Mixing Scanner and BufferedReader

import static java.lang.System.*; import java.io.*;

import java.util.Scanner; public class Mix

(10)

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)

out.printf("Dear %s you can vote", name); else

out.printf("Dear %s you cannot vote",name); }

}

Creating static objects

We can define static objects in some class and access them any time in any class import static java.lang.System.*;

import java.io.*;

import java.util.Scanner; public class MyClass {

public static Scanner sc=new Scanner(in);

public static BufferedReader br=new BufferedReader(new InputStreamReader(in)); }

Using Static objects

import static java.lang.System.*; import java.io.*;

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)

out.printf("Dear %s you can vote", name); else

out.printf("Dear %s you cannot vote",name); }

(11)

}

20.02.2011 What is Class? What is Object? What is Reference?

How object different from Reference? What is Class?

A class is a set of specifications or blueprint about an entity to create similar set of objects. A class defines a set of attributes and behavior about the entity. A class is user defined data type created with class keyword.

class <classname> {

//members }

Members inside a class

A class can have three kinds of members Fields or Attributes

Methods or Behaviors Static Objects

Types of class members

These members can be categorized in two categories 1. Static or Class Members

2. Non-Static or instance members

Class members do not require an object to use them but can be used though the objects. Use static keyword with such members.

Instance members always require an object. What is an object?

A real entity created based on class specifications is called object or instance. Use new keyword along with special method called Constructor to create an object.

To use the object for different operations we need to hold reference of it. <classname> <referencename>=new <constructor>(<arguments>); Example

(12)

Number y=new Number(); What is a Constructor?

A constructor is a special method inside a class having some features 1. Same name as class

2. No return type

3. Used to initialized fields of an object

4. If no constructor is created then default or blank constructor is created

automatically, but if create any parameterized constructor then blank constructor is not created automatically, we have to create it, if required.

5. Constructors can be overloaded 6. Constructor can be private as well Note:

 Use JAVAP tool of JDK to view members inside a class.  Data can be passed to the instance variable using two ways

i. Using constructor ii. Using methods E.g.

JAVAP Number Example 1

Create a class Number having a num as field to get the data. Create some methods like square(), cube(), cuberoot() on data. Pass data to num using a method like setNumber(). class Number { double num; void setNumber(double n) { num=n; }

double square() //non-static {

return num*num; }

double cube() //non-static {

return square()*num; }

double cubeRoot() //non-static {

return Math.pow(num,1.0/3); }

(13)

class Test {

public static void main(String args[]) {

Number x=new Number(); Number y=new Number(); x.setNumber(6); y.setNumber(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot()); } } Example 2

Create a class Number having a num as field to get the data. Create some methods like square(), cube(), cuberoot() on data. Pass data to num using a constructor.

class Number { double num; Number(double n) { num=n; }

double square() //non-static {

return num*num; }

double cube() //non-static {

return square()*num; }

double cubeRoot() //non-static { return Math.pow(num,1.0/3); } } class Test {

public static void main(String args[]) {

Number x=new Number(6); Number y=new Number(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot());

(14)

} }

Example 3

Create a class Number having a num as field to get the data. Create some methods like square(), cube(), cuberoot() on data. Pass data to num using a constructor or using a method. class Number { double num; Number() { } Number(double n) { num=n; } void setNumber(double n) { num=n; }

double square() //non-static {

return num*num; }

double cube() //non-static {

return square()*num; }

double cubeRoot() //non-static { return Math.pow(num,1.0/3); } } class Test {

public static void main(String args[]) {

Number x=new Number(); x.setNumber(6);

Number y=new Number(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot()); }

(15)

Example 4

What happens when parameter name and field names are same. In such cases use this keyword to refer the current object

class Number { double num; Number() { } Number(double num) { this.num=num; }

void setNumber(double num) {

this.num=num; }

double square() //non-static {

return num*num; }

double cube() //non-static {

return square()*num; }

double cubeRoot() //non-static { return Math.pow(num,1.0/3); } } class Test {

public static void main(String args[]) {

Number x=new Number(); x.setNumber(6);

Number y=new Number(9); System.out.println(x.cubeRoot()); System.out.println(y.cubeRoot()); }

}

Assignment

Create a class Customer having fields accno, name and balance. Create constructor to open an account. Create methods deposit(), withdraw() and showBalance().

(16)

class Customer {

int accno; String name; double balance;

Customer(int accno, String name, double opamount) {

this.accno=accno; this.name=name; balance=opamount; }

void deposit(double amount) {

balance+=amount; }

void withdraw(double amount) {

balance-=amount; }

void showBalance() {

System.out.println("Current Balance is : "+balance); }

}

class ICICI {

public static void main(String args[]) {

Customer c=new Customer(123,"Amit Verma",9000); c.deposit(5000); c.withdraw(3400); c.showBalance(); } } Home assignment

Create a class Book having field bookno, title, author, status, lastissuedate and price. Create constructors and methods to create an instance of book.

Create method issue(), receive() and isavailable(), getIssueDate(). Test the application with three books.

Solution

public class Book {

(17)

int bookno; String title,author,lastissuedate=null; boolean status=true; double price; public Book() { }

public Book(int bookno, String title, String author, double price) { this.bookno=bookno; this.title=title; this.author=author; this.price=price; } String getTitle() { return title; }

void setData(int bookno, String title, String author, double price) { this.bookno=bookno; this.title=title; this.author=author; this.price=price; }

public void issue(String issuedate) {

lastissuedate=issuedate; status=false;

}

public String getIssueDate() {

return lastissuedate; }

public boolean isAvailable() {

return status; }

public void recieve(String rcvdate) {

lastissuedate=null; status=true; }

public static void main(String[] args) {

Book b[]=new Book[3];

(18)

b[1]=new Book(13,"Programming in Java","James Gosling",750); b[2]=new Book(15,"Programming in .NET","Microsoft Press",567); b[0].issue("12-Feb-2011");

if(b[0].isAvailable())

System.out.println("Book "+b[0].getTitle()+ " is avaible"); else

System.out.println("Book "+b[0].getTitle()+ " is not availble");

} }

(19)

26.02.2011 Pillars of OOPs Encapsulation

It stats that place all the members of a class under one body. class <classname>

{

//members }

Abstraction

Java provides four abstraction layers to control the accessibility of members. - Private

o Within the class - Public

o Anywhere access - Protected

o In current class or in child class - Package (default)

o Within the package or current folder

What is a package? How to create a package? How to use a package? How to distribute a package? What is JAR?

Package

A package is a folder having related set of classes which can be bundled into a JAR or ZIP file.

Each of the classes placed in a package must have package command on top.

package <packagename>; How to create a package?

Create a folder to hold your packages. e.g. d:\pkg17

(20)

e.g. testpackage

Now create the classes and place into this package folder. Each of such classes must have package command on top.

package testpackage; public class General {

public static long factorial(int n) { if(n==0 || n==1) return 1; else return n*factorial(n-1); } }

Using the package

- Import the classes of the package

- Set the classpath to lookup the classes and package on the disc Set classpath=%classpath%;d:\pkg17;

package testpackage; public class General {

public static long factorial(int n) { if(n==0 || n==1) return 1; else return n*factorial(n-1); } }

Distributing the package

Convert the folder into a JAR or ZIP

To create the zip file, select all the package and convert into a zip file and set into classpath Example

set classpath=%classpath%;c:\testpackage.zip; Creating JAR files (Java Archive)

(21)

c – for create t – for Tabulate x – for Extract v – for Verbose f – for File Name

JAR cvf <filename.jar> <file list> Example

First goto the folder having packages JAR cvf test.jar .

Now set the test.jar file into classpath set classpath=%classpath%;c:\test.jar;

27.02.2011 Polymorphism

When an items can perform more than one task, it is called as polymorphism. It is a concept which get implemented using overloading.

Java allows only method overloading.

When two or more methods have the same name but different number of arguments or type of arguments, called as method overloading.

Return type do not participate in overloading. Example

Create a class Test having three methods to calculate area of circle, square and rectangle. class Test

{

public void area(int side) {

System.out.println("Square is "+side*side); }

public void area(double r) {

System.out.println("Square is "+Math.PI*r*r); }

public void area(int l, int w) {

System.out.println("Area is "+l*w); }

(22)

Inheritance

Most important pillar of OOPs which provides re-usability of code. Classes can be at three levels

1. Parent class 2. Super class 3. Child class

All classes in Java are child of Object class. Java allows only single inheritance.

Use extends keyword to inherit a class into other class. class A { } class B extends A { }

If B is a current class, A is 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 Num2 having two fields a, b. Create methods to return bigger one and product of those numbers.

Create another class Num3 working on three numbers. Also create method for product and biggest one.

Use inheritance. class Num2 {

int a,b;

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

(23)

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 int g3() { return g2()>c?g2():c; } } class IntTest {

public static void main(String args[]) {

Num3 x=new Num3(4,5,6); System.out.println(x.p3()); }

}

Method Overriding

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

While overriding we can increase the scope of overridden method but cannot decrease it. class Num2

{

int a,b;

public Num2(int a, int b) {

this.a=a; this.b=b; }

public int greatest() {

(24)

return a>b?a:b; }

public int product() {

return a*b; }

}

class Num3 extends Num2 {

int c;

public Num3(int a, int b, int c) {

super(a,b); this.c=c; }

public int product() //overriding {

return super.product()*c; }

public int greatest() //overriding { return super.greatest()>c?super.greatest():c; } } class IntTest {

public static void main(String args[]) {

Num3 x=new Num3(4,5,6); System.out.println(x.product()); }

}

Method overriding is mainly used for Runtime Polymorphism or Dynamic Method Dispatch (DMD).

05.03.2011

Golden rule of Inheritance

A parent can hold reference to its childs and invoke only those methods of child whose signature is provided from parent to the child.

(25)

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

It allows to execute the methods of childs using the same reference, it is called as dynamic method dispatch (DMD).

It can be done only if method overriding is done. Example

class A {

public void show() {

System.out.println("Calling from A"); }

}

class B extends A {

public void show() //Overriding {

System.out.println("Calling from B"); }

public void welcome() { System.out.println("Welcome to B"); } } class C extends B {

public void show() //overriding { System.out.println("Calling from C"); } } class D {

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

(26)

{ A p; //Runtime polymorphism p=new A(); p.show(); p=new B(); p.show(); p=new C();

p.show(); // dynamic method dispatch (DMD)

} }

Types of classes

Java provides three kinds of classes 1. Concrete class

2. Abstract class 3. Final class

A class that can be instantiated and can also be inherited, is called as concrete class. It is by default.

class X { }

A class that is always made for inheritance purpose only but can never be instantiated, such classes is called as abstract class. Use abstract keyword to declare a class as abstract. An abstract class may or may not have any abstract method but if a class contains any abstract method the class must be declared as abstract.

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

Types of Methods

The methods again can be of three types 1. Concrete methods

2. Abstract methods 3. Final methods Concrete methods

A method having the body contents and allows to overriding the contents, is called as concrete method. It is by default.

(27)

Abstract methods

When a method has the signature but no body contents, it is called as abstract method. Such methods can be declared at two places

1. Inside an abstract class 2. Inside an interface

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

Abstract methods are made for overriding purpose only. Final methods

A method that can be used in child class but can never be overridden is called as final method. Use final keyword with such methods

Method Overloading Vs Method Overriding

Multiple methods having same name but different signatures in same or child class is called as method overloading.

When a method of parent class, re-written in child class is called as overriding. It can never be in same class.

While overloading we can increase or decrease the scope of overridden method but while overriding we can increase the scope of overridden method but can never decrease it.

Example

Create a class as Common to manage common data of Customer, Vender and Employee like name, email,mobile etc.

abstract class Common {

private String name,email,mobile; public Common()

{ }

public Common(String name, String email, String mobile) {

this.name=name; this.mobile=mobile; this.email=email; }

(28)

{

this.name=name; }

public String getName() {

return name; }

public void setEmali(String email) {

this.email=email; }

public String getEmail() {

return email; }

public void setMobile(String mobile) {

this.mobile=mobile; }

public String getMobile() {

return mobile; }

}

class Customer extends Common {

private int cid; public Customer() {

}

public Customer(int cid,String name, String email,String mobile) {

super(name,email,mobile); this.cid=cid;

}

public void setCid(int cid) {

this.cid=cid; }

public int getCid() {

return cid; }

}

class Vendor extends Common {

(29)

class Employee extends Common {

}

public class Inheritance {

public static void main(String[] args) {

Customer c=new Customer(); c.setCid(456);

c.setName("Rakesh");

c.setEmali("[email protected]"); c.setMobile("9898889889");

System.out.printf("Name is %s, Email is %s and CID is %d",c.getName(),c.getEmail(),c.getCid());

} }

(30)

Interfaces

A user defined data type very similar to class but contains all abstract methods and final fields. All methods are public and abstract by default and all fields are public and final by default.

It allows implementing multiple inheritance in Java. Use interface keyword to declare an interface

When inheriting an into a class use implements keyword

When inheriting an interface into another interface use extends keyword

Example

public interface Finance { void budget(); } public interface Hr { void salaryInfo(); }

public class ERP implements Hr,Finance {

public void budget() {

System.out.println("Budget is 4Cr"); }

public void salaryInfo() {

System.out.println("Salary will be given on 7th"); }

}

class ITC {

public static void main(String args[]) {

Hr x=new ERP(); x.salaryInfo();

Finance f=new ERP(); f.budget();

} }

(31)

What are the finals?

If used with fields, makes the constant

If used with the method, do not allows the method to overriding If used with class, do not allow to inherit a class

static blocks static constructor Finalizer

Garbage collection

Can we run some before the entry point? Yes, using static blocks.

Can we run a Java program without using entry point? Yes, using static block.

Can be initialize static fields? Yes, using static blocks

What is the output of following? class Test { static { System.out.println("Hi"); }

public static void main(String args[]) { System.out.println("Hello"); } static { System.out.println("Kese Ho"); } } Output Hi Kese Ho Hello Static Blocks

(32)

A block of code which always executes before the entry point static { //statements } Example class Test1 { static { System.out.println("Hi"); System.exit(0); } } class Test1 {

static int num; static { num=6; System.out.println(num); System.exit(0); } } What is Finalizer?

A method from Object class which automatically get called when object is garbage collected by the Garbage Collector.

protected void finalize()

We need to override this method in our class to provide some cleanup work.

Can be forcibly call the Garbage Collector? Yes, using System.gc() method

(33)

Create a new project as Java Class Library Add your packages

Add classes within the packages Build the project

It creates a .jar file under dist folder Using a .jar file in NetBeans

Create a new project and add your .jar file into libraries

Revision 1. import 2. import static 3. this 4. super 5. extends 6. implements 7. abstract 8. final 9. static 10. interface 11. class 12. for-each loop 13. finalize() Arrays

Array is again a variable that can hold multiple values of similar data type. Use new keyword to create an array. Each array is treated like object and provides length property.

int num[]=new int[5]; int num[][]=new int[3][4]; Object x[]=new Object[5];

We can use a variable to define size of array.

Example //Array Test class ArrayTest1 {

public static void main(String args[]) {

(34)

int num[]=new int[5]; num[0]=56; num[1]=577; num[2]=333; num[3]=222; num[4]=555; for(int i=0;i<num.length;i++) System.out.println(num[i]); Object x[]=new Object[5];

x[0]=678; x[1]=56.89; x[2]='a'; x[3]="Amit"; x[4]=new java.util.Date(); for(int i=0;i<x.length;i++) System.out.println(x[i]); } }

Using foreach loop

A variant of for loop which works with arrays and collections only. It works without knowing size of array and array indexing.

for(datatype variable : arrayname) {

Statements; }

Example

//Using foreach loop class ForEachTest {

public static void main(String args[]) {

int num[]=new int[5]; num[0]=56;

num[1]=577; num[2]=333; num[3]=222; num[4]=555;

(35)

for(int x : num)

System.out.println(x); }

}

Example

WAP to create an array of user defined size and find the sum of all the numbers in array import java.util.Scanner;

class ArrayTest2 {

public static void main(String args[]) {

Scanner sc=new Scanner(System.in); int num;

System.out.print("Size of array : "); num=sc.nextInt();

int ar[]=new int[num]; int sum=0;

for(int i=0;i<ar.length;i++) {

System.out.printf("Enter number %d : ",i+1); ar[i]=sc.nextInt(); sum+=ar[i]; } System.out.println("Sum is : "+sum); } }

Abstract Window Toolkit (AWT)

It is a Java technology for GUI development using a set of classes provided under java.awt package.

It provides three kinds of classes 1. Containers

2. Components 3. Supporting Classes

(36)

A container class is used to hold some components. Example Frame, Applet, Dialog, Panel etc.

A component is again a class used for user interaction. Example Label, Button, TextField, TextArea, Choice, Checkbox, Menu etc.

Supporting classes used to support the containers and the components. Examples Font, Color, Dimension etc.

All components and containers are child of Component class which is an abstract class which provides common methods for all components and containers

 setSize(int w, int h)  setLocation(int x, int y)

 setBounds(int x, int y, int w, int h)  setVisible(boolean value)

 setEnabled(boolean value)  setBackground(Color c) Example

Create a window based application in Java having a window of 200x300 and background color as red

Method 1: without inheriting import java.awt.*;

class FirstApp {

public static void main(String args[]) {

Frame f=new Frame(); f.setSize(200,300);

f.setBackground(Color.red); f.setVisible(true);

} }

Method 2: Using inheritance import java.awt.*;

class MyWindow extends Frame {

public MyWindow() {

(37)

setBackground(Color.blue); setVisible(true);

}

public static void main(String args[]) {

new MyWindow(); }

}

Working with containers

Each container is a class inherited from Container class which provides common methods for all the containers

 public void add(Component c)

 public void setLayout(LayoutManager lm)

LayoutManager is an abstract class providing common method for all layout manager classes

 FlowLayout – default for Applet

 BorderLayout – default for Frame and Dialog  GridLayout

 GridBagLayout  CardLayout

Frame class

A container class which is required for any GUI based application. Every desktop application must inherit from Frame class.

Constructors Frame()

Frame(String title) Methods

void setTitle(String title)

void setResizable(boolean value) Component classes  Label  TextField  TextArea  Checkbox  Choice

(38)

 List  Button  Menu  MenuItem  PopupMenu

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.

Label  lbl TextField  txt Button  btn or cmd Form  frm

Checkbox  chk Option Button  opt Menu  mnu

MenuItem  mit Example

cmdOk, txtNumber etc.

Label class

- To place some text inside a container o Label()

o Label(String text) o void setText(String text) o String getText()

TextField class

- To create single line text and password fields o TextField()

o TextField(int columns) o void setText(String text) o String getText()

o void setEchoChar(char ch) Button class

(39)

o Button()

o Button(String label) o void setLabel(String label) o String getLabel()

TextArea class

- To create multiline textbox o TextArea()

o TextArea(int rows, int columns) o void setText(String text)

o String getText() Example

Create a form having a login, password and remarks. Also create a button Login Check import java.awt.*;

class TestApp extends Frame { Label l1,l2,l3; TextField t1,t2; TextArea ta1; Button b1; public TestApp() { l1=new Label("Login"); l2=new Label("Password"); l3=new Label("Remarks"); t1=new TextField(20); t2=new TextField(20); t2.setEchoChar('*'); ta1=new TextArea(5,20);

b1=new Button("Login Check"); setLayout(new FlowLayout()); add(l1);add(t1); add(l2);add(t2); add(l3);add(ta1); add(b1); setSize(280,300); setResizable(false); setVisible(true); }

public static void main(String args[]) {

(40)

new TestApp(); }

}

Placing components at specified position First setLayout() as null

Use setBounds() method of the components to define the location import java.awt.*;

class TestApp1 extends Frame { Label l1,l2,l3; TextField t1,t2; TextArea ta1; Button b1; public TestApp1() { l1=new Label("Login"); l2=new Label("Password"); l3=new Label("Remarks"); t1=new TextField(20); t2=new TextField(20); t2.setEchoChar('*'); ta1=new TextArea(5,20);

b1=new Button("Login Check"); setLayout(null); l1.setBounds(20,50,80,20);t1.setBounds(100,50,100,20); l2.setBounds(20,90,80,20);t2.setBounds(100,90,100,20); l3.setBounds(20,130,80,20);ta1.setBounds(100,130,100,100); b1.setBounds(100,250,100,20); add(l1);add(t1); add(l2);add(t2); add(l3);add(ta1); add(b1); setSize(280,300); setResizable(false); setVisible(true); }

public static void main(String args[]) {

(41)

new TestApp1(); }

}

Checkbox class

- Used to create a checkbox and radio button. Checkbox allows to select none or all items while radio button allows to select only one item from group

- To create the radio buttons we need to make the groups using CheckboxGroup class - Constructors for Checkbox

o Checkbox()

o Checkbox(String text)

o Checkbox(String text, boolean checked) - Constructor for radio button

o Checkbox(String text, boolean checked, CheckboxGroup cg) o Checkbox(String text, CheckboxGroup cg, boolean checked) - Methods

o boolean getState()

Choice class

- Used to create a drop down list and allows to select only one item o Choice()

- Method

o void add(String item) o String getSelectedItem() List class

- Allows to select multiple items o List()

o List(int size)

o List(int size, boolean multiple) Example

Create a checkbox having text Agree to Terms and Conditions and two radio buttons for Gender Selection as Male or Female.

Also create a dropdown list having some country names.

Introduction to Events in Java

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

(42)

- ActionListener

o For Button, MenuItem etc. - MouseListener

- MouseMotionListener - KeyListener

o For TextField, TextBox etc. - ItemListener

o For Choice, List, Checkbox etc. - WindowListener

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

KeyListener interface

public void keyReleased(KeyEvent e) public void keyPressed(KeyEvent e) public void keyTyped(KeyEvent e) Methods of KeyEvent class

char getKeyChar() void consume() WindowListener interface

public void windowDeactivated(WindowEvent e) public void windowActivated(WindowEvent e) public void windowIconified(WindowEvent e) public void windowDeiconified(WindowEvent e) public void windowOpened(WindowEvent e) public void windowClosed(WindowEvent e) public void windowClosing(WindowEvent e)

(43)

public void mouseMoved(MouseEvent e) public void mouseDragged(MouseEvent e) Methods of MouseEvent class

int getX() int getY()

boolean isPopupTrigger() – to trap the right click

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

(44)

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

Using Color Class

- Provides some built-in colors and also provides the way to create new colors upto 24 bit

o Color(int red, int green, int blue) - Every color ratio can be 0 to 255 only

Creating Random Numbers

Use Math.random() method to get a random number between 0 and 1 Example 2

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

class SampleApp extends Frame implements

ActionListener,KeyListener,WindowListener,MouseMotionListener {

Label lblNumber,lblResult; TextField txtNumber,txtResult; Button cmdSquare,cmdCube;

(45)

public SampleApp() { lblNumber=new Label("Number"); lblResult=new Label("Result"); txtNumber=new TextField(); txtNumber.addKeyListener(this); 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); addWindowListener(this); addMouseMotionListener(this); 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));

(46)

}

public void keyPressed(KeyEvent e) {

}

public void keyReleased(KeyEvent e) {

}

public void keyTyped(KeyEvent e) {

int num=(int) e.getKeyChar(); //System.out.println(num);

if(!(num==8 || num==46 || (num>=48 && num<=57))) e.consume();

}

public void windowDeactivated(WindowEvent e){} public void windowActivated(WindowEvent e){} public void windowIconified(WindowEvent e){} public void windowDeiconified(WindowEvent e){} public void windowOpened(WindowEvent e){} public void windowClosed(WindowEvent e){}

public void windowClosing(WindowEvent e){System.exit(0);} public void mouseDragged(MouseEvent e){}

public void mouseMoved(MouseEvent e) { String s=e.getX()+","+e.getY(); setTitle(s); //int r=e.getX()%256; //int g=e.getY()%256; //int b=(e.getX()+e.getY())%256; int r=(int)(Math.random()*255); int g=(int)(Math.random()*255); int b=(int)(Math.random()*255); String x=r+","+g+","+b; System.out.println(x); Color c=new Color(r,g,b); setBackground(c);

} }

Different places to override the listeners 1. Same class

(47)

3. Outer class 4. Anonymous class

Inner classes

A class within is a class is called as inner class. An inner can access all the resources of containing class.

Using Adapter classes

- Special classes corresponding to listeners which contains pre-overridden methods of listeners

- All those listeners who have only one method do not have any corresponding adapter o KeyListener  KeyAdapter o WindowListener  WindowAdapter o MouseMotionLister  MouseMotionAdapter o Etc. Example

Write a windows application to close the application when we press x button and show the current mouse position using Inner class and adapters

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 extends MouseMotionAdapter {

public void mouseMoved(MouseEvent e) {

String x=e.getX()+","+e.getY(); setTitle(x);

} }

(48)

class WE extends WindowAdapter {

public void windowClosing(WindowEvent e) { System.exit(0); } } } Outer class

When the methods are overridden in any general class, such method is called as 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() { } public ME(Frame f) { this.f=f; }

public void mouseMoved(MouseEvent e) {

String x=e.getX()+","+e.getY(); f.setTitle(x);

} }

class WE extends WindowAdapter {

(49)

{

System.exit(0); }

}

Anonymous class

- When we define the working on event while registering the event, without create any other class, a class get created automatically by the compiler, such class is called as anonymous class

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

class AnonymousTest extends Frame { Button b; public AnonymousTest() { addMouseMotionListener(new MouseMotionAdapter() {

public void mouseMoved(MouseEvent e) { String x=e.getX()+","+e.getY(); setTitle(x); } }); addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0); }

});

b=new Button("Click Me");

b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

javax.swing.JOptionPane.showMessageDialog(null,"You Clicked Me"); } }); setLayout(new FlowLayout()); add(b); setSize(300,300); setVisible(true); }

public static void main(String args[]) {

(50)

} }

03.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.Applet class

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. Image getImage(URL path, String filename)

5. URL getCodeBase() 6. URL getDocumentBase()

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

(51)

});

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="folder name of class files or jar files" 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 (Java Plugin)

Example

(52)

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

}

(53)

</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 image file 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/2.jpg"); }

public void paint(Graphics g) {

g.drawImage(img,0,0,this); }

}

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

(54)

Passing parameters to the applets

- We can pass the data to the applet class using the HTML code using <param> sub tag of <applet></applet> tag

- <param> tag provides two attributes o Name="parameter name" o Value="parameter value" Example

<param name="photo" value="2.jpg">

To read the data send by the parameter using getParameter() method of Applet class String getParameter(String paramname)

Example

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

public class ParamApplet extends Applet {

Image img; public void init() {

String fname=getParameter("photo");

img=getImage(getDocumentBase(),"images/"+fname); }

public void paint(Graphics g) {

g.drawImage(img,0,0,this); }

}

<applet code="ParamApplet" width="200" height="200"> <param name="photo" value="2.jpg">

</applet>

<applet code="ParamApplet" width="200" height="200"> <param name="photo" value="6.jpg">

</applet>

What is repaint()?

A method of Applet class that can re-invoke the paint() method

Example

(55)

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

}

public void update(Graphics gr) {

int r=x%256; int g=y%256; int b=(x+y)%256;

Color c=new Color(r,g,b); setBackground(c);

} }

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

(56)

Creating Menus

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

Creating Drop down menus MenuBar

Menu

MenuItem Menu

Use ActionListener on Menu and MenuItem for programming

Place the MenuBar on the Frame using setMenuBar() method of Frame class Example

Create a menu Colors having three colors Red, Green and Blue. On click on any these menu items change the background color of the form.

Use ellipses (…) to indicate a dialog. Use hypen (-) to a separator lines import java.awt.*;

import java.awt.event.*;

class MenuTest extends Frame implements ActionListener { MenuBar mb; Menu colors; MenuItem red,green,blue,pt; public MenuTest() { mb=new MenuBar(); colors=new Menu("Colors"); red=new MenuItem("Red"); green=new MenuItem("Green"); blue=new MenuItem("Blue"); pt=new MenuItem("Popup Test..."); red.addActionListener(this); green.addActionListener(this); blue.addActionListener(this); pt.addActionListener(this); colors.add(red); colors.add("-"); colors.add(green);

(57)

colors.add(blue); colors.add(pt); mb.add(colors); setMenuBar(mb); setSize(300,300); setVisible(true); }

public void actionPerformed(ActionEvent e) { if(e.getSource()==red) setBackground(Color.red); else if(e.getSource()==blue) setBackground(Color.blue); else if(e.getSource()==green) setBackground(Color.green); else new PopupMenuTest(); }

public static void main(String args[]) {

new MenuTest(); }

}

Creating PopupMenu

Create a PopupMenu and add the Menu and MenuItem into it Use show() method of PopupMenu class to show the menu

public void show(Component c, int x, int y)

Use mouseReleased() event to check the release of mouse and use isPopupTrigger() method of MouseEvent class to know about the right click

boolean isPopupTrigger()

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

class PopupMenuTest extends Frame implements ActionListener {

PopupMenu pm;

MenuItem red,green,blue,pt; public PopupMenuTest()

(58)

{ 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) { if(e.getSource()==red) setBackground(Color.red); else if(e.getSource()==blue) setBackground(Color.blue); else if(e.getSource()==green) setBackground(Color.green); else new PopupMenuTest(); }

public static void main(String args[]) {

new PopupMenuTest(); }

}

(59)

- Create a manifest file (.mft) by defining the startup project class name - Use the entry as

o Main-Class: classname <Press Enter>

Now create a JAR file using cvmf options

Now double click on MenuTest.jar file Closing the current form only Use dispose() method of the Frame

(60)

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 class 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. Batch17.mdb

or

b. Batch17.accdb 2. Create your tables

a. Employee

i. empid – Numeric – Primary Key ii. name - text

iii. email - text

3. Create a data entry form to save the data

4. Create INSERT Command and test it

5. Java provides a default driver to work with MS Access called as JDBC-ODBC Bridge

(61)

a. sun.jdbc.odbc.JdbcOdbcDriver

6. 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)

7. 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. batch17 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(“url”,”login”,”password”); b. Example

i. Connection cn=DriverManager.getConnection("jdbc:odbc:batch17"); 10. Create an object to run the statement pass the reference to some

Statement type reference. 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

(62)

10.04.2011

Using MySql as Database

MySql in an Open Source RDBMS. Create your database

CREATE DATABASE batch17;

Make the database as current database USE batch17;

View the name of current database Select database();

Show the number of tables in the database Show tables;

Create your tables

create table employee(empid int primary key, name varchar(50), email varchar(50)); Database Information

Host Name or Server Name: localhost or IP Address Port No: 3306

Database: batch17 User Id: root Password: pass

Driver Name: com.mysql.jdbc.Driver

Connector JAR: mysql-connector-java-5.0.0-beta-bin.jar URL: jdbc:mysql://localhost:3306/batch17

Create your data entry form using NetBeans Setting the classpath for JAR file of MySql

(63)

While creating SQL statement we can leave the place holders for data using ? where data can be provided later on.

String sql="INSERT INTO employee VALUES(?,?,?)";

Such command can never be executed using Statement but we need PreparedStatement or CallableStatement

CallableStatement is used for stored procedures only. Use prepareStatement() method of Connection interface PreparedStatement ps=cn.prepareStatement(sql);

Passing data to the place holders Use setXXX() methods to pass the data

Example setInt(1,empid); setString(2, name); setString(3, email); Full Code import java.awt.*; import java.awt.event.*; import java.sql.*;

public class MySqlTest extends Frame { TextField t1,t2,t3; Button b; public MySqlTest() { t1=new TextField(20); t2=new TextField(20); t3=new TextField(20); b=new Button("Save"); b.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) { int empid=Integer.parseInt(t1.getText()); String name=t2.getText(); String email=t3.getText(); try { DriverManager.registerDriver(new com.mysql.jdbc.Driver()); Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/batch17","root","pass"); String sql="INSERT INTO employee VALUES(?,?,?)";

(64)

PreparedStatement ps=cn.prepareStatement(sql); ps.setInt(1,empid); ps.setString(2, name); ps.setString(3, email); ps.executeUpdate(); cn.close(); }catch(Exception ex) { System.out.println(ex); } } }); setLayout(new FlowLayout()); add(t1);add(t2);add(t3);add(b); setSize(300,300); setVisible(true); }

public static void main(String args[]) {

new MySqlTest(); }

}

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 the exception.

(65)

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

Examples

IOException FormatException 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); return; }catch(IOException ex) { System.out.println("Error found : "+ex.getMessage()); } catch(NumberFormatException ex) {

System.out.println("Sorry! Only numbers are allowed");

}

catch(ArithmeticException ex) {

System.out.println("Sorry! Denominator cannot be zero");

}

catch(Exception ex) {

(66)

System.out.println("Some error found... Kinly call on 889898989"); //ex.printStackTrace(); } finally {

System.out.println("Thanks for using our system"); }

} }

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

throw statement is used to throw an object of some exception kind

of class.

Use throws keyword 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;

(67)

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

Create another class for a bank like ICICI to use the customer services class ICICI

{

public static void main(String args[]) {

Customer c=new Customer(45,"Rakesh Verma",9000); c.deposit(5000); try { c.withdraw(30000); }catch(LowBalanceException ex) { System.out.println(ex.getMessage()); } c.showBalance(); } } 16.04.2011

Using Oracle as database

- To connect with Oracle we must have o Server Name e.g. ora

o User Id e.g. scott o Password e.g. tiger

(68)

- Create a data source for Oracle using Driver o Microsoft ODBC for Oracle

Create your tables 1. Product

a. pid - numeric b. pname - varchar c. price – numeric Create an application to save data

Example

package batch17_1604; import java.sql.*; import java.util.*; public class Main {

public static void main(String[] args) throws Exception {

Scanner sc=new Scanner(System.in); System.out.print("Product Id : "); int pid=sc.nextInt(); System.out.print("Product Name : "); String pname=sc.next(); System.out.print("Price : "); double price=sc.nextDouble(); DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver()); Connection cn=DriverManager.getConnection("jdbc:odbc:batch17ora","scott","tiger"); String sql="INSERT INTO product VALUES(?,?,?)";

PreparedStatement ps=cn.prepareStatement(sql); ps.setInt(1, pid); ps.setString(2,pname); ps.setDouble(3,price); ps.executeUpdate(); cn.close();

(69)

System.out.println("Record has been saved"); }

}

Using MS SQL Server as Database An RDBMS from Microsoft.

Start your Server Create your database Create your tables

2. Product

a. pid - numberic b. pname - varchar c. price – numberic Create your DSN using Driver

1. SQL Server

To create a DSN you must have

1. Server Name e.g. IMPECCABLETRAIN 2. Database e.g. batch17

package batch17_1604; import java.sql.*; import java.util.*;

public class UsingSqlServer {

public static void main(String[] args) throws Exception {

Scanner sc=new Scanner(System.in); System.out.print("Product Id : "); int pid=sc.nextInt(); System.out.print("Product Name : "); String pname=sc.next(); System.out.print("Price : "); double price=sc.nextDouble(); DriverManager.registerDriver(new sun.jdbc.odbc.JdbcOdbcDriver()); Connection cn=DriverManager.getConnection("jdbc:odbc:batch17ss"); String sql="INSERT INTO product VALUES(?,?,?)";

PreparedStatement ps=cn.prepareStatement(sql); ps.setInt(1, pid);

References

Related documents