Java
Java
Java is a technology from Sun MicroSystems developed by James Gosling in 1991 with initial name ‘Oak’.
It was designed with the goal to run any kind of device.
http://java.sun.com
http://www.java.com
http://developers.sun.com
What are different tools required for Java SE?
JAVAC.EXE is the compiler for JAVA development found in <jdk folder>\BIN folder
PATH is an environmental variable to hold a list of folder to search the executable files (.exe, .com and
.bat).
Add your folder of JDK into the PATH using the following methods
1. Using command prompt
a. SET PATH=%PATH%;d:\jdk1.6\bin
2. Using MyComputer
Using IDEs
Hierarchy in Java
JAR file
- A compressed file like a ZIP file that is created using JAR.EXE tool of JDK
Package
- A collection of similar set of classes
o java.lang (default)
▪ Math, String, System, Thread, Runnable etc.
o java.io
▪ For input/output operators
▪ File, FileReader, FileWriter, InputStreamReader, BufferedReader, IOException
etc.
o java.util
▪ Provides collections and utilities
▪ Stack, Queue, LinkedList
▪ Timer, TimerTask
▪ Date
▪ Scanner
▪ Etc.
o java.awt
▪ For graphics programming in Java
▪ Button, Checkbox, TextField, Color, Font etc.
//First.java
class Test
{
public static void main(String args[])
{
System.out.printf("Welcome to Java");
}
}
Save this program using an editor like Notepad into your folder
Features of Java
1. Simple and sober
2. Object Oriented Programming
3. Multi Threaded
4. Java is portable
5. Java is platform Independent or Write Once, Run Anywhere
a. Java Virtual Machine (JVM) is the software responsible for such feature
b. .java → JAVAC → .class (byte code) → JVM → Binary → Execute
c. JVM is a machine dependent software but make the Java Platform Independent
6. Java is secure
7. Java is Robust
a. Java provides a big set of classes for almost every purpose
b. Built-in support of Exception handling makes the Java more powerful
c. No more memory leakage. Memory is handled a software called as Garbage Collector
(GC)
- Special keyword used to define the kind of data and range of data of some variable or constant
or some expression is called as data type
o Primitive Type
o User Defined Types
- Primary Types can
o Integrals (All are signed)
▪ byte – 1 byte
▪ short – 2 byte
▪ int – 4 byte
▪ long – 8 byte
o Floatings
▪ float – 4 bytes
▪ double – 8 bytes
o characters
▪ char -2 byte (Unicode)
o Booleans
▪ boolean – 2 byte
▪ Can have true or false only
- User Defined Types
o Class
o Interface
o Enumerators
Providing values to the variables
1. Using Literals
2. Using keyboard Input
3. Using command line argument
Example
Write a program to get name and age of a person check it to be valid voter
import java.util.Scanner;
public class Voter
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter your name : ");
String name=sc.next();
System.out.print("Enter your Age : ");
int age=sc.nextInt();
if(age>=18)
System.out.println("Dear "+name+" you can vote");
else
System.out.printf("Dear %s you cannot vote",name);
}
}
- When a key is pressed from keyboard (System.in), a combination of bits (stream) get produced
and send an object of class InputStreamReader that converts the stream into a character
- Those characters get passed to BufferedReader class and stored in buffer area till we hit the
enter key
- To read the data from buffer area we need a method called as readLine() which returns a string
value
o String readLine()
- To convert data from string type to some numeric type Java provides special classes called as
Wrapper classes
- Special classes corresponding to data types that provides advance functioning of that data types
called as Wrapper Class
Data Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Example 1
Get a number from keyboard and print that number into Decimal, Octal, Binary and Hexa Decimal
import java.util.Scanner;
public class WrapperTest
{
public static void main(String []args)
{
Scanner sc=new Scanner(System.in);
System.out.print("Enter a number : ");
int num=sc.nextInt();
System.out.println("Number is Octal is :"+Integer.toOctalString(num));
System.out.println("Number is Binary is :"+Integer.toBinaryString(num));
System.out.println("Number is Hex is :"+Integer.toHexString(num));
}
}
Wrapper classes help in data conversion from String type to value type
Conversion Formula
datatype variable=wrapperclass.parseDatatype(stringdata);
Example
Write a program to get name and age of a person check it to be valid voter using BufferedReader class
import java.io.*;
public class VoterBR
{
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("Enter Age : ");
int age=Integer.parseInt(br.readLine());
if(age>=18)
System.out.println("Dear "+name+" you can vote");
else
System.out.printf("Dear %s you cannot vote",name);
}
}
Try
Write a program to get two numbers and print the biggest one
Case 1: Using Scanner class
Case 2: Using BufferedReader class
Static Objects
- An object of a class created in another class as static that can be re-used again and again
without re-creating it
- Use static keyword to define such objects
Example
Create an object of Scanner class and another object of BufferedReader in a class as MyClass. Make
both the object as static object.
Now use this class in another class General in another file to get name and age of a person and check it
as valid voter.
//MyClass.java
import java.util.*;
import java.io.*;
class MyClass
{
public static Scanner sc=new Scanner(System.in);
public static BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
}
//General.java
class General
{
public static void main(String arg[]) throws IOException
{
System.out.print("Enter the Name : ");
String name=MyClass.br.readLine();
System.out.print("Age : ");
int age=MyClass.sc.nextInt();
if(age>=18)
System.out.println("Dear "+name+" you can vote");
else
System.out.println("Dear "+name+" you cannot vote");
}
}
Example
import static java.lang.System.*;
import java.io.*;
import static java.lang.System.*;
class ImportStaticTest
{
public static void main(String arg[]) throws IOException
{
out.print("Enter the Name : ");
String name=MyClass.br.readLine();
out.print("Age : ");
int age=MyClass.sc.nextInt();
if(age>=18)
out.println("Dear "+name+" you can vote");
else
out.println("Dear "+name+" you cannot vote");
}
}
Example
Write a program to read name and age of a person from command line and check it to be valid voter.
Lets assume class name as Voter
Example
Write a method that accepts any number of arguments as number and print sum of those number
class DynamicArgs
{
public static void sum(int... num)
{
int s=0;
for(int i=0;i<num.length;i++)
{
s=s+num[i];
}
System.out.println("Sum is : "+s);
}
public static void main(String args[])
{
sum(2,3,4,5,6,7,8,9);
}
}
- Java provides a new loop to work with array and collections without knowing site of it and any
array indexing
class DynamicArgs
{
public static void sum(int... num)
{
int s=0;
for(int t : num)
s=s+t;
System.out.println("Sum is : "+s);
}
public static void main(String args[])
{
sum(2,3,4,5,6,7,8,9);
}
}
Write a program to get some numbers from command line and print biggest number out of those
numbers.
class Sum
{
public static void main(String args[])
{
int b=Integer.parseInt(args[0]);
int n;
for(int i=1;i<args.length;i++)
{
n=Integer.parseInt(args[i]);
if(b<n)
b=n;
}
System.out.println("Biggest one is "+b);
}
}
Arrays
1234
5678
9012
Output
159
260
371
482
- A system used for better project management by mapping the real world entities in computer
programming
- It is independent of any programming language
- It has several components
o Inheritance
o Abstraction
o Encapsulation
o Polymorphism
- It get implemented using class and objects
Encapsulation
Fields are used to hold some data about an object. They can be of two types
1. Variables
2. Constants
a. Use final keyword to declare a constant
Example
class Number
{
int num;//variable
final double pi=3.14; //constant
}
Methods
- Denotes some action
- Can be of two types
o General methods
o Special methods
- General methods can be three types
o Concrete methods
o Abstract Methods
o Final Methods
- Special methods can be as Constructor
Constructor
Special method of a class having some features
1. Same name as class name
2. No return type
3. Used to initialize fields of a class
4. If no constructor is created then default constructor is created automatically
5. If we create any parameterized constructor then default constructor is not created
automatically, we have to create it, if required
What is a class?
What is an object?
Example
String s=new String();
Scanner sc=new Scanner(System.in);
Passing data to the class fields
1. Using Constructors
2. Using General Methods
Example
Create a class as Number having a field as num. Now create constructors to pass data to num along with
some method to pass data to num.
Now write the method to operate on this number as factorial, square, cube etc.
Solution
class Number
{
int num; //field
public Number()
{
}
public Number(int n)
{
num=n;
}
public void setNumber(int n)
{
num=n;
}
public int getNumber()
{
return num;
}
public long factorial()
{
long f=1;
for(int i=1;i<=num;i++)
f=f*i;
return f;
}
public int square()
{
return num*num;
}
}
class Test
{
public static void main(String args[])
{
Number x=new Number();
x.setNumber(8);
Number y=new Number(7);
System.out.printf("Factorial of %d is %d\n",x.getNumber(), x.factorial());
System.out.printf("Factorial of %d is %d",y.getNumber(), y.factorial());
}
}
class Test
{
public static void main(String args[])
{
Number x=new Number();
x.setNumber(8);
Number y=new Number(7);
System.out.printf("Factorial of %d is %d\n",x.getNumber(), x.factorial());
System.out.printf("Factorial of %d is %d",y.getNumber(), y.factorial());
}
}
Non static or instance members always need an object to call them while static members do not need an object to call them
but can be called by the object.
P1
Create a class Customer having fields name and balance. Create constructor to pass name and balance. Create a method
Deposit() to deposit some money and ShowBalance() to show the current balance. Create another method as CalcInterest()
that get amount, rate of interest and period and returns the interests paid for that periods.
class Customer
{
String name;
double balance;
public Customer(String name, double opamount)
{
this.name=name;
balance=opamount;
}
public void deposit(int amount)
{
balance+=amount;
}
public void showBalance()
{
System.out.println("Current balance is "+balance);
}
public static void calcInterest(int p, double r, double t)
{
double intr=(p*r*t)/100;
System.out.println("Interest is "+intr);
}
}
class CustomerTest
{
public static void main(String args[])
{
Customer c1=new Customer("Amit Verma",9000);
c1.deposit(5000);
c1.showBalance();
Customer.calcInterest(10000,9,5);
}
}
P2
1. Create a class for a customer of a home shoppe to manage their information like customer id, name, mobile, credit
limit, current credit.
2. Create a menu to make a purchase and get payment, show the current credit available, show general customer
details, open as account
Abstraction
- Defines the scope or visibility of the class and its members
- Java provides four abstraction layers
o Private
o Public
o Protected
o Default or Package
- Private means accessible within the class
- Public means anywhere access in same or different package. Can be used by an object in any package
- Protected means in same class or in child class in same or different package. Can be used by an an object in same
folder or package only.
- Package or default means within the same folder or package
What is a package?
- A package is a folder having related set of classes
- Each class in a package must have package command on top
package <packagename>;
class <classname>
{
//members
}
package general;
class MyMath
{
int num;
MyMath()
{
}
MyMath(int num)
{
this.num=num;
}
double squareRoot()
{
return Math.pow(num,0.5);
}
}
Using a package
Import a package and use it classes
Set the classpath to define the folder name having the packages
For DOS
SET CLASSPATH=%CLASSPATH%;e:\b1packages
For Kawa
Package→ classpath → Add Dir…
NetBeans
Select the Project Name → Library Properties → Add Jar/Folder…
Polymorphism
Method Overloading
- When two or more method have the same name but different number of arguments or type of
arguments is called as method overloading
Inheritance
JAVAP classname
Create a class as Num2 having two numbers. Write some methods like g2() and p2()
Create another class Num3 by inheriting class Num2 and create the methods g3() and p3()
class Num2
{
int a,b;
public Num2(int a, int b)
{
this.a=a;
this.b=b;
}
public int g2()
{
return a>b?a:b;
}
public int p2()
{
return a*b;
}
}
class InhTest
{
public static void main(String args[])
{
Num3 x=new Num3(4,5,6);
System.out.println(x.p2());
}
}
Method Overriding
- A method of parent or super class, re-written in child class with same signature but different
body contents is called as method overriding
- It is best used for runtime polymorphism or dynamic method dispatch (DMD)
- While overriding we can increase scope of the overridden method but cannot decrease it
class Num2
{
int a,b;
public Num2(int a, int b)
{
this.a=a;
this.b=b;
}
public int greatest()
{
return a>b?a:b;
}
public int product()
{
return a*b;
}
}
class InhTest
{
public static void main(String args[])
{
Num3 x=new Num3(4,5,6);
System.out.println(x.product());
}
}
Runtime Polymorphism
- In inheritance, a parent can hold reference to its childs and can invoke all those methods of
childs whose signature is provided from parent to the child
- Single reference of a parent class can be used to hold reference of childs and invoke its methods
final methods
- A method that can never be overridden
- Use final keyword with such methods
final class
- The class can never be inherited in other class
abstract methods
- A method having the signature but no body contents
- Can be created at two places
o Inside an abstract class
o Inside an interface
- If created inside an abstract class, abstract keyword is required. If a class contains any abstract
method, it must be declared as abstract class.
- If created inside an interface, no keyword is required. All methods inside an interface are public
and abstract by default
Abstract class
Example
Institute Management System
- Entities
o Student
▪ Alumni
▪ Current
o Faculty
▪ Permanent
▪ Visiting
Common to All
1. Name
2. Email
3. Mobile
Common to student
1. rollno
2. course
Common to Faculty
1. empid
2. subject
Alumni
- orgname
- designation
Current Student
- currsem
Permanent Faculty
- leaves
Visiting Faculty
- orgname
- designation
Example
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 String getName()
{
return name;
}
public String getEmail()
{
return email;
}
public String getMobile()
{
return mobile;
}
}
class Test
{
public static void main(String args[])
{
Faculty f=new Faculty(123,"Rakesh
Verma","[email protected]","98988998","Oracle");
System.out.println(f.getName());
System.out.println(f.getMobile());
System.out.println(f.getSubject());
}
}
Interfaces
- A user defined data type very similar to class but contains only abstract methods and final fields
- It allows to implement multiple inheritance in Java
- A class can inherit any number of interfaces using implements keyword
- Use interface keyword to create an interface
- One interface can also inherit other interface using extends keyword
- Can never be instantiated but can create its reference
- In an interface all members are public and abstract by default
Example
Create an ERP software for different departments of an organization
1. Finance→budget()
2. HR→ salary()
interface Finance
{
void budget();
}
interface Hr
{
void salary();
}
class ERP implements Finance,Hr
{
public void budget()
{
System.out.println("Budget is 5cr");
}
public void salary()
{
System.out.println("7th of Every month");
}
}
class AbcIndia
{
public static void main(String args[])
{
Hr x=new ERP();
x.salary();
}
}
Terms in inheritance
Exception Handling
- A method to find runtime errors in a program using some special kind of classes called
exceptions
- Each exception is a class inherited from Exception class and have Exception world associated
with them
o IOException
o IndexOutOfBoundException
o FormatException
- All such classes provide common methods
o String getMessage()
o String toString()
o void printStackTrace()
- Java provides five keywords for exception handling
o try
o catch
o throw
o throws
o finally
- Here try-catch is a block of statements to execute them and trap the runtime errors
try
{
//statements
}catch(classname reference)
{
//message
}
Test Case
Write a program to input two numbers and print division of that numbers
import java.io.*;
class ExpTest
{
public static void main(String args[])
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
try
{
System.out.print("Number 1 : ");
int a=Integer.parseInt(br.readLine());
System.out.print("Number 2 : ");
int b=Integer.parseInt(br.readLine());
int c=a/b;
System.out.println("Divisions : "+c);
return;
}
catch(NumberFormatException ex)
{
System.out.println("Sorry!Only Numbers are allowed");
}
catch(ArithmeticException ex)
{
System.out.println("Sorry! Denominator cannot zero");
}
catch(Exception ex)
{
System.out.println("Some error has occurd. contact customer care at 8989898");
//System.out.println(ex.toString());
//ex.printStackTrace();
}
finally
{
System.out.println("Thanks");
}
}
}
Creating Custom Exceptions
- Create a class as exception to send a message Low Balance Unable to withdraw when a user
tries to get more money than balance.
- Being an exception class, inherit it from Exception class
- Override the methods of Exception class
o String getMessage()
o String toString()
Note:
- Use throw keyword to throw an object of some exception kind of class
- Use throws keyword to mark a method that the method is throwing some kind of exception to
be trapped by the compiler
class Customer
{
String name;
int balance;
public Customer(String name, int opamt)
{
this.name=name;
balance=opamt;
}
public void deposit(int amount)
{
balance+=amount;
}
public void withdraw(int amount) throws LowBalanceException
{
if(amount>balance)
throw new LowBalanceException();
balance-=amount;
}
public void showBalance()
{
System.out.println("Current Balance is "+balance);
}
}
class SBI
{
public static void main(String args[])
{
Customer c1=new Customer("Amit",8000);
c1.deposit(5000);
c1.showBalance();
try
{
c1.withdraw(30000);
}catch(LowBalanceException ex)
{
System.out.println(ex.getMessage());
}
c1.showBalance();
}
}
P4
Create class a InvalidNumberException showing a message Invalid Number Try Again.
Create another class a Number having a field num and a method factorial(). Throw an exception is a
factorial() is called without passing any data to num as InvalidNumberException
String Handling
class StringTest
{
public static void main(String args[])
{
String s1="Vikas";
String s2="Vikas";
if(s1==s2)//value comparison
System.out.println("Equal");
else
System.out.println("Unequal");
}
}
Output
Equal
class StringTest
{
public static void main(String args[])
{
String s1=new String("Vikas");
String s2=new String("Vikas");
if(s1==s2) //address comparison
System.out.println("Equal");
else
System.out.println("Unequal");
}
}
Output
Unequal
class StringTest
{
public static void main(String args[])
{
String s1=new String("Vikas");
String s2=new String("Vikas");
if(s1.equals(s2)) //value at the address
System.out.println("Equal");
else
System.out.println("Unequal");
}
}
Output
Equal
Types of String
- Strings are of two types
o Immutable String or Fixed Size String
o Mutable String or Expandable Size String
- String class is used to managed immutable strings while StringBuilder and StringBuffer classes
are used from mutable strings
- When we concatenate two strings using String class, a memory is de-referenced and send to
Garbage Collector
- Use StringBuffer (network applications) or StringBuilder (local applications) to manage
expandable strings using Append() method
class StringTest
{
public static void main(String args[])
{
String s="Amit";
s=s+" Kumar";
System.out.println(s);
StringBuilder sb=new StringBuilder();
sb.append("Amit");
sb.append(" Kumar");
System.out.println(sb);
String x=sb.toString();
}
}
- int length()
- String toUpperCase()
- String toLowerCase()
- char charAt(int index)
- int indexOf(String s) returns -1 if not found
- int indexOf(String s, int startpoint)
- int lastIndexOf(String s)
- String substring(int start, int end)
o To read a substring from a string as (end-start) characters
- boolean equals(String s)
- boolean equalsIgnoreCase(String s)
- boolean startsWith(String s)
- boolean endsWith(String s)
-
Example
class StringMethods
{
public static void p(String s)
{
System.out.println(s);
}
Interview Questions
1. What are static blocks?
2. Can we run any code before main()?
3. Can we run a program without main()?
4. Can we have private class?
5. Can be we private constructors?
6. What is singleton object? How to create it?
7. What is the difference among final, finally and finalizer?
8. What are the factory methods?
9. Can we invite Garbage Collect to collect the memory?
Static Block
Special block inside a program that always execute before main() and used to initialize static variables
and execute some code that need to be called before main().
class StaticBlocks
{
static
{
System.out.println("Hi to all");
}
public static void main(String args[])
{
System.out.printf("Hello to all");
}
static
{
System.out.println("Bye to all");
}
Singleton Object
- If we want to allows only single object of a class, it is called as singleton object
- We need to make the constructor as private to disallow creation of object outside class
- Create a static object of the class and create another method to return it to outside world
- If a method, other than constructor, of a class returns an object of its own class is called factory
method.
class MyClass
{
private static MyClass mc=new MyClass();//Singleton object
private MyClass()
{
}
public static MyClass getObject() //factory method
{
return mc;
}
public long factorial(int n)
{
if(n==1)
return 1;
else
return n*factorial(n-1);
}
}
class SingletonTest
{
public static void main(String args[])
{
MyClass mc=MyClass.getObject();
System.out.println(mc.factorial(6));
}
}
Finalizer
- Special method of Object class with the name as finalize() which get called automatically when
an object is garbage collected
- It is used to write some code that has to be executed when an object is released from memory
o protected void finalize()
class FinalizerTest
{
public void finalize()
{
System.out.println("Bye Bye");
}
public static void main(String args[])
{
FinalizerTest t1=new FinalizerTest();
FinalizerTest t2=new FinalizerTest();
t1=null;
t2=null;
System.gc();
}
}
Next Topics
1. AWT (Abstract Window Toolkit)
2. Event Handling
3. Java Applets
4. JDBC
5. Java IO
6. Multi Threading
7. Collections and Generics
8. Java Utilities
9. Java Networking
10. Java Swing
11. RMI
12. Servlets
a. Tomcat Server
Note: All containers and components are child of a class named as Component that provides all
common methods for components and containers. It is an abstract class.
Frame class
- To define a window
o Frame()
o Frame(String title)
- void setTitle(String title)
- void setResizable(boolean value)
Label class
- To define fixed text
o Label()
o Label(String text)
- void setText(String text)
- String getText()
TextField class
- To create single text and password field
o TextField()
o TextField(int columns)
- void setText(String text)
- String getText()
- void setEchoChar(char ch)
- char getEchoChar()
- char setEditable(boolean value)
Button class
- To create the push button
o Button(String label)
- void setLabel(String label)
- String getLabel()
Test Application
Create a screen for Login and Password
Login : [ ]
Password : [ ]
<Check Login>
Note: Every container type class is child of Container class that provides common methods for all
containers.
public void add(Component c)
public void setLayout(LayoutManager lm)
Layout Managers
1. BorderLayout (default for Frame)
2. FlowLayout (default for Applet)
3. CardLayout
4. GridLayout
5. GridBagLayout
Event Handling
- A system to take some action when some activity is done using keyboard, mouse or
some system activity
- Each event is an abstract method defined inside special interfaces called as Listeners
under java.awt.event package
o MouseListener
o MouseMotionListener
o KeyListener
o AdjustmentListener
o ItemListener
o WindowListener
o ActionListener
- ActionListener
o public void actionPerformed(ActionEvent e)
▪ Methods of ActionEvent class
• Object getSource()
• String getActionCommand()
How events work in Java
- In Java, events get handled using Event Delegation Model
- We need to place a delegate on the controls on which events need to be trapped.
- Register the listeners with the control to place a delegate
o Controlname.addXXXListener(object of the class having methods of listener);
- Implement the interface
- Override the methods
Example
cmdSquare.addActionListener(this);
cmdCube.addActionListener(this);
this.setResizable(false);
txtResult.setEditable(false);
setLayout(new FlowLayout());
add(lblNumber);add(txtNumber);
add(lblResult);add(txtResult);
add(cmdSquare);add(cmdCube);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new TestApp();
}
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));
}
}
Write a program to trap the current mouse position on a form when we move the mouse pointer on a
frame.
Methods of MouseMotionListener
- public void mouseMoved(MouseEvent e)
- public void mouseDragged(MouseEvent e)
o Methods of MouseEvent class
▪ int getX()
▪ int getY()
▪ boolean isPopupTrigger()
Solutions
import java.awt.*;
import java.awt.event.*;
class EventTest extends Frame implements MouseMotionListener
{
public void mouseMoved(MouseEvent e)
{
String p="Mouse is on "+e.getX()+","+e.getY();
setTitle(p);
}
public void mouseDragged(MouseEvent e)
{
}
public EventTest()
{
addMouseMotionListener(this);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new EventTest();
}
}
Test Case 2
Write a program to have a text box which allows to type only numbers.
Activity → Keyboard
Listener → KeyListener
Methods
public void keyReleased(KeyEvent e)
public void keyPressed(KeyEvent e)
public void keyTyped(KeyEvent e)
Solution
import java.awt.*;
import java.awt.event.*;
class KeyTest extends Frame implements KeyListener
{
TextField t;
public KeyTest()
{
t=new TextField(10);
t.addKeyListener(this);
setLayout(new FlowLayout());
add(t);
setSize(200,200);
setVisible(true);
}
public void keyReleased(KeyEvent e)
{
}
public void keyPressed(KeyEvent e)
{
}
public void keyTyped(KeyEvent e)
{
int code=(int)e.getKeyChar();
//setTitle(Integer.toString(code));
if(!((code>=48 && code<=57) || code==8))
e.consume();
}
public static void main(String args[])
{
new KeyTest();
}
Inner class
- A class within a class that can access all the members of containing class
Test case 1
Create an application having a button as Close. On click on Close button quit the application. Use Inner
class mode to implement the interfaces.
Anonymous class
- A class without any name is called as anonymous class
- If we override a method of a listener while registering the event, then a class get
created automatically called as anonymous class
Example
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
System.exit(0);
}
}
);
Example
Create an application having a single window. Write the code to quit the window when we press x key of
the form.
Hint : WindowListener or WindowAdapter
Event: windowClosing
import java.awt.*;
import java.awt.event.*;
class AdapterTest extends Frame
{
public AdapterTest()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new AdapterTest();
}
}
Other controls
Checkbox class
- To create a check box and radio button
- Checkbox allows to select all or none
- Radio buttons is a group of controls where we can select only one item from group
For Checkbox
Checkbox(String text)
Checkbox(String text, boolean state)
boolean getState()
Sample case
Create a window form having a check box [ ] Agree to terms and conditions and a button. Initially the
button is disabled. When checkbox is checked enable it and unchecked disable it
import java.awt.*;
import java.awt.event.*;
class CheckboxTest extends Frame implements ItemListener
{
Button b;
Checkbox c;
public CheckboxTest()
{
c=new Checkbox("Agree to terms and conditions");
c.addItemListener(this);
b=new Button("Next");
setLayout(new FlowLayout());
add(c);add(b);
b.setEnabled(false);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new CheckboxTest();
}
public void itemStateChanged(ItemEvent e)
{
b.setEnabled(c.getState());
}
}
Checkbox male,female;
CheckboxGroup gender;
gender=new CheckboxGroup();
male=new Checkbox("Male",gender,true);
female=new Checkbox("Female",gender,false);
Choice class
- To create a drop down list
- It allows to select only one item
o Choice()
o public void add(String s)
o String getSelectedItem()
o String getSelectedIndex()
List class
- To create a list box that allows to select one or more items
o List()
o List(int size)
o List(int size, boolean multiple)
o void add(Strings )
o String []getSelectedItems()
o int []getSelectedIndices()
TextArea class
- To create multiline Text box
o TextArea(int rows, int columns)
o void setText(String s)
o String getText()
Creating Menus
- Menus can be of two types
o Dropdown Menu
o Popup Menu
MenuBar
➔ Menu
o MenuItem
o Menu
- To place the Menubar on the Frame use setMenuBar() method of Frame class
Creating a Popup Menu
import java.awt.*;
import java.awt.event.*;
class PopupTest extends Frame implements ActionListener
{
PopupMenu pm;
MenuItem red,green,blue;
public PopupTest()
{
pm=new PopupMenu();
red=new MenuItem("Red");
green=new MenuItem("Green");
blue=new MenuItem("Blue");
pm.add(red);
pm.add(green);
pm.add(blue);
add(pm);
red.addActionListener(this);
green.addActionListener(this);
blue.addActionListener(this);
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)
{
MenuItem b=(MenuItem)e.getSource();
if(b==red)
setBackground(Color.red);
else if(b==blue)
setBackground(Color.blue);
else
setBackground(Color.green);
}
public static void main(String args[])
{
new PopupTest();
}
}
Sample
import java.awt.*;
import java.awt.event.*;
class GUIApp extends Frame
{
Label lblNumber,lblResult;
TextField txtNumber,txtResult;
public GUIApp()
{
addMouseMotionListener(new MouseMotionAdapter()
{
public void mouseMoved(MouseEvent e)
{
String s=e.getX()+","+e.getY();
setTitle(s);
}
});
setLayout(null);
lblNumber=new Label("Number");
lblNumber.setBounds(30,50,60,20);
txtNumber=new TextField();
txtNumber.setBounds(100,50, 100,20);
lblResult=new Label("Result");
lblResult.setBounds(30,80,60,20);
txtResult=new TextField();
txtResult.setBounds(100,80, 100,20);
add(lblNumber);add(txtNumber);
add(lblResult);add(txtResult);
setSize(220,200);
setVisible(true);
}
public static void main(String args[])
{
new GUIApp();
}
}
Java Applets
- Java classes that get merged into HTML code and run inside a web browser are called as
Java Applets
- Such classes must inherit from java.applet.Applet class
- Applet related classes are provided under java.applet package
- Applets do not require any constructor or entry point
- No sizing and visibility settings
- Must be public
- Java Applet class provides various methods that need to be overridden in the child class
for customized applets
o public void paint(Graphics g)
o public void init()
▪ Similar to constructor
o public Image getImage(URL path, String filename)
o public URL getCodeBase()
o public URL getDocumentBase()
o public AudioClip getAudioClip(URL path, String filename)
o public String getParameter(String paramname)
o public void showStatus(String s)
▪ To show a message on status bar of the browser
Method 1
Open this file in Web Browser
➔ The browser must be Java Enabled
Method 2
Open the file with AppletViewer tool of JDK from DOS Prompt
AppletViewer FirstApplet.htm
Test Application
- Write a program with a text box to input a number and print Square Root of it onto the
status bar of the browser
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class GuiApplet extends Applet
{
TextField t;
Label l;
Button b;
public void init()
{
t=new TextField(10);
l=new Label("Number");
b=new Button("Square Root");
add(l);add(t);add(b);
b.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
double num=Double.parseDouble(t.getText());
double result=Math.pow(num,1.0/2);
showStatus("Square root is "+result);
}
});
}
- Use codebase attribute of <applet> tag to define the folder name having the class files
Example
Pass the image name as parameter and use it to display
What is repaint()?
- repaint() is a method of Applet class that allows to call the paint() method again
- We the applet is repainted another internally get used called as update() to create the
current applet
Test Case
Create a class to show the current mouse position with the mouse pointer.
<applet code="RepaintTest" width="300" height="300">
</applet>
- All classes and interfaces related with JDBC are provided under java.sql package
o Class class
o DriverManager class
o Connection interface
o Statement interface
o PreparedStatement interface
o CallableStatement interface
o ResultSet interface
Steps to connect with database
1. Look for the driver class and its JAR file
a. For MySql
i. com.mysql.jdbc.Driver class
b. Get the JAR file containing this class from MySql.com
2. Load the Driver into memory
a. DriverManager.registerDriver(new com.mysql.jdbc.Driver());
3. Now provide the URL (Uniform Resource Locator) to reach the database server
a. Connection cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/b18","root",”pass");
4. Create the SQL Statement to be executed
String sql="INSERT INTO employee VALUES("+txtEmpId.getText()+",'"+txtName.getText()+"','"+txtEmail.getText()+"')";
5. Create an object and pass the reference to Statement interface to the command using
Connection interface with createStatement() method
a. Statement st=cn.createStatement()
6. Now execute the command depending on type of it
a. executeUpdate()
i. for all commands except SELECT
b. executeQuery()
i. for SELECT only
7. Close the connection
a. cn.close();
Note: To show a dialog use classes from Swing (javax.swing) like JOptionPane
JOptionPane.showMessageDialog(this,"Record has been saved");
Example
try
{
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection
cn=DriverManager.getConnection("jdbc:mysql://localhost:3306/b18","root","pass");
String sql="INSERT INTO employee
VALUES("+txtEmpId.getText()+",'"+txtName.getText()+"','"+txtEmail.getText()+"')";
//System.out.println(sql);
Statement st=cn.createStatement();
st.executeUpdate(sql);
cn.close();
JOptionPane.showMessageDialog(this,"Record has been saved");
}catch(SQLException ex)
{
JOptionPane.showMessageDialog(this,ex.getMessage());
}
Note: JDBC-ODBC bridge needs a Data Source Name (DSN) to connect with database and hide the
location of database from the program
Control Panel → Administrative Tools → ODBC → Select System DSN → Add… → Select the Driver as
Microsoft Access Driver (*.mdb) for 2003 and Microsoft Access Driver (*.mdb,*.accdb) for 2007 and
2010 → Select the Database file name and define some Data Source Name (DSN) e.g. b18 is the data
source name.
Now URL to connect with database will be
jdbc:odbc:<dsn name>
Example
jdbc:odbc:b18
Sample Case
Create a table Student (rollno-N-PK, name-text, course-text) under testdb.mdb or testdb.accdb file
Create a data source name (DSN) as b18 for this database file.
Read data from keyboard and save it into database. (Use PreparedStatement and System property)
}
}
import java.util.*;
import java.io.*;
import java.sql.*;
import static java.lang.System.*;
class SaveDataPlaceHolders
{
public static void main(String args[])
{
try
{
Scanner sc=new Scanner(System.in);
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
out.print("Enter Roll No : ");
int rollno=sc.nextInt();
out.print("Name : ");
String name=br.readLine();
out.print("Course : ");
String course=br.readLine();
String sql="INSERT INTO student VALUES(?,?,?)";
//out.println(sql);
System.setProperty("jdbc.drivers","sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:b18");
PreparedStatement ps=cn.prepareStatement(sql);
ps.setInt(1,rollno);
ps.setString(2,name);
ps.setString(3,course);
ps.executeUpdate();
cn.close();
out.println("Records Saved");
}catch(IOException ex)
{
out.println("Error found : "+ex.getMessage());
}
catch(SQLException ex)
{
out.println("Error : "+ex.getMessage());
}
}
}
Test Example
String sql=”Select * from employee”;
PreparedStatement ps=cn.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
Test Case 1
Write a program to show all records inside a table “Student”
import java.sql.*;
class ReadData
{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:b18");
String sql="Select * from student";
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();
}
}
Test Case 2
Write a program to show records in GUI Format as <First> <Prev> <Next> <Last>. Make the ResultSet as
scrollable and sensitive to changes in database even after issuing the select command.
Note: To make the scrollable Resultset, it provides certain constants. Constants can be of two types
1. To define the scrolling type
a. TYPE_FORWARD_ONLY
b. TYPE_SCROLL_SENSITIVE
i. Changes will be available to the program
c. TYPE_SCROLL_INSENSITIVE
i. Changes will be not be available to the program
2. To define the concurrency type
a. CONCUR_READ_ONLY
b. CONCUR_UPDATABLE
These constants get used while creating an object of Statements, CallableStatement or
PreparedStatement etc.
Assignment
Table Name : Product (pid – N – PK, pname-Text, Price-N)
DSN Name: product
Write a program to input data from keyboard and save it into Product Table.
Test Application
Create an application to manage doctor’s detains and the prescriptions given by doctors.
Table: Doctor
1. did – N – Auto Generated - PK
2. dname
3. mobile
4. email
5. address
When View All button is clicked show all doctors in following format
Note: To get current System date use Date class of java.util package
import java.util.*;
class CurrentDate
{
public static void main(String args[])
{
Date d=new Date();
System.out.println(d.toString());
}
}
Also create a Dropdown menu and Popup menu having Menu Items
1→ Add Doctor…
2 → Add Prescription…
Types of Drivers
• Type 1: JDBC-ODBC Bridge
• Type 2: Native-API/partly Java driver
• Type 3: Net-protocol/all-Java driver
• Type 4: Native-protocol/all-Java driver
CallableStatement?
Java Swings
- Advance version of GUI Application to build light weight, rich look applications
- It can also be to create multiple look and feels
- It is part of Java Foundation Classes (JFC) and most of the classes starts with J
- Example
o JFrame, JApplet, JPanel etc.
o JButton, JTextField, JPasswordField, JTextArea
o JScollPane, JOptionPane, JColorChoose etc.
- It allows to use images, shortcuts, hotkeys and tooltips on controls
- While adding the controls on a container get reference of the ContentPane layer
o Container cn=getContentPane();
JLabel class
- To show text or image on the control
o JLabel(String text)
o JLabel(Icon img)
- All controls using an image as Icon must use a class inherited from Icon interface
ImageIcon() class
Example
import java.awt.*;
import javax.swing.*;
class JLabelTest extends JFrame
{
public JLabelTest()
{
JLabel x=new JLabel(new ImageIcon("2.jpg"));
x.setToolTipText("Marry Me");
setLayout(new FlowLayout());
add(x);
setTitle("Hi");
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new JLabelTest();
}
}
JScrollPane class
import java.awt.*;
import javax.swing.*;
class JScrollPaneTest extends JFrame
{
public JScrollPaneTest()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel x=new JLabel(new ImageIcon("file2.jpg"));
x.setToolTipText("Marry Me");
JScrollPane jp=new JScrollPane(x);
add(jp);
setTitle("Hi");
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new JScrollPaneTest();
}
}
JTextArea class
- To select data in multiple rows and columns
o JTextArea(int rows, int cols)
- void setText(String text)
- String getText()
import javax.swing.*;
import java.awt.*;
class JTextAreaTest extends JFrame
{
public JTextAreaTest()
{
JTextArea ta=new JTextArea(10,20);
JScrollPane jp=new JScrollPane(ta);
setLayout(new FlowLayout());
add(jp);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new JTextAreaTest();
}
}
JButton class
- Allows to use Image, Text
- Also allows to use hot key and tooltips
o JButton(String label)
o JButton(Icon image)
o JButton(String label, Icon image)
Example
import javax.swing.*;
import java.awt.*;
class JButtonTest extends JFrame
{
public JButtonTest()
{
JButton b1=new JButton("Save",new ImageIcon("save.gif"));
JButton b2=new JButton("Open",new ImageIcon("open.gif"));
JButton b3=new JButton("Close",new ImageIcon("close.gif"));
b1.setToolTipText("Save Data");
b2.setToolTipText("Open a file");
b3.setToolTipText("Close the File");
b1.setMnemonic('S');
b2.setMnemonic('O');
b3.setMnemonic('C');
setLayout(new FlowLayout());
add(b1);add(b2);add(b3);
setSize(200,200);
setVisible(true);
}
public static void main(String args[])
{
new JButtonTest();
}
}
JColorChooser class
Example
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
class JColorChooserTest extends JFrame implements ActionListener
{
public JColorChooserTest()
{
JButton b=new JButton("Select a color...");
b.addActionListener(this);
setLayout(new FlowLayout());
add(b);
setSize(200,200);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
Color c=JColorChooser.showDialog(this,"Select a color",Color.white);
getContentPane().setBackground(c);
}
public static void main(String args[])
{
new JColorChooserTest();
}
JPanel class
- To create a sub container within a container
- It has all capabilities of container accept cannot be shown independently
Example
import java.awt.*;
import javax.swing.*;
class JPanelTest extends JFrame
{
public JPanelTest()
{
JTextField t=new JTextField();
JButton b[]=new JButton[10];
JPanel p=new JPanel();
for(int i=0;i<b.length;i++)
{
b[i]=new JButton(i+"");
p.add(b[i]);
}
p.add(new JButton("+"));
p.add(new JButton("-"));
add(t,"North");
add(p,"Center");
setResizable(false);
setSize(300,300);
setVisible(true);
}
public static void main(String args[])
{
new JPanelTest();
}
Creating Toolbar
- Use JToolBar class to create the toolbar
- Create JButton controls and add them into JToolBar
- Add JToolBar in North area of container
- Create CallableStatement
import java.util.*;
import java.sql.*;
class UsingCallable
{
public static void main(String args[]) throws Exception
{
Scanner sc=new Scanner(System.in);
System.out.print("Roll No : ");
int rollno=sc.nextInt();
System.out.print("Name : ");
String name=sc.next();
System.out.print("Course : ");
String course=sc.next();
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("jdbc:odbc:sql");
CallableStatement cs=cn.prepareCall("{call SaveStudent(?,?,?)}");
cs.setInt(1,rollno);
cs.setString(2,name);
cs.setString(3,course);
cs.executeUpdate();
cn.close();
System.out.println("Record Saved");
}
}
Multi Threading
- A thread is a light weight process within a process
- It is best used to utilize the CPU resources
- Multiple activities can run automatically and concurrently
- All Java programs are single threaded by default
- One thread is always present known as main thread
class ThreadTest
{
public static void main(String args[])
{
Thread t=Thread.currentThread();
System.out.println(t.getName());
System.out.println(t.getPriority());
}
}
System.out.println("Main ends");
}
}
}
}
else
{
for(int i=5;i<=100;i+=5)
{
System.out.println(name+":"+i);
try
{
Thread.sleep(1000);
}catch(Exception ex)
{
}
}
}
}
public static void main(String args[])
{
System.out.println("Main Created");
MyThread t1=new MyThread("Pepsi");
MyThread t2=new MyThread("Coke");
MyThread t3=new MyThread("Fanta");
System.out.println("Main ends");
}
}
Application of threads in Applet
import java.applet.*;
import java.awt.*;
public class ThreadApplet extends Applet implements Runnable
{
int i;
String fname;
public void init()
{
Thread t=new Thread(this);
t.start();
}
public void run()
{
for(;;)
{
fname="images/"+ (++i)+".jpg";
if(i==6) i=0;
try
{
Thread.sleep(3000);
}catch(Exception ex)
{
}
repaint();
}
}
public void paint(Graphics g)
{
Image img=getImage(getDocumentBase(),fname);
g.drawImage(img,0,0,this);
}
}
Synchronization
- When two or more threads try to access the same resource then there could be a
deadlock
- To handle the deadlocks Java provides synchronized keyword
- It can be used as two ways
o With the methods
o As block
Or
Example
//Stock.java
class Stock
{
int goods=0;
public synchronized void addStock(int i)
{
goods+=i;
System.out.println("Stock Added : "+i);
System.out.println("Current Stock : "+goods);
notify();
}
public synchronized int getStock(int j)
{
System.out.println("Item asked :"+j);
while(true)
{
if(goods>=j)
{
goods-=j;
System.out.println("Stock taken away:"+j);
System.out.println("Present stock :" +goods);
break;
}
else
{
System.out.println("Stock not enough...") ;
System.out.println("Waiting for stocks to come...");
try{
wait();
}catch(InterruptedException e){}
}
}
return goods;
}
public static void main(String args[])
{
Stock j =new Stock();
Producer p= new Producer(j);
Consumer c=new Consumer(j);
try{
Thread.sleep(10000);
p=null;
c=null;
System.out.println("Thread stopped");
}catch(InterruptedException e){}
System.exit(0);
}
}
//Consumer.java
class Consumer implements Runnable
{
Stock c;
Thread t;
Consumer(Stock c)
{
this.c=c;
t=new Thread(this,"consumer");
t.start();
}
public void run()
{
while(true)
{
try
{
t.sleep(1000);
}catch(Exception e){}
c.getStock((int)(Math.random()*100));
}
}
}
//Producer.java
s.addStock((int)(Math.random()*100));
}
}
}
Daemon Thread
- A thread that works in background is called as daemon thread
- Use check whether a thread is daemon thread or general thread use
o boolean isDaemon() method
- To set type of thread use
o void setDaemon(boolean value) method
- When one thread needs some information from other thread then it should remain in
memory until other thread’s work get finished
- To ensure this use join() method on such threads
- First joined thread will end in last
o x.join()
o y.join()
o z.join()
- z will finish first, then y and in last x
File Handling
- To work with files and folders and allows to create new files in text mode and binary
mode
- All related classes are provides under java.io package
o File
o FileReader – Read file in text mode
o FileWriter – Write contents in text mode
o FileInputStream – to read contents in binary mode
o FileOutputStream – to write binary contents to the file
File class
- Use to create a folder, get list of files and sub-folder inside a folder, rename a folder and
remove a folder
- Get properties of a file, remove it and rename it
boolean exists()
returns true if the file or folder exists
boolean isFile()
boolean isDirectory()
String []list()
boolean mkdirs()
To create the directory
Example
//File handling
import java.io.*;
class FileTest
{
public static void main(String args[])
{
File f=new File("d:/first.cs");
if(f.exists())
System.out.println("file exists");
else
System.out.println("file not found");
}
}
import java.io.*;
class SaveTextData
{
public static void main(String args[]) throws IOException
{
FileWriter fw=new FileWriter("d:/test.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string : ");
String s=br.readLine();
fw.write(s);
fw.close();
}
}
Reading contents
//Reading contents of a file
import java.io.*;
class ReadData
{
public static void main(String arg[]) throws Exception
{
FileReader f=new FileReader("d:/test.txt");
BufferedReader br=new BufferedReader(f);
String s;
while ((s=br.readLine())!=null)
{
System.out.println(s);
}
f.close();
}
}
import java.io.*;
class SaveTextData
{
public static void main(String args[]) throws IOException
{
FileOutputStream fw=new FileOutputStream("d:/test1.txt");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a string : ");
String s=br.readLine();
byte []data=s.getBytes();
fw.write(data);
fw.close();
}
}
Collections
Generics
Autoboxing and Unboxing
Collections
- A collection is a class that holds dynamic set of Objects
- Such classes are provided under java.util package
o Vector
o Hashtable
o ArrayList
o Enumeration
o LinkedList
o Stack
o Queue
Types of collections
1. Legacy collection
2. Collection Framework
Vector class
- To hold dynamic set of objects
o Vector()
o void addElement(Object x)
o Object elementAt(int index)
o int size()
Example 1
import java.util.*;
class VectorTest
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Date());
v.addElement("Rahul");
v.addElement(new Integer(56));
v.addElement(new Integer(89));
v.addElement(new Float(45.6f));
import java.util.*;
class VectorTest
{
public static void main(String args[])
{
Vector v=new Vector();
v.addElement(new Date());
v.addElement("Rahul");
v.addElement(new Integer(56));
v.addElement(new Integer(89));
v.addElement(new Float(45.6f));
}
}
}
}
import java.util.*;
class VectorTest
{
public static void main(String args[])
{
ArrayList v=new ArrayList();
v.add(new Date());
v.add("Rahul");
v.add(new Integer(56));
v.add(new Integer(89));
v.add(new Float(45.6f));
}
}
Generics
import java.util.*;
class VectorTest
{
public static void main(String args[])
{
ArrayList <Integer>v=new ArrayList<Integer>();
v.add(new Integer(56));
v.add(new Integer(89));
}
}
import java.util.*;
class ArrayListTest
{
public static void main(String args[])
{
ArrayList <Integer>v=new ArrayList<Integer>();
v.add(56); //auto boxing
v.add(89);
}
}
Hashtable class
- Helps in managing key/value pairs
o Hashtable()
o void put(Object key, Object value)
o Object get(Object key)
o Enumeration keys()
Enumeration interface
System.out.println(t.get("JVM"));
Enumeration e=t.keys();
while (e.hasMoreElements())
{
Object key=e.nextElement();
System.out.println(key+"/"+t.get(key));
}
}
}
LinkedList class
- To managed a linked list
o LinkedList()
o void add(Object x)
o void addFirst(Object x)
o void addLast(Object x)
o void set(int index, Object x)
▪ To replace
Stack class
- To create a stack based on LIFO (Last-In-First-Out) model
o Stack()
o void push(Object x)
o Object pop()
o Object peek()
KeyStroke ks=KeyStroke.getKeyStroke(KeyEvent.VK_V,Event.CTRL_MASK);
Port Number
import java.net.*;
class TestServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(300);
System.out.println("Server is ready....");
Socket client=s.accept(); //this method accept a Socket as server so we use Socket client
System.out.println("Client connected : "+client);
}
}
import java.net.*;
import java.io.*;
class TestClient
{
public static void main(String args[])
{
try
{
Socket server=new Socket("localhost",300);
System.out.println("Server found : "+server);
}catch(IOException ex)
{
System.out.println("Sever Not found");
}
}
}
Write another programs to send a message from server and read it at client side
import java.net.*;
import java.io.*;
class HelloServer
{
public static void main(String args[]) throws Exception
{
ServerSocket s=new ServerSocket(300);
System.out.println("Server is ready....");
for(;;)
{
Socket client=s.accept();
PrintWriter out=new PrintWriter(client.getOutputStream(),true); //flush immediately(data send
immediately so true)
out.println("Hi to all");
System.out.println("Client connected : "+client);
}
}
}
import java.net.*;
import java.io.*;
class HelloClient
{
public static void main(String args[])
{
try
{
Socket server=new Socket("localhost",300);
BufferedReader br=new BufferedReader(new InputStreamReader(server.getInputStream()));
System.out.println(br.readLine());
System.out.println("Server found : "+server);
}catch(IOException ex)
{
System.out.println("Sever Not found");
}
}
}
ProcessBuilder class
import java.util.*;
class ProcessBuilderTest
{
public static void main(String args[]) throws Exception
{
ProcessBuilder p=new ProcessBuilder("notepad.exe");
p.start();
}
}
Enumerators
class enumTest
{
enum Rights
{Admin,General,Student,Faculty}
public static void main(String args[])
{
Rights x=Rights.Admin;
System.out.println(x);
}
}
Java Servlets
- Install the software at defined location and on defined port number e.g. 6789
- Define the password of admin for later use
Test Application
Create an HTML form having a field as num that input a number to print a table.
<html>
<body>
<form method="POST" action="/table.xyz">
<p>Number <input type="text" name="num" size="20"></p>
<p><input type="submit" value="Create Table" name="B1"></p>
</form>
</body>
</html>
Create a servlet class to receive the number and print table of that number. Place this class into some
package.
package b18;
import javax.servlet.*;
import java.io.*;
public class NumberTable extends GenericServlet
{
public void service(ServletRequest req, ServletResponse res) throws ServletException,
IOException
{
PrintWriter out=res.getWriter();
int num=Integer.parseInt(req.getParameter("num"));
for(int i=1;i<=10;i++)
out.println(i*num+"<br>");
}
}
To compile this class we need the JAR file containing javax.servlet package.
Add the JAR file into class path from <tomcat>\common\lib\servlet-api.jar
<servlet>
<servlet-name>ts</servlet-name>
<servlet-class>b18.NumberTable</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ts</servlet-name>
<url-pattern>/table.xyz</url-pattern>
</servlet-mapping>
http://localhost:6789/tablegenerator.htm
RMI (Remote Method Invocation)
- It is a client/server technology that can handle many clients from different locations and
serve them by executing methods stored as server side
- Such applications use
o RMI Protocol
o The client must know about the IP Address and server name
o No port number required
- Such application transfer data in secure mode using concept of marshelling and un-
marshelling
- Such application contains four kind of classes
o Interface
o Implementation
o Client Program
o Server Program
- All classes and interfaces are provided under java.rmi and java.rmi.server package
- Main classes and interfaces required
o Remote interface
o RemoteException class
o UnicastRemoteObject class
o Naming class
- Additional tools
o RMIC.EXE (RMI Compiler)
o RMIREGISTRY.EXE
Test Application
Write an RMI based application to pass a string and get reverse that string.
Step 1:
First of all create an interface and inherit it from Remote interface. Define the methods to be called by
the client. Every method must throw an exception RemoteException
import java.rmi.*;
public interface Test extends Remote
{
String reverse(String s) throws RemoteException;
}
Step 2
import java.rmi.*;
import java.rmi.server.*;
public class TestImp extends UnicastRemoteObject implements Test
{
public TestImp() throws RemoteException
{
}
public String reverse(String s)
{
StringBuffer sb=new StringBuffer();
sb.append(s);
String temp=sb.reverse().toString();
return temp;
}
Step 3:
Create a server program to provide some server name to the class and send a copy of the
implementation class to the client.
//Server Program
import java.rmi.*;
import java.net.*;
public class Server
{
public static void main(String args[]) throws RemoteException,MalformedURLException
{
Naming.rebind("test",new TestImp());
}
}
Use rmi protocol and Naming.lookup() method to search the server and get refernce of the
implementation class.
import java.rmi.*;
public class Client
{
public static void main(String args[]) throws Exception
{
Test t=(Test) Naming.lookup("rmi://localhost/test");
if (t==null)
{
System.out.println("Server Not found");
}
else
{
System.out.println(t.reverse("Hi to All"));
}
}
}
Step 5:
Create Stub and Skelton for marshelling and un-marshelling the arguments
Stub is for client and Skelton is for server. In Java 5.0 + Skelton is option
RMIC TestImp
Division of files
For Server
1. Interface
2. Implementation class
3. server program
Client Side
Run the client program
Example:
Running a program and display response of it
import java.io.*;
import java.util.*;
class ProcessBuilderTest
{
public static void main(String[] args) throws Exception
{