0% found this document useful (0 votes)
185 views

Java Basics Java Basics: For More Tutorials Visit For More Tutorials Visit

The document outlines 6 sessions on basic Java concepts including features of Java, data types, variables, arrays, operators, conditional statements, constructors, inheritance, packages, exceptions, threads, AWT and Swing. It describes Java fundamentals such as the Java Virtual Machine, object-oriented features of Java, and gives examples of simple Java programs and applets. The sessions cover fundamental Java programming concepts for beginners to learn the basics of the Java language.

Uploaded by

Aashish Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
185 views

Java Basics Java Basics: For More Tutorials Visit For More Tutorials Visit

The document outlines 6 sessions on basic Java concepts including features of Java, data types, variables, arrays, operators, conditional statements, constructors, inheritance, packages, exceptions, threads, AWT and Swing. It describes Java fundamentals such as the Java Virtual Machine, object-oriented features of Java, and gives examples of simple Java programs and applets. The sessions cover fundamental Java programming concepts for beginners to learn the basics of the Java language.

Uploaded by

Aashish Singh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 166

JAVA BASICS

For more tutorials visit


www.roshinionline.com
Basic Java – Session Outline

 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?

 Need for platform neutral language for Consumer Electronic


devices
 Java and Internet
Java

 Simple
 Object Oriented
 Robust
 Multi-threaded
 Architecture Neutral
 Interpreted
 Distributed
 Dynamic
JVM & JRE make it Cross Platform

Java Source Code X.java

Byte Code X.class

Java Virtual Machine


Java Runtime Environment
Native OS
JVM – Java Virtual Machine

 Often misunderstood as an interpreter


 An emulator which emulates the intermediate machine
architecture
 Java application binds to a JVM and JVM binds to a specific
platform
 JVM does not require a chip or silicon based implementation to
operate
JRE – Java Runtime Environment

 Java Runtime acts as an Operating System, loading required


classes into JVM for execution
 Interface between JVM and Native OS
 The support classes required by the Java executables reside in
the runtime environment and are fetched by the JVM as needed
Java Runtime Environment

Java Support Classes


JVM Executables

Native OS
Java

 Application – create stand-alone application that runs on the


local machine
 Applets – A Java program that runs on the web
Java Object Oriented

 Unlike C++, purely Object Oriented


 Represent real life instances
 Classes – template for an object
 Object – instance of a class
A Simple Java Program

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;

public class HelloWorld extends Applet


{
public void paint(Graphics g)
{
g.drawString(“Hello World”,50,25);
}
}
Hello.html

<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

public int getEmpNo()


{
return empno;
} Methods
public void setEmpNo(int eno) Or
{ Object Behavior
empno=eno;
}

};
Primitive Data Types

 byte
 short Integers
 int
 long

 float Floating point


 double

 char
 boolean
Integers
 Signed, Positive and Negative values
 Java does not support unsigned, positive only integers

Type Width Range


byte 8 bits -128 to 127
short 16 bits -32,768 to 32,767
int 32 bits -2,147,483,648 to
2,147,483,647
long 64 bits -9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
Floating Point Types

 Real numbers, used when evaluating expression that require a


fractional precision

Type Width Range


float 32 bits -3.4e-38 to 3.4e38
double 64 bits -1.7e-308 to 1.7e308
Characters

 Uses 16 bit Unicode to represent characters


 Unicode defines a character set that can represent all
characters found in all human languages
 Range is 0 to 65,536
 There are no negative characters
 ASCII is a subset of Unicode character set
 ASCII ranges from 0 to 127
Boolean

 A simple type for logical values


 Only 2 possible values – true or false
 Provides a 1 bit storage for representing true or false values
String

 Strings are implemented as array of characters


 Strings are object types
 All String assignment and manipulation facilities are provided by
means of the String class
 Everything from character level manipulation to pattern
searching methods is encapsulated in String class
Wrapper classes

 Encapsulates or wraps simple types like int and char


 Simple types are not part of object hierarchy
 Enumeration classes store only objects in them – so have to
wrap the simple types
Variables

 Basic unit of storage


 Declaration

type identifier[=value][,identifier[=value],…];

e.g. int x=10, y=25;


Basic Java – Session 2

 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

// x and y are both known here


