Professional Documents
Culture Documents
B.Tech. CSE
Semester VI
Viswajyothi College of Engineering
1
I/O Basics
Streams
An abstraction that either produces or consumes
the information
Eg:- An input stream is an abstraction that can handle
different kinds of input : keyboard, disk file or network
In java.util
Collections Framework - Goals
1. High Performance
2. High Degree of inter operability among collections
3. Various algorithms to manipulate the collections
4. Extending/adapting collection had to be easy
5. Integration of standard arrays to collection
framework
interface
interface interface interface
Set List Queue SortedMap
Linked TreeSet
HashSet Implementations
Various Collection Interfaces
Collection
List
Set
SortedSet
Comparator
Iterator & ListIterator
RandomAccess
Collection
Foundation in which collection framework is built
Several Methods are declared
Extends Set
Set in sorted way ie Ascending order
ClassCastException
NullPointerException
Collection Classes
Standard classes that implement the interfaces
The ArrayList Class
Extends AbstractList and Implements List
Supports dynamic array that can grow/shrink
ArrayList constructors
ArrayList()
ArrayList(Collection c)
ArrayList(int capacity)
Other methods:-
void ensureCapacity(int
cap)
import java.util.*;
class arraylistdemo
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
System.out.println("Initial Size of ArrayList is "+al.size());
al.add("A");
al.add("B");
al.add("C");
al.add("D");
al.add("E");
System.out.println("After alteration the Size of ArrayList is
"+al.size());
System.out.println("The Contents are "+al);
al.remove("B");
al.remove(1);
System.out.println("After alteration the Size of ArrayList is
"+al.size());
System.out.println("The Contents are "+al);
}
}
Obtaining an array from ArrayList
import java.util.*;
class arraytoarraylist
{
public static void main(String args[])
{
ArrayList al=new ArrayList();
al.add(new Integer(1));
al.add(new Integer(2));
al.add(new Integer(3));
al.add(new Integer(4));
System.out.println("The Contents are "+al);
Object temp[]=al.toArray();
int sum=0;
for(int i=0;i<temp.length;i++)
sum+=((Integer)temp[i]).intValue();
System.out.println(sum);
}
}
LinkedList Class
Extends AbstractSequentialList implements List
Constructors
LinkedList()
LinkedList(Collection c)
System.out.println("The Original List is
import java.util.*;
"+ l);
class ll
l.addFirst("A");
{
l.addLast("J");
public static void main(String
System.out.println("The New List is "+
args[])
l);
{
l.add(1, "A2");
LinkedList l=new
System.out.println("The New List is "+
LinkedList();
l);
l.add("B");
l.remove("A2");
l.add("C");
l.remove(2);
l.add("D");
System.out.println("The New List is "+
l.add("E");
l);
l.add("F");
l.removeFirst();
l.add("G");
l.removeLast();
l.add("H");
Object val=l.get(3);
l.add("I");
l.set(3, (String) val +" Changed");
System.out.println("The Final List is "+
l);
}
}
HashSet
Extends AbstractSet implements Set
Use Hash table for storage
Constructors
TressSet()
TreeSet(Collection c)
TreeSet(Comparator comp)
TreeSet(SortedSet s)
import java.util.*;
class tree
{
public static void main(String args[])
{
TreeSet t=new TreeSet();
t.add("B");
t.add("A");
t.add("D");
t.add("E");
t.add("C");
t.add("F");
System.out.println("The TreeSEt is "+ t);
}
}
Accessing a collection via
Iterator
Employ iterator/ListIterator interface to traverse the
list, remove or add elements
Steps:-
1. Obtain an iterator to the start of the collection by
ListIterator ltr=al.listIterator();
while(ltr.hasNext())
{
Object element=ltr.next();
ltr.set(element+"+");
Storing userclassdefined
address
classes in
collections
import java.util.*;
{
public static void main(String args[])
class mailing {
{ LinkedList l=new LinkedList();
String name; l.add(new mailing("J.W West","11 Oack Ave","Urbana,
String street; "Georgia ,"678934"));
String city; l.add(new mailing("Ralph Baker","1421 Maple Lane",
String state; "Mahomet","Washington","672213"));
String zip; l.add(new mailing("Tom Carlton","867 Elm Street",
mailing(String n, String s, "Champaign","IL","687543"));
String c, String st, String z)
{ Iterator itr=l.iterator();
name=n; while(itr.hasNext())
street=s; {
city=c; Object element=itr.next();
state=st; System.out.print(element +"\n");
zip=z; }
} }
public String toString() }
{
return name + "\n"
+street+"\n"+city+"\n"+state+"\n"+zip+"
\n\n";
}
Maps
An object which stores association with keys and
values
Keys and values are objects
Keys must be unique, values can be duplicated
Map Interfaces
1. Map
2. SortedMap
3. Map.Entry
Map Interface
Given a key and value you can store the value in Map
object
After the value is stored,you can retrieve it using the
key
get(Object)
put(Object k ,Object v)
May raise
NoSuchElementExceptio
ClassCastException
Note: - Methods in page 465 NullPointerException
Map.Entry interface
To work with map entry
Pls recall:-
entrySet() returns Set,each of these entries is a
Map.entry object
HashMap()
HashMap(Map m)
HashMap(int cap)
HashMap(int cap, float fillratio)
import java.util.*;
class hashmap
{
public static void main(String args[])
{
HashMap hm=new HashMap();
hm.put("A",new Double(1000));
hm.put("B",new Double(2000));
hm.put("C",new Double(3000));
hm.put("D",new Double(4000));
hm.put("E",new Double(5000));
Set s=hm.entrySet();
Iterator i=s.iterator();
while(i.hasNext())
{
Map.Entry me=(Map.Entry)i.next();
System.out.print(me.getKey()+ ":");
System.out.println(me.getValue());
}
}
}
TreeMap
Implements Map
Storing key/value pair in sorted order
TreeMap()
TreeMap(Comparator c)
TreeMap(Map m)
TreeMap(SortedMap sm)
import java.util.*;
class treemap
{
public static void main(String args[])
{
TreeMap tm=new TreeMap();
tm.put("A",new Double(1000));
tm.put("B",new Double(2000));
tm.put("C",new Double(3000));
tm.put("D",new Double(4000));
tm.put("E",new Double(5000));
Set s=tm.entrySet();
Iterator i=s.iterator();
while(i.hasNext())
{
Map.Entry me=(Map.Entry)i.next();
System.out.print(me.getKey()+ ":");
System.out.println(me.getValue());
}
}
}
LinkedHashMap
Extends HashMap
Maintains a linkedlist of entries in the map in the
order in which they are entered
LinkedHashMap()
LinkedHashMap(Map m)
LinkedHashMap(int cap)
LinkedHashMap(int cap, float fillratio)
LinkedHashMap(int cap, float fillratio, boolean
order)
Comparator
To sort elements in collection and maps
Eg:- TreeSet and TreeMap
while(i.hasNext())
{
Object element = i.next();
System.out.print(element + " ");
}
System.out.println();
}
}
OUTPUT :- Tree is now stored in reverse
order:
The Collection Algorithms
Predefined algorithms that can be used with
collections and maps
Defined as static methods in Collections class
Continuation at page 478 & 479
import java.util.*; System.out.println();
class algorithm Collections.shuffle(ll);
{ itr=ll.iterator();
public static void main(String args[])
while(itr.hasNext())
{ {
LinkedList ll=new LinkedList(); Object element=itr.next();
ll.add(new Integer(10)); System.out.print(element +" ");
ll.add(new Integer(6)); }
ll.add(new Integer(-1)); System.out.println();
ll.add(new Integer(2));
System.out.println("Minimum="+Collections.min(l
ll.add(new Integer(39));
ll.add(new Integer(-100));
System.out.println("Minimum="+Collections.max(
}
}
Comparator r=Collections.reverseOrder();
Collections.sort(ll,r);
Iterator itr=ll.iterator();
while(itr.hasNext())
{
Object element=itr.next();
System.out.print(element +" ");
}
Arrays class
Applet
Small applications accessed over the internet
server, transported over the internet,
automatically installed and executed by the client
Eg: - Color.black
import java.awt.*;
import java.applet.*;
/* Passing Parameters to
<applet code=parameter applet
public class parameter extends Applet
width=300 height=80> {
<param name=fontName String fontname;
value=TimesnewRoman> int size;
<param name=fontSize value=14> float leading;
<param name=leading value=2> boolean active;
<param name=accountEnabled value=true>
</applet> public void start()
{
*/ String param;
fontname=getParameter("fontName");
size=Integer.parseInt(getParameter("fontSize"));
leading=Float.valueOf(getParameter("leading"))
.floatValue();
active=Boolean.valueOf(getParameter("account"
.booleanValue();
}
public void paint(Graphics g)
{
g.drawString("Font Name :"+fontname,0,10)
g.drawString("Font Size :"+size,0,30);
g.drawString("Leading :"+leading,0,60);
g.drawString("Account Active:"+active,0,90);
}
}
Events
Eg:-
Pressing a button
Enter a character using keyboard
Mouse clicks
Delegation event model
Listeners must be
1. Registered with the source
event
EventObject Methods:-
Object getSource()
toString()
Action Event Class
Generated when a button is pressed,a list item is double clicked
or a menu item is selected
COMPONENT_ADDED, COMPONENT_REMOVED
Container getContainer( )
Component getChild( )
FocusEvent class
FOCUS_GAINED, FOCUS_LOST
Component getOppositeComponent( )
boolean isTemporary( )
InputEvent class
Sub classes are KeyEvent and MouseEvent
char getKeyChar( )
int getKeyCode( )
MouseEvent Class
MouseEvent(Component src, int type, long when, int modifier,int x, int y,int clicks,
boolean triggerspopup)
getX()
geyY()
The MouseWheelEvent Class
WHEEL_BLOCK_SCROLL, WHEEL_UNIT_SCROLL
MouseWheelEvent(Component src, int type, long
when, int modifier,int x, int y,int clicks, boolean
triggerspopup,int scrollhow,int amount,int count)
int getWheelRotation( )
int getScrollType( )
int getScrollAmount( )
ItemEvent Class
Object getItem( )
ItemSelectable getItemSelectable( )
int getStateChange( )
Text Event Class
When char are entered in the text fields
TEXT_VALUE_CHANGED
TextEvent(Object src,int type)
WindowEvent class
Window getWindow( )
EventListener Interfaces
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code= AnAppletWithButtons width=200 height=60>
</applet>
*/
public class AnAppletWithButtons extends Applet implements ActionListener
{
Button button1, button2;
public void init()
{
button1 = new Button("Button 1");
add(button1);
button1.addActionListener(this);
}
import java.awt.*;
import java.awt.event.*;
import java.applet.*; Handling Keyboard Events
/*
<applet code= keyboardevent width=200 height=60>
</applet>
*/
public class keyboardevent extends Applet implements KeyListener
{ public void keyPressed(KeyEvent ke)
String msg=""; {
int x=10,y=20; showStatus("Key Down");
}
public void init()
{ public void keyReleased(KeyEvent ke)
addKeyListener(this); {
requestFocus(); showStatus("Key Up");
} }
AWT
The AWT contains numerous classes and methods
that allow you to create and manage windows
All elements that comprise a GUI are derived from the abstract class
Component.
A container is a component that can accommodate other components
Container provides the overloaded method add () to include
components in the container
AWT Controls
Labels
Push Button
Check Box
Choice List
Lists
Scroll Bars
Text Editing
To add and remove
Label()
Label(String str)
Label(String str, int how)
how- Label.LEFT, .RIGHT,.CENTER
String getText()
void setText(String str)
import java.awt.*;
import java.applet.*;
/*
<applet code= label width=200 height=60>
</applet>
*/
Button()
Button(String str)
After creation
void setLabel(String str)
String getLabel()
import java.awt.*;
import java.awt.event.*; public void actionPerformed(ActionEven
import java.applet.*; {
/* String str=ae.getActionCommand();
<applet code= button width=200 if(str.equals("Yes"))
height=60> yes.setLabel("Yes Clicked");
</applet> else if(str.equals("No"))
*/ no.setLabel("No Clicked");
public class button extends Applet else
implements ActionListener maybe.setLabel("Maybe Clicked");
{ repaint();
Button yes,no,maybe; }
}
public void init()
{
yes=new Button("Yes");
no=new Button("No");
maybe=new Button("Maybe");
add(yes);
add(no);
add(maybe);
yes.addActionListener(this);
no.addActionListener(this);
maybe.addActionListener(this);
CheckBox
Contains a label and used to turn an option on or off. It
consists of a small box with a check mark or not.
Checkbox()
Checkbox(String str)
Checkbox(String str, Boolean on)
Checkbox(String str, Boolean on, CheckboxGroup cbgroup)
Checkbox(String str, CheckboxGroup cbgroup, Boolean on)
boolean getState()
void setState(boolean on)
String getLabel()
void setLabel(String str)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= checkbox width=200 height=60>
</applet>
*/
Choice()
List()
List(int numrows)
List(int numrows, boolean multipleselect)
To add
void add(String name) // add to end of the list
void add(String name,int index) // to index
String getSelectedItem()
int getSelectedIndex()
String [] getSelectedItems()
int[] getSelectedIndexes()
int getItemCount()
void select(int index)
import java.awt.*; public void itemStateChanged(ItemEvent ie)
import java.awt.event.*; {
import java.applet.*; repaint();
/* }
<applet code= list width=200 height=60>
</applet> public void paint(Graphics g)
*/ {
public class list extends Applet implements int idx[];
ItemListener idx=digit.getSelectedIndexes();
{ msg="Current Values: ";
String msg=""; for(int i=0;i<idx.length;i++)
List digit,words; msg+=digit.getItem(idx[i])+" ";
public void init() g.drawString(msg,6,120);
{ msg="words: "+ words.getSelectedItem();
digit=new List(4,true); g.drawString(msg,6,140);
words=new List(4,false); }
digit.add("1"); }
digit.add("2");
digit.add("3");
digit.add("4");
words.add("One");
words.add("Two");
words.add("Three");
words.add("Four");
add(digit);
add(words);
digit.select(3);
words.select(3);
digit.addItemListener(this);
words.addItemListener(this);
Scroll Bars
Scroll bars are used to select continuous values between a
specified minimum and maximum. Scroll bars may be
oriented horizontally or vertically
Scrollbar( )
Scrollbar(int style)
Scrollbar(int style, int initialvalue, int thumbSize, int min, int max)
Scrollbar.VERTICAL
Scrollbar.HORIZONTAL
void setValues(int initialValue, int thumbSize, int min, int max)
int getValue( )
void setValue(int newValue)
int getMinimum( )
int getMaximum( )
TextField
Single line text entry
Textfield()
Textfield(int numchars)
Textfield(String str)
Textfield(String str,int numchars)
String getText()
void setText(String str)
String getSelectedText()
void select(int startindex,int endindex)
boolean isEditable()
void setEditable(boolean canedit)
void setEchoChar(char ch)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= list width=200 height=60>
</applet>
*/
public class text extends Applet implements ActionListener
{
TextField name,password; public void actionPerformed(ActionEvent ae)
Label n,p; {
public void init() repaint();
{ }
name=new TextField(12); public void paint(Graphics g)
password=new TextField(8); {
password.setEchoChar('*'); g.drawString("Name:"+name.getText(),6,60);
n=new Label("Name",Label.RIGHT); g.drawString("Selected Text in Name:
p=new Label("Password",Label.RIGHT); +name.getSelectedText(),6,80
add(n); g.drawString(Password:"+password.getText(),6
add(name); }
add(p);
add(password); }
name.addActionListener(this);
password.addActionListener(this);
}
TextArea
TextArea()
TextArea(int numLines,int numchars)
TextArea(String str)
TextArea(String str, int numLines,int numchars)
TextArea(String str, int numLines,int numchars,int
sbars)
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code= textarea width=200 height=60>
</applet>
*/
public class textarea extends Applet
{
setLayout(LayoutManager layoutObj)
If no call to setLayout default layout manager is used
FlowLayout
FlowLayout()
FlowLayout(int how)
FlowLayout(int how, int horz, int ver)
how takes values FlowLayout.LEFT,.CENTER,.RIGHT
Space b/w components in horz and ver
public void init()
{
setLayout(new FlowLayout(FlowLayout.LEFT));
.
}
Border Layout
BorderLayout()
BorderLayout(int horz,int vert)
GridLayout()
GridLayout(int rows,int cols)
GridLayout(int rows,int cols,int horz,int vert)
import java.awt.*;
import java.applet.*;
/*
<applet code= gridlayout width=200
height=60>
</applet>
*/
public class gridlayout extends Applet
{
public void init()
{
int k=1;
setLayout(new GridLayout(4,4));
for(int i=1;i<16;i++)
{
add(new Button(""+k));
k++;
CardLayout
PANEL
Class
CardLayout();
CardLayout(int horz,int vert)
}
public void mouseExited(MouseEvent me)
{
}
public void mouseReleased(MouseEvent me)
{
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==windows)
{
card.show(os,"Windows"); // Shows card name passed as
argument
}
else
card.show(os,"Linux");
}
MenuBar
Menu
MenuItem
import java.awt.*; public class menu extends Applet
import java.applet.*; {
import java.awt.event.*; Frame f;
/* public void init()
<applet code= menu width=200 height=60> {
</applet> f=new menuframe("My Menu");
*/ setSize(new Dimension(500,500)); // For Applet
class menuframe extends Frame f.setSize(500,500); // For Frame
{ f.setVisible(true);
}
menuframe(String title) public void start()
{ {
super(title); // Title for Frame f.setVisible(true);
MenuBar mbar=new MenuBar(); }
setMenuBar(mbar); public void stop()
{
Menu file=new Menu("File"); f.setVisible(false);
MenuItem item1,item2,item3; }
file.add(item1=new MenuItem("New")); }
file.add(item2=new MenuItem("Open"));
file.add(item3=new MenuItem("Exit"));
mbar.add(file);
JButton(Icon i)
JButton(String s)
JButton(String s, Icon i)
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends Japplet implements ActionListener
{
JTextField jtf;
public void init()
{ ImageIcon italy = new ImageIcon("italy.gif"
Container contentPane = getContentPane();
jb = new JButton(italy);
contentPane.setLayout(new FlowLayout());
jb.setActionCommand("Italy");
ImageIcon france = new ImageIcon("france.gif"); jb.addActionListener(this);
JButton jb = new JButton(france); contentPane.add(jb);
jb.setActionCommand("France");
jb.addActionListener(this);
ImageIcon japan = new ImageIcon("japan.g
contentPane.add(jb);
ImageIcon germany = new ImageIcon("germany.gif");
jb = new JButton(japan);
jb = new JButton(germany); jb.setActionCommand("Japan");
jb.setActionCommand("Germany"); jb.addActionListener(this);
jb.addActionListener(this); contentPane.add(jb);
contentPane.add(jb);