Basics of Java Presentation
Basics of Java Presentation
Session 1
Features of Java, What is JVM & JRE, First Java Code, Data Type, Wrapper
Class, Variables
Session 2
Variables, Arrays, Operators, Conditional Statements, Constructors, Destructors
Session 3
Inheritance, Super Reference, Packages, Access Modifiers, Overloading &
Overriding, Polymorphism in Java
Session 4
Java Streams, Serialization, Abstract Classes, Interfaces, Collections
Session 5
Exceptions, Threads, Synchronized Methods
Session 6
AWT, Introduction to Swing, Event Handling, Listeners, Adapters,
Inner classes, Applets
Basic Java Session 1
Features of Java
What is JVM & JRE
First Java Code
Data Type
Wrapper Class
Variables
Why Java?
Simple
Object Oriented
Robust
Multi-threaded
Architecture Neutral
Interpreted
Distributed
Dynamic
JVM & JRE make it Cross Platform
Native OS
Java
class HelloWorld
{
public static void main(String[] args)
{
System.out.println(Hello World);
}
}
Check out
To compile:
javac HelloWorld.java
To run:
java HelloWorld
Hello World Applet
import java.applet.Applet;
import java.awt.Graphics;
<HTML>
<APPLET CODE=HelloWorld.class WIDTH=150 HEIGHT=25>
</APPLET>
</HTML>
Check out
To compile:
javac HelloWorld.java
To run:
HelloWorld
class Employee
{
int empno;
Attributes
String empname;
Data Types Or
int empsal;
String job;
Object State
byte
short Integers
int
long
char
boolean
Integers
type identifier[=value][,identifier[=value],];
Variables
Arrays
Operators
Conditional Statements
Constructors
Destructors
Scope of Variables
Class scope
Methods scope
Scopes can be nested
When outer scope encloses an inner scope, objects declared in
outer scope is accessible to inner scope, but reverse is not true
class scope
{
public static void main(String[] args)
{
int x; //known to all code within main
x=10;
if(x==10)
{ // starts a new scope
int y=20; // known only to this block
Integer array
int marks[]=new int[2];
marks[0]=75;
String array
String[] names=new String[2];
names[0]=Changepond;
Array of references
Student[] students=new Student[2];
students[0]=new Student(Mathew);
Array initialization
int[] intArray1={1,2,3};
int[] intArray2=new int[]{1,2,3};
String[] months={January,February,March);
Array of Arrays
int twoD=new int[2][3];
00 01 02 03
10 11 12 13
20 21 22 23
Arithmetic +, -, *, /, %
Logical !, &&, ||
Assignment =
if (boolean expression)
{
statement1
statement2
}
else
{
statement3
statement4
}
switch
do
{
statement1;
statement2;
} while (boolean expression);
nestedloop:
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
if(j==5)
break nestedloop;
}
}
continue
Class Student
{
int id;
String name;
Student()
{}
}
Parameterized constructors
Class Student
{
int id;
String name;
Student(int id, String name)
{
this.id=id;
this.name=name;
}
}
Garbage Collection
Inheritance
Super Reference
Packages
Access Modifiers
Overloading & Overriding
Polymorphism in Java
Java Inheritance
class PackageDemo
{
public static void main(String args[])
{
Teacher t=new Teacher(ajai);
t.teach();
}
}
The Classpath variable
Student.printNextID();
}
}
Method overloading
class OverloadDemo
{
private int data;
OverloadDemo()
{
System.out.println(Default constructor);
}
//overloaded constructor
OverloadDemo(int id)
{
data=id;
System.out.println(overloaded constructor);
}
Method overloading
void test()
{
System.out.println(No parameters);
}
// overloaded method
void test(int a, int b)
{
System.out.println(a and b: +a,b);
}
double test(double a)
{
System.out.println(double a: +a);
return a*a;
}
}
Parameter passing in Java
Class Student
{
int id;
String name;
void printNextID()
{
System.out.println(Student.printNextID());
}
}
Polymorphism
Class HardworkingStudent extends Student
{
String name;
int id;
void printNextID()
{
System.out.println(HardworkingStudent.printNextID());
}
}
Polymorphism
Class HardworkingStudent extends Student
{
public static void main(String args[])
{
Student s=new HardworkingStudent(vinod,12);
s.prepareForTests();
s.printNextID();
}
}
Basic Java Session 4
Java Streams
Serialization
Abstract Classes
Interfaces
Java Streams and Object Serialization
reads
A stream
Source Program
A stream
writes dest
Program
Java Streams
Character Streams
- Reader and Writer are the abstract super classes for character
streams
- Reads and writes characters
- eg: FileReader, FileWriter, BufferedReader, BufferedWriter
Byte Streams
- InputStream and OutputStream are abstract super classes for
byte streams
- Reads and Writes bytes
Java Streams
IO Streams
- Input Streams allow to read data from a source, Output streams
allow to write data to a destination
- InputStream and OutputStream are abstract classes that define
the fundamental ways to read and write stream of bytes
Data Streams
- read and write primitive data types
- DataInputStream and DataOutputStream classes provide
methods for reading and writing primitive data types
Java Streams
File Streams
- used to read from and write to a file
- FileInputStream and FileOutputStream
- FileReader and FileWriter
Filter Streams
- Allows you to do some additional processing when reading and
writing data
- Used to implement complex streams with added functionality
- Base class is FilterStream, BufferInputStream is derived from
FilterInputStream
example
import java.io.*;
class ReadData
{
public static void main(String[]args) throws IOException
{
DataInputStream din = new DataInputStream(System in);
String name = din.readLine();
}
}
example
import java.io.*;
import java.io.*;
BatchStudEnumerator(Batch b)
{
students = b.students;
nStudents = b.nStudents;
currentIndex = 0;
}
public boolean hasMoreStudents()
{
if(currentIndex == nStudents)
return false;
else
return true;
}
// InterfaceDemo.java
public Student nextStudent()
{
return students[currentIndex++];
}
}
Class Batch
{
String courseName;
Student[] students;
int nStudents;
public Batch(String cName, int maxStudents)
{
courseName = cName;
students=new Student[maxStudents];
nStudents=0;
}
public void addStudent(Student newStudent)
{
students[nStudents++] =newStudent;
}
StudEnumeration getStudents()
{
return new BatchStudEnumerator(this);
}
} //a reference to an interface can be substituted for a reference to an object
// implementing the interface
//InterfaceDemo.java
Class EnumerationTest
{
public static void main(String args[])
{
Batch b= new Batch(J1,2);
b.addStudent(new Student(murali));
b.addStudent(new Student(ajai));
StudEnumeration e = b.getStudents();
while(e.has MoreStudents())
{
Student s=e.nextStudent();
System.out.println(I got: + s);
}
}
}
The Collections Framework
An Introduction
COLLECTIONS
A collection is a structured group of objects
An array is a kind of collection
A Vector is a kind of collection
A linked list is a kind of collection
Java 1.2 introduced the Collections Framework and
provided many great implementations
Vectors have been redefined to implement Collection
Trees, linked lists, stacks, hash tables, and other classes
are implementations of Collection
Arrays do not implement the Collection interfaces
Types Of Collection
Java supplies several types of Collection:
Set: cannot contain duplicate elements, order is not important
SortedSet: like a Set, but order is important
List: may contain duplicate elements, order is important
Java also supplies some collection-like things:
Map: a dictionary that associates keys with values, order is not important
SortedMap: like a Map, but order is important
Collection Map
SortedSet
Vector
TreeSet TreeMap
Stack
Each class (in green) implements one or more interfaces (in Black),
hence implements all the methods declared in those interfaces
We will look at the interface methods
The Collection interface
Some simple Collection methods:
int size( )
boolean isEmpty( )
boolean contains(Object e)
boolean add(Object e)*
boolean remove(Object e)*
Iterator iterator( )
Some bulk Collection methods:
boolean containsAll(Collection c)
boolean addAll(Collection c)*
boolean removeAll(Collection c)*
boolean retainAll(Collection c)*
void clear( )
Results:
one
two
three
Basic Java Session 5
Exceptions
Threads
Synchronized Methods
Exceptions
Complier checks
- whether the method is throwing an exception that it not declared
in the throws clause
whether appropriate handlers are setup to catch the exceptions
// NoCatch.java
class NoCatch
{
public static void main(String[] args)
{
Batch b = new Batch(J1, 2);
b.addStudent(new Student(ajai));
System.out.println(Added ajai to the batch);
b.addStudent(new Student(vijai));
System.out.println(Added vijai to the batch);
b.addStudent(new Student(vinod));
System.out.println(Added vinod to the batch);
}
}
class ItsCatching
{
public static void main(String[] args)
{
Batch b = new Batch(J1, 2);
try
{
b.addStudent(new Student(ajai));
System.out.println(Added ajai to the batch);
b.addStudent(new Student(vijai));
System.out.println(Added vijai to the batch);
b.addStudent(new Student(vinod));
System.out.println(Added vinod to the batch);
}catch(ArrayIndexOutOfBounceException e)
{
System.out.println(Caught an exception: +e);
}
}
}
More on Exceptions
AWT
Introduction to Swing
Event Handling
Listeners
Adapters
Inner classes
Applets
AWT
Component Button
FlowLayout Label
BorderLayout Checkbox
GridLayout List
Choice
Container
Window Panel
Frame
Java.awt.Component
...contd.
...contd.
Label
Button
TextField
TextArea
Choice
List
MenuBar, Menu, MenuItem
Swing - AWT
When a program does not its look and feel, the Swing UI manager
must figure out which look and feel to use
To programmatically specify a look and feel, use the
UIManager.setLookAndFeel() method
UIManager.setLookAndFeel(
com.sun.java.swing.plaf.windows.WindowsLookAndFeel);
How to change the Look and Feel
To make existing components reflect the new look and feel, invoke
the SwingUtilities updateComponentTreeUI method once per top-
level container
For example
UIManager.setLookAndFeel(lnfname);
SwingUtilities.updateComponentTreeUI(frame);
frame.pack();
IDE
aButton.addActionListener(new ActionListener)
{
public void actionPerformed(ActionEvent ev)
{
System.out.println(hello world);
}
}
ItemListener
aCombo.addItemListener(new ItemListener)
{
public void itemStateChanged(ItemEvent ev)
{
System.out.println(hello world);
}
}
Adapters
Sample code
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
});
An anonymous WindowAdapter class is used here
MouseAdapter
Sample code
addMouseListener(new MouseAdapter()
{
public void mouseClicked(WindowEvent ev)
{
if(ev.isPopupTrigger())
System.out.println(Right mouse click);
}
});
An anonymous MouseAdapter class is used here
Inner classes
start()
Called whenever user returns to the page or maximizes the window
stop()
Called everytime the user leaves the page or the window is
iconified
Generally overridden to suspend running threads
Applet - destroy() / paint()
destroy()
Called by the browser when the applet is about to be unloaded
paint()
Called when the applet begins execution