System.out.println(“x and y :” + x + “ ” + y);
x=y*2;
} // end of if
y=100; //error: y is not known here

// x is still known here


System.out.println(“x is :” + x);
}
};
Java Arrays

 Arrays are also objects, with a fixed length


 Arrays of primitive data types are different from arrays of
references
 Size of the array is mentioned only when the array is created
 Array indexes run from 0 to the length of the array minus 1 (n-1)
 Accessing beyond the end of the array results in a runtime error
Arrays

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

Student[] studArray=new Students[]


{new Student(“Mickey”),new Student(“Donald”)};

String[] months={“January”,“February”,“March”…);

char string=“Java”; //error


Multi-dimensional Arrays

 Array of Arrays
int twoD=new int[2][3];

int twoD=new int[3][];


int twoD[0]=new int[4];
int twoD[1]=new int[4];
int twoD[2]=new int[4];
Multi-dimensional Arrays

00 01 02 03

10 11 12 13

20 21 22 23

Given: int twoD[][]=new int[3][4];


Operators

Arithmetic +, -, *, /, %

Relational >, <, >=, <=, !=, ==

Logical !, &&, ||

Bit Manipulation ~, &, |, ^, <<, >>, >>>

Assignment =

Increment, Decrement ++, --

Compound Assignment +=, *=, etc.

Miscellaneous (type), instanceof, new, ?:


if… else…

if (boolean expression)
{
statement1
statement2

}
else
{
statement3
statement4
}
switch

switch (integer expression)


{
case value1: statement1;
statement2;

break;
case value2: statement3;
statement4;

break;
default: default statement;
}
do…while…

do
{
statement1;
statement2;

} while (boolean expression);

 The do-while look executes at least once


while…

while (boolean expression)


{
statement1;
statement2;

}
for loop

for (initialization; condition; increment or decrement)


{
statement1;
statement2;

}
break

 Used to exit a block, usually based on a condition


 Used to break out of innermost loop
for (int i=0; i<10; i++)
{
if(i==5)
break;
}
Labelled break

nestedloop:
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
if(j==5)
break nestedloop;
}
}
continue

 Skips to the end of the loop’s body


 Evaluates the boolean expression that controls the loop
int x=0;
while (x<10)
{
++x;
if(x==5)
continue;
system.out.println(“x is : “ + x);
}
return

 Used to terminate the execution of a method


 If a method has a return type, then return must include an
expression that could be assigned to the return type
Constructors

 Initializes the state of an object as soon as it is created


 Has the same name as the class
 Has no return type
Default Constructor

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

 Automatic deallocation of memory


 No explicit need to destroy objects as in C++
 when no references to objects exists, it is assumed that it is no
longer needed, memory occupied is deallocated
 It occurs periodically during execution of the program
Object Destruction

 finalize() defines actions that will occur when an object is about


to be reclaimed by a garbage collector
 used to free the non-java resources that an object holds. Eg: file
handle
 The Java Runtime calls this method whenever it is about to
recycle an object of this class
Basic Java – Session 3

 Inheritance
 Super Reference
 Packages
 Access Modifiers
 Overloading & Overriding
 Polymorphism in Java
Java Inheritance

 Single inheritance v/s multiple inheritance


 Subclasses inherit all the fields and methods in the super-class
 extending classes
 Overriding methods
Class Hardworking Student extends Student
{
public void refreshPortions()
{ //added behavior
System.out.println(this + ”refreshed the portions”);
}

public void prepareForTests()


{ //overridden method
refreshPortions();
}
}
The super reference

 Subclasses normally augment the behavior of the super-class


 An overriden method in a subclass invokes the super class
method, then adds behavior specific to itself
 The super reference
 super constructors
// SuperDemo.java
class HardworkingStudent extends Student {
HardworkingStudent(String name){
super(name);
}
public void refreshPortions(){//added behavior
System.out.println(this+ “:refreshed the portions”);
}
public void prepareForTests() { //Overridden method
super.prepareForTests();
refreshPortions();
}
public static void main(String args[]) {
HardworkingStudent s=new HardworkingStudent(“vinod”);
s.prepareForTests();
}
}
Object and Class classes

 All classes are directly or indirectly derived from the class


java.lang.Object
 Any reference can be converted to a Object reference (arrays
too)
 Object class - getClass, equals(Object o), toString()
 Class class - encapsulates the run time state of an object or
interface.
Object and Class classes

 Objects of type Class are created automatically, when classes


are loaded
 you cannot explicitly declare a Class Object
 getName(), getInterfaces(), getSuperClass(), toString()
Java Packages

 Related classes can be put in a package


 Used to separate unrelated classes from each other
 Used to hide implementation specific classes from classes in
other packages(eg:java.util.Vector)
 Prevent name space pollution(amity.student, amity.com.util)
 java.lang, java.util, java.net, java.awt, java.applet
Package level access

 Default access in java is package level access


 Public classes
 Classes that are not public cannot be accessed from other
packages
 Public classes have to be put in a java source file with the same
name
 The package statement
package another;
class PackageDemo
{
public static void main(String args[])
{
Trainer t=new Trainer(“ajai”);
t.teach();
}
}
Importing classes from packages

 Qualified name of String is java.lang.String


 How are we able to refer to it as String?
 The import statement
 No runtime overhead associated with import
 Classes in java.lang are automatically imported to the default
unnamed package
import ccjiTeacher;
//all classes in a package can be imported using import package.*;

class PackageDemo
{
public static void main(String args[])
{
Teacher t=new Teacher(“ajai”);
t.teach();
}
}
The Classpath variable

 Java runtime searches for referenced classes in directories


specified in CLASSPATH
 Package names & class file directory organization
 Java source file organization
Access Modifiers

 Who has access to use the class?


 Who has access to inherit the class’s properties?
 Modifier Visibility
public unrestricted
protected Accessible only from within the package,
but extensible anywhere
default Accessible and extensible only from within
the package
private Accessible only from within declared class file
class AccessDemo
{
public static void main(String args[])
{
Student s1=new Student(1,”ajai”);
Student s2=new Student(2,”vijai”);
}
}
Method overriding rules

 Overridden methods in subclasses should have atleast the


same access as declared in the superclass
- public in super class should be public in subclass too
- protected in super class, protected or public in subclass
- package level should not be declared private
final - Keyword

 Can be used as declaration modifier for either class, methods or


variables
 Any class declared as final may not be subclassed
 Methods declared as final may not be overridden
 Variables declared as final are similar to const in C/C++
 final variables must be initialized when declared
static - Keyword

 Used as field and method modifier to specify a permanent


nature
 If the field is declared as static, all instances of the class share
the same variable memory storage region
 instance independent - hence called as Class variable and
Class method
 static variables and methods can be accessed without creating
an instance of the class
static - Keyword

 They can only call other static methods


 They must only access static data
 They cannot refer to ‘this’ or ‘super’
class Student
{ private int id;
private String name;
private static int nextID=0;
Student(String studName)
{
id=++nextID;
name=studName;
}
public String toString()
{
return “[“ + name + ”,” + id + “]”;
public static void main(String args[])
{
Student s1= new Student(“ajai”);
Student s2= new Student(“vijai”);
System.out.println(“s1 is:” +s1);
System.out.println(“s2 is:” +s2);
}
}
class StaticMethodDemo
{
public static void main(String[]args)
{
Student s1=new Student(“ajai”);
Student s2=new Student(“vijai”);

Student.printNextID();
}
}
Method overloading

 It is possible to define two or more methods within the same


class that share the same name if the parameters are different
 Java uses type and /or number of arguments to determine
which method to call
 overloaded methods may have different return types, but return
type alone is insufficient to distinguish the different versions
 overloaded constructors
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

 Pass by value and pass by reference


 Java supports only pass by value
 Java reference has to be explicitly set to refer an object of that
class or its subclasses, if it has no reference by default it is null.
 Unlike Java, C++ references by default implicitly creates an
instance of the class eg: String s;
 Can be thought of as safe pointers
Polymorphism in Java

 All super class methods that are accessible to subclass exhibit


polymorphic behavior if overridden
 Polymorphism should never be confused with method
overloading
 Enables overridden methods to be invoked using super class
references
 Dynamic binding/ method dispatch
Polymorphism - Details

 A super class reference can refer to subclass object(widening


reference conversion)
 If the reference indeed refers to an object of the subclass, then
invoking an overridden method results in the subclass method
to be invoked
 Understanding polymorphism is the key to understanding object
oriented design concepts
Polymorphism

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

 Object serialization is used to make Java objects persistent


 JDK 1.1 provides native support for object serialization
 Its major use is to transmit objects across the network, the
so-called passing objects by value
 The Java RMI does this in a automatic transparent way
Java Streams

 A network connection, memory buffer, or disk file can be


manipulated by the Java IO classes – handled by the abstraction
Stream
 Stream is a logical entity that either produces or consumes
information
 A Stream is linked to a physical device by the Java IO system
Java Streams

reads
A stream
Source
Source Program

A stream

writes dest
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.*;

public class CopyFiles


{
public static void main(String[]args) throws IOException
{
FileReader in = new FileReader (“Customer.txt”);
FileWriter out = new FileWriter(“CustomerData.txt”);
int c;
while((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
}
}
example

import java.io.*;

public class CopyFiles


{
public static void main(String[]args) throws IOException
{
BufferedInputStream in = new BufferedInputStream(new
FileInputStream(“Customer.txt”));
int c;
while((c = in.read()) != -1)
System.out.print((char)c);
in.close();
out.close();
}
}
Object Serialization

 Object serialization extends the core Java streams classes with


support for objects
 Object serialization involves saving the state of objects in a
serialized form into a stream sufficient to reconstruct the objects
 Objects to be saved may support either Serializable or
Externalizable
 For Serializable objects, the serialized form automatically includes
sufficient information to restore the objects state
 For Externalizable objects, the class is solely responsible for the
content of the serialized form
Code Sample
//just mark the objects to be saved as implements Serializable

//saving the object’s state to a file


FileOutputStream fos = new FileOutputStream(“tmp”);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(obj);

//restoring the object’s state from the file


FileInputStream fis = new FileInputStream(“tmp”);
ObjectIntputStream ois= new ObjectIntputStream (fis) ;
Object obj =ois.readObject();
Abstract classes

 Implementation of certain methods are left to subclasses


 Design of frameworks, where general algorithm is known
(eg : InputStream)
 Abstract methods do not have an implementation
Abstract classes

 Classes having abstract methods has to be declared abstract


 Abstract classes cannot be instantiated
 Subclasses that do not implement all the abstract methods have
also to be declared abstract
abstract class Stat //AbstractDemo.java
{ protected int numbers[];
Stat(int numbers[])
{
this.numbers = numbers;
}
protected abstract void sort();
public int median()
{
int median;
sort(); //Call abstract method, implemented by subclasses
int middle = numbers.length / 2;
if(numbers.length % 2)
median = numbers[middle];
else
median =(numbers[middle] + numbers[middle+1] )/ 2;
return median;
}
}
//AbstractDemo.java
Class BblStat extends Stat
{
BblStat(int numbers[])
{
super(numbers);
}
public void sort()
{
System.out.println(“Sorted the numbers using the Bubble Sort method”);
}
}
//AbstractDemo.java
Class QckStat extends Stat
{
QckStat(int numbers[])
{
super(numbers);
}
public void sort()
{
System.out.println(“Sorted the numbers using the Quick Sort method”);
}
}
//AbstractDemo.java
Class AbstractDemo
{
static void doIt(Stat s)
{
int median = s.median();
System.out.println(“median is” + median);
}
public static void main(String args[])
{
Stat s = new QckStat();
doIt(s);
}
}
Interfaces

 Protocol of behavior, which must be adhered by the class


implementing it
 Pure design concept, no associated implementation
 Component technologies(COM, COBRA)
 Programming to an interface
Java Interfaces

 Set of public abstract methods(and static final attributes)


 expression of pure design, can never carry implementation details,
hence per object fields can never be a part of an interface
 Multiple interface inheritance
 Classes implement interfaces
// InterfaceDemo.java
Interface StudEnumeration
{
boolean hasMoreStudents();
Student nextStudent();
}
Class BatchStudEnumerator implements StudEnumeration
{
private Student[] students;
private int nStudents;
private int currentIndex;

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

Set List SortedMap

SortedSet

 There are two groups: Collections of single elements, and Maps


containing key/value pairs
 These are all interfaces, but there are classes implementing each
interface
Collection Map

Set List Hashtable HashMap

HashSet SortedSet ArrayList LinkedList SortedMap

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

* Returns true if the Collection was changed, false otherwise


A simple map: Hashtable

 To create a Hashtable, use:


import java.util.*;
Hashtable table = new Hashtable();

 To put things into a Hashtable, use:


table.put(key, value);

 To retrieve a value from a Hashtable, use:


value = (type)table.get(key);
Vectors

 The class Vector has been retrofitted to implement the


Collection interface

 Vector supplies add(Object) and iterator() methods (among


others)

 Let’s look at creating a Vector and iterating through the


elements
The Iterator interface
interface iterator { // java.lang.util
boolean hasNext();
// Returns true if the iteration has more
// elements.
Object next();
// Returns the next element in the
// interation.
void remove();
// Removes from the underlying collection
// the last element returned by the
// iterator (optional operation).
Using a Vector
Collection numerals = new Vector();
numerals .add("one");
numerals .add("two");
numerals .add("three");

Iterator iter = numerals.iterator();


while (iter.hasNext()) {
System.out.println(iter.next());
}

Results:
one
two
three
Basic Java – Session 5

 Exceptions
 Threads
 Synchronized Methods
Exceptions

 Signify abnormal conditions during the execution of the program


 Separates program logic from error handling logic
 Errors: Checked & Unchecked Exceptions
 Unchecked exceptions are derived from a subclass of Throwable
called RuntimeException
Exceptions

 Runtime exceptions denote a class of exceptions that is not specific


to a method, can occur when evaluating any java code
 Checked exceptions are more specific to a method – the method
throws an instance of the checked exception on abnormal
conditions
 Methods must not be vague about the exceptions that they throw
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

 Declaring a new exception type


 The finally block
- is entered whether exception is thrown or not
- used for necessary clean up before returning from a method
eg: open file stream is closed in a finally block
class CourseFilledException extends Exception
{
CourseFilledException()
{
super();
}
CourseFilledException(String s)
{
super();
}
}
//class Batch
void addStudent(Student newStudent)throws CourseFilledException
{
if(nStudents == students.length)
throw new CourseFilledException(“Max Students:” + students.length);
Students[nStudents++] = newStudent;
}
class FinallyDemo
{
public static void main(String[]args)
{
Batch b =new Batch(“P1”,3);
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(CourseFilledException e)
{
System.out.println(“Caught and exception: “+ e);
}
finally{
System.out.println(“Reached Finally Block”);
}
}
}
When to use Exceptions

 Do not use exceptions to report simple errors which can be


checked by return value from a method
 use it to provide more information than simple return values
 eg: it would be a serious error to add a student to a batch, who
already has been added
Java Threads

 Threads are merely separate execution paths sharing memory


address space
 increase application performance by optimizing the machine
resources
 Single Threading v/s Multithreading
 support for multithreading and synchronization is built into the
language
- java.lang.Thread
Creating Threads

 Extending the Thread class


- offlineEnroller.java
 Implementing Runnable
- onlineEnroller.java
class OfflineEnroller extends Thread
{
private Batch batch;
OfflineEnroller(Batch b)
{
batch = b;
}
public void run()
{
int name = 0;
try{
while(true)
{
++name;
Student s=new Student(“OffLineStudent(“+name+”)”);
if(batch.addStudent(s)==false)
break;
System.out.println(“added: “+s);
}
}catch(StudentExistsException e){
System.out.println(“Caught: “+e);
}
public static void main(String args[])
{
Batch b=new Batch(“J1”, 15);
Thread t=new OfflineEnroller(b);
t.start();
}
}
class OnlineEnroller implements Runnable
{
private Batch batch;
OnlineEnroller(Batch b)
{
batch = b;
}
public void run()
{
int name = 0;
try{
while(true)
{
++name;
Student s=new Student(“OnLineStudent(“+name+”)”);
if(batch.addStudent(s)==false)
break;
System.out.println(“added: “+s);
}
}catch(StudentExistsException e){
System.out.println(“Caught: “+e);
}
}
public static void main(String args[])
{
Batch b=new Batch(“J1”, 15);
Thread t=new Thread(new OnlineEnroller(b));
t.start();
}
}
synchronized methods

 Thread that is currently executing a synchronized method in an


object owns the object monitor
 other threads are prevented from invoking a synchronized method
on this object till the monitor becomes free(ie. These threads are
blocked)
 other threads can invoke non-synchronized methods on this object
 other threads can be executing the same or other synchronized
method of another object
synchronized statements

 Locks an object, without executing a synchronized method of that


object
public static void abs(int[] array) { synchronized(array)}
Basic Java – Session 6

 AWT
 Introduction to Swing
 Event Handling
 Listeners
 Adapters
 Inner classes
 Applets
AWT

AWT features include

 a rich set of user interface components


 a robust event-handling model
 graphics and imaging tools, including shape, color, and font classes
 layout managers, for flexible window layouts that don’t depend on a
particular window size or screen resolution
Java.lang.Object

CheckboxGroup TextComponent TextField

Component Button

FlowLayout Label

BorderLayout Checkbox

GridLayout List

Choice

Container

Window Panel

Frame
Java.awt.Component

 A component is an object having a graphical representation that


can be displayed on the screen and that can interact with the user
 Examples of components are buttons, checkboxes , and scrollbars
of a typical graphical user interface

Some methods of Component:


setVisible(boolean)
isEnabled()
setBackground(Color)
Java.awt.Container

 A generic container object is a component that can contain other


AWT components
 Use the add(component) method to add a component to a
container
 getComponents() would return all the components in a container
Java.awt.Window

 Window class creates the top level window


 Sits directly on the desktop, cannot be contained in any other object
 Generally, you won’t create a Window object directly, instead a
subclass of Window called Frame
 Creation of a window requires associating it with an owner(Frame
or Window)
Labels and Buttons

Labels : Simplest of AWT components


 Display only; hence do not generate an action event

Label nameLb1= new Label(“Name”);


nameLb1.setForeground(Color.green);

Buttons : Most useful components


 Generate action events

Button submitButton=new Button(“submit”);


CheckBoxes

 Similar to buttons, but used as on/off switches


 Contains two parts
- a label(text displayed on the checkbox)
- a state(state of the checkbox - false/true)
CheckBox chBox1=new CheckBox(“Yes/No”);
 Use checkBox.getState() method to find out if a checkBox is
selected or not
CheckBoxGroup

 A special case of CheckBox; a set of CheckBoxes put together in a


group so that only one could be selected at a point of time
CheckBoxGroup group1=new CheckBoxGroup();
CheckBox chBox1=new CheckBox(“Red/Blue”,group1,false);
CheckBox chBox2=new CheckBox(“Yellow/Green”,group1,true);

 To obtain user selection


Use getState() on each checkBox or
Use getSelectedCheckBox() on the CheckBoxGroup
Layout Manager

 Interface that know how to layout components


 BorderLayout, CardLayout , FlowLayout, GridLayout,
GridBagLayout implement the LayoutManager interface
 Default layout manager for all cantainers is FlowLayout - just aligns
the components from left to right
Layouts

 BorderLayout - has 4 narrow fixed - width components at the edges


and one large area in the center, represented by “North”, “South”,
“East”, “West”, and “Center”
 GridLayout - lays out components in a 2 dimensional grid
 CardLayout - helps in having hidden layouts, activating them when
needed

...contd.
...contd.

 GridBagLayout places components in a grid of rows and columns,


allowing specified components to span multiple rows or columns.
Not all rows necessarily have the same height. Similarly, not all
columns necessarily have the same width

Note: Now , Go to Sample Code


More...

 Label
 Button
 TextField
 TextArea
 Choice
 List
 MenuBar, Menu, MenuItem
Swing - AWT

 Swing components are implemented with absolutely no native code


 You can specify which look and feel your program’s GUI uses. By
contrast, AWT components always have the look and feel of the
native platform
 Swing components with state use models to keep the state
 You don’t add components directly to a top-level container such as
a JFrame. Instead, you add components to a container(called the
content pane) that is itself contained by the JFrame
- getContentPane().add(component);
How to set the Look and Feel

 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

 Integrated Development Environments minimize the time needed to


create Java applications/applets/beans/servlets GUIs drastically
 All IDEs do not guarantee 100% pure Java code. Some popular
IDEs
- Visual Age For Java2.x,IBM
- JBuilder2,Inprise
- Visual J++, Microsoft
- Symantee Café, Symantee Corporation
Event Handling

 AWT provides a set of listener interfaces that event handlers have


to implement
 AWT components notify the occurrence of events by generating
event objects that should be handled by a event listener
 Events could be clicking on a button, using the mouse on a
components, selecting items from a list, etc.
ActionListener

 Handles Button events in the actionPerformed(ActionEvent ev)


method
 Creates an ActionEvent object and submits to the handler

aButton.addActionListener(new ActionListener)
{
public void actionPerformed(ActionEvent ev)
{
System.out.println(“hello world”);
}
}
ItemListener

 Handles Item(List, ComboBox) events in the


itemStateChanged(ItemEvent ev)method
 Creates an ItemEvent object and submits to the handler

aCombo.addItemListener(new ItemListener)
{
public void itemStateChanged(ItemEvent ev)
{
System.out.println(“hello world”);
}
}
Adapters

 MouseListener, WindowListener comes bundled with more than


one method
 Classes using such listeners need to implement all the methods, or
atleast provide stubs
 Adapter classes provide stubs for all the methods in such Listener
interfaces
 Extend from Adapter classes and override the methods instead of
implementing interfaces
WindowAdapter

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

 Classes enclosed within a class


 Scope always remains along with the enclosing class

 Static inner class is a nested class

 Created when u need to write classes with little functionality needed

for use only in the scope of a main class


Inner class created by
 EnclosingClass instance.new InnerClass();
Inner classes – Sample Code

public class MainClass extends Frame{



addWindowListener(new InnerClass());

public class InnerClass extends WindowAdapter


{
public void windowClosing(WindowEvent ev)
{
System.exit(0);
}
}
}
Events: How to…

To handle events, use Listeners and Adapters


Steps involved:
 Implement the listener or extend the Adapter

 Provide implementation for the methods in the interface or override

the methods in the Adapter


Applets

 Applet is a class that is derived from java.applet.Applet


 Can be embedded in an HTML page and the class file gets
downloaded to the client along with the HTML page
 Milestones during the lifetime of an applet – init(), stop(), start(),
destroy(), paint()
 showStatus(String text) displays message on the status bar of the
applet
Applet – init()

 This is the method which is called by the browser when an instance


of applet is created and loaded
 Initialization of the applet could be done here
 No argument constructors are allowed
Applet - start() / stop()

start()
 Called whenever user returns to the page or maximizes the window

 Usually overridden to resume the suspended threads

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

 Called each time the applet’s output must be redrawn

 has one parameter of type Graphics – contains graphics context

used whenever output to the applet is required


Applet - update()
 Update() fills an applet with the default background color and then
calls paint()
 Override update so that it displays without flashing

public void paint(Graphics g){


update(g);
}
public void update(Graphics g){
Color bg = getBackground();
Color fg = getForeground();
g.setColor(bg); g.fillRect(x,y,w,h);
g.setColor(fg);
}
Applet parameters

 Applet can be passed parameters using <PARAM> tag in HTML file


<PARAM NAME = “printString” VALUE = “Hello”>

 Use the getParameter(paramName) in the applet code to retrieve


the value associated
String textToBePrinted = getParameter(“printString”);
AppletContext

 A link to the browser itself, actually controls the browser


environment in which the applet resides
- getAppletContext() returns the AppletContext environment
 To change the displayed web page, use the
getAppletContext().showDocument(Url url)method
 Use codebase and documentbase properties in the html file to let
the environment know where to look for classes at runtime
Applet Security

 Easily downloadable over the internet, hence needs to be restricted


 To prevent access to system resources in client machine, browser
or applet viewer installs a security manager – which prevents the
applet from
- accessing system properties
- making network connection to any other host other than the
originating host
- loading of local libraries
Points to note

 When an applet uses java extension classes the browser’s java


environment might/might not support it
 Java plug-in for Internet Explorer and Netscape Navigator could be
used
 Plug-in has to be identified in the html file
 Package the files needed by an applet into a jar(Java Archive) and
load over the internet
 Java console could be opened using the plug-in for informative
debugging messages

You might also like