JAVA Tutorial
Index
1. Java Introduction
2. GUI Programming - AWT /SWING
3. Event Handling
4. Exception Handling
5. File I/O
6. JDBC
7. Oral Preparation
Object Model :Abstraction
Abstraction is the process of identifying the key aspects
of an entity and ignoring the rest.
We select only those aspects which are important with
respect to domain use.
Example: Abstraction of a person object.
A person have lot many attributes, but if application is
for health care industry ,then only health related
attributes will be considered and not others.
Only domain expert can do right abstraction.
Object Model : Encapsulation
Wrapping up of data and methods inside an object is
called as encapsulation.
Encapsulation ensures that data within an object is
protected; it can be accessed only by its methods.
The data is hidden, so that it doesnt get corrupted due to
some programming mishap.
The client can access data, but only through the methods
of class.
The implementer can dictate how the data could be
accessed.
Encapsulation
Methods
Variables
Object Model : Inheritance
Inheritance is a property of a class hierarchy whereby
each subclass inherits attributes and methods of its super
class.
The sub class can have additional specific attributes and
methods.
is-a kind of relationship.
Vehicle
2 Wheeler
3 Wheeler 4 Wheeler
Kinetic Scooter
Object Model : Polymorphism
The ability of different objects to respond to the same
message in different ways is called polymorphism.
Polymorphism helps us to design extensible software as
we can add new objects to the design without rewriting
existing procedures.
Example,
move ()
move ()
move ()
Object Model: Minor Pillars
Strong Type Casting:
prevents mixing of abstraction E.g.- Bank Slip.
Persistence :
saves state of a object across time & space.
E.g. Local object and object that outlive the program.
Concurrency :
many objects responding simultaneously.
E.g.- typing into a file & printing file at the same time.
Features of java: Why Java?
Object oriented:
everything is in class.
Simple:
programming is simple.
Robust:
reliable language.
Distributed:
useful in distributed environment.
Secure:
data is encapsulated within object.
Portable / Platform Independent:
can be run on any OS.
write once ,run everywhere
Dynamic :
dynamic changes can be made(polymorphism)
Multi Threaded:
many processes(threads) run at a time.
Java differences with C
Basic statements in java are identical to C++.
Object-oriented only!
No .h files.
main() is inside a class.
No global variables.
No Structures, pointers (object references only).
No destructor: automatic garbage collection.
Single inheritance only, interfaces.
Applet/application.
GUI: AWT, Swing.
Packaging.
Error Handling, exceptions (try, catch).
E.g. Array bounds checking
Why is java platform independent?
C program execution
C
Program
Windows
OS
Linux OS
Mac OS
Compiler
Compiler
Compiler
.c file
In C program execution ,
Source code is compiled and executed.
But for every operating system different
compiler is required.
It is necessary to compile a C program on
each OS.
Hence platform dependent execution.
Example, .NET Framework run only on
Microsoft windows.
Java program execution
Java
Program
Byte
code
JVM for
Linux OS
JVM for
Macintosh OS
Compiler
JVM for
Windows OS
.java file .class file
In Java program execution ,
Compiler converts source code in to byte code.
Byte code is a class file.
JVM installed on each OS coverts byte code
into OS native code(machine code).
Same class file can be executed on any OS.
In short, write code once and run it anywhere.
Java is platform independent but JVM is
platform dependent .
Java compilation & execution syntax
Code:
hello.java (text file)
Compile:
javac hello.java
Creates: hello.class (byte code)
Run:
java hello
Java virtual machine, interprets (machine code)
Packaging: jar
Sample Java program
hello.java:
class hello {
public static void main(String[] args)
{
System.out.println(Hello World!);
}
}
javac hello.java
java hello
Hello World!
Typically create objects
hello.java:
class hello{
int a;
public hello(int x)// Constructor
{this.a=x;}
public static void main(String[] args)
{ // Create and use objects
hello h = new hello(4);
System.out.println(value of a is :+h.a);
} }
javac hello.java
java hello
value of a is :4
Many Classes
Compile each separately
Can be main( ) in any/all classes
hello.java:
class hello {
goodbye g;
public static void main(String[] args){
}
agoodbye.java:
class goodbye {
public static void main(String[] args){
}
Making Batch File
dir
hello.class
goodbye.class
blah.class
foo.class
bar.class
areyouawakein.class
Java ???
RunMe.bat:
java hello
Class
A class is a template for creation of like objects.
An object is an instance of a class.
Classes are used to map real world entities into data
members & member functions.
Java Class Syntax:
class class_name
{ variable declaration ;
method declaration ;
public static void main(String [] args)
{
}
} //end of class
Constructor
Constructor is a special method with same name as its
class name.
No return type for constructor. Not even void.
Constructors are implicitly called when objects are
created. Used for initialization.
A constructor without input parameter is default
constructor.
Constructor can be overloaded (parameterized).
Structure of Memory
Stack Area
Heap Area
Data Area
Code Section
Local Variables
Dynamically allocated Area
Static & Global Variables.
Movable Boundary
Fixed Boundary
( objects store on heap )
Method Overloading
Reusing the same name for a method.
Method signature (types and no of parameters & return
types) different.
Method calls are resolved at compilation time
using the method signature.
Also called as Static Polymorphism, because of
compile time method resolution.
Inheritance
Inheritance is one of the major pillars of object oriented
approach.
Inheritance allows creation of hierarchical classification.
Advantage of inheritance is reusability of code.
Already written code can be extended as & when
required to adopt different situations.
Super & Sub classes
Vehicle
3 Wheeler 2 Wheeler
Generalization
Specialization
This is is - a kind of hierarchy.
Sub class inherits data members & methods of its super class
Super class
Sub class
Inheritance Syntax
class super_class_name
{
// body of super class
}
class sub_class_name extends super_class_name
{
// body of sub class
}
This sub class can use member variables and methods of super class.
Polymorphism
Polymorphism involves same method names having
different implementations.
Polymorphism support resolves the method call to
suitable implementation.
Polymorphism allows to design & implement systems
that are more easily extensible and maintainable.
Method Overriding
Reusing the same name for a method.
Method signature (types and no of parameters & return
types) is same.
Method calls are resolved at run time using the dynamic
data type.
Also called as Dynamic Polymorphism, because of run
time method resolution.
Dynamic data type governs method selection
Every reference variable has two types-
1. static 2. dynamic
Example:
Employee emp = new Manager();
Here emp has static data type Employee
and has dynamic data type Manager.
Example
Lets create an array of Employees:
Emp e[ ] = new Emp[4];
e[0]= new Employee();
e[1] = new Manager();
e[2] = new SalesPerson();
e[3] = new SalesExecutive();
computeSalary() is the method for all.
To find salary of SalesPerson.
e[2].computeSalary();
Difference between Overloading and Overriding
Method Overloading Method Overriding
Method overloading happens in the
same class
Method overriding happens between
inherited classes.
Signature of overloaded method should
be different
Signature of overridden method should
be same.
Constructor can be overloaded. Instance methods , class methods
(static methods )can be overridden.
Handy for program design , because you
dont have to keep track of a bunch of
different method names.
Overriding enables to provide a different
behavior for an object without changing
method signature.
Abstract Class
Abstract class is a facility to collect generic or common
features into a single super class.
Abstract classs one or more methods are declared but
not defined.
Object of abstract class can not be created.
Any sub class of an abstract class must implement all
abstract methods of super class.
Advantages:
1. Useful to achieve polymorphism.
2. Helps to create base classes that are generic
and implementation is not available.
Abstract Class Syntax
An abstract class definition looks like a class definition
that can have abstract methods as well as concrete
methods.
The keyword abstract appears before class name.
abstract class Instrument
{
abstract void play(); //abstract method
void replay(); //normal method
}
Abstract methods need to be overridden.
Interface
Java does not support multiple inheritance.
Meaning that one sub class can not be inherited from two
super classes.
Java supports single chain of implementation
inheritance(single hierarchy).
Vehicle Cars
2 Wheeler
This is wrong.
The subclass 2 wheeler can not be
inherited from two super classes.
Need of Interface
To overcome lack of multiple inheritance Java uses
INTERFACE INHERITANCE.
Interface is essentially a collection of constants &
abstract methods.
The interface approach is sometimes known as
programming by contract.
An interface is used via the keyword implements.
Thus a class can be declared as
class MyClass implements Sun //Sun is an interface
{
}
Interface Syntax
A Java interface definition looks like a class definition
that has only abstract methods , although the abstract
keyword need not appear in the definition.
public interface Testable
{
void method1();
void method2(int i , String s);
}
Here the methods are only declared not defined.
A Class implementing interface must override all
methods of that interface.
Interface Rules
Methods in an interface are always public & abstract.
Data members in an interface are always public, static ,
& final.
A sub class can only have a single super class in Java.
But a class can implement any number of interfaces.
Valid Combinations:
class extends class
class implements interface
interface extends interface
Difference between Abstract Class & Interface.
Abstract Class Interface
Abstract classes are only used when
there is is-a type of relationship
between classes
Interfaces can be implemented by
classes that are not related to one
another.
Abstract class can be used within single
hierarchy.
Interface can be used within different
hierarchies.
A class can not extend more than one
abstract class.
A class can implement more than one
interfaces.
Abstract class can have abstract methods
as well as concrete methods.
(normal methods)
Interfaces contain only abstract methods
& final variables.
Final keyword
If a variable is final, it acts like a constant in whole
program.
If a method is final, it can not be overridden in subclass.
If a class is final, it can not be inherited by sub class.
Every method of a final class is by default final.
GUI Programming: AWT
AWT stands for Abstract Windowing Toolkit.
AWT is a general-purpose , multi-platform windowing
library.
AWT provides all the basic functionality that may be
needed for use in developing GUI application.
AWT library provides classes that encapsulates many
useful GUI components.
Hierarchy in AWT
Object
Component
Panel
Container
Window
TextField
Text
TextArea
List
Label
Choice
Checkbox
Canvas
Scrollbar
FileDialog
Dialog Frame
AWT Components
Button :
Generates an event when clicked.
Canvas:
Used to render Graphics.
Checkbox:
Maintains a Boolean States.
CheckBoxGroup:
Used to implement a set of Radio Buttons.
Choice:
Menu item that maintains Boolean States.
AWT Components
Label :
Displays a Text string.
List :
Displays a list of items.
Menu :
Contains Menu Items.
MenuItem:
Inserted in a Menu.
MenuBar :
Contains Menus.
AWT Components
ScrollBar :
Implements Scrolling Bars.
ToolBar :
Contains Buttons.
TextArea :
Provides editing for multiline text string.
TextField :
Provides editing for a one line text string.
Methods of Component Class
setVisible()
Makes the component visible.
setEnabled()
Enables or Disables a component.
setBackground()
Sets the components background color.
setFont()
Sets components Font.
setSize()
Sets Size of component.
Methods of Component class
setBounds(): Sets Location and Size of component.
paint() : It is Called to repaint component.
public void paint(Graphics g) {
g.drawString(Hello World,50,50) ;
g.setFont(Arial.Font.BOLD,20);
g.setColor(color.GREEN);
}
O/P=> Hello World
AWT Containers
Class Window:
A basic building block class for producing Windows.
Class Frame:
1. A basic building block class for producing full-
fledged Windows.
2. Frame Have Titles , Background, Colors,
Optional menu Bars and Layout Managers.
3. Frame can not have a sub frame within it.
Syntax to create a Frame:
import java.awt.*;
class My_Frame extends Frame
{
public static void main(String args[])
{
My_Frame mf=new My_Frame();
mf.setSize(100,100);
mf.setVisible(true);
}
}
AWT Toolkit
Encapsulates details of the underlying OS & h/w that a
JVM is running on.
This object is created when the JVM starts ,before any of
the application classes are loaded.
Toolkit defines the methods that create OS peers for
AWT components.
These methods are called automatically.
Toolkit Object can be obtained by calling
getDefaultToolkit() method of Toolkit class.
i.e.
Toolkit. getDefaultToolkit() ;
Peers
Peers are the copies of Operating systems components.
AWT takes help of underlying OS to generate peers of
each User Interface Components and use them.
Hence the resulting program will run on any platform
(OS) with look & feel of target Platform.
Meaning that if program is run on Windows OS , look
& feel of GUI will be similar to that of Windows OS.
If program is run on Linux OS, look & feel will be like
Linux OS components.
Swing
AWT took help of underlying OS to generate peers for
each UI component.
Swing components are purely written in Java.
Therefore lightweight, since no peers are created.
Also Swing components need not depend on look &
feel of the target platform.
Swing has much bigger set of built-in controls like,
Trees ,image buttons, tabbed panes, sliders, toolbars,
color choosers, tables, text areas to display HTML etc.
Syntactically, letter J is used as prefix to components
name.
Swing Example
import javax.swing.*;
public class Swing_Frame extends Jframe{
Jbutton b;
JTextField tf;
public Swing_Frame (){
tf=new JTextField();
b=new Jbutton(Click);
add(tf); add(b) ; }
public static void main(String args[]) {
swing_Frame sf=new Swing_Frame();
sf.setVisible(true);
}
Event Handling
GUI applications are event- driven applications.
GUI applications generate events when user of the
program interacts with the GUI.
The underlying OS is constantly monitoring these
events.
When a event occurs , the OS reports these events to the
programs that are running.
The application will handle the event using a appropriate
Event Handler.
Delegation Event Model
Source generates an event and send it to one or more
Listeners.
Listener simply waits until it receives an event.
Once received , Listener processes the event ad returns
the response.
Advantage:
* Application Logic that processes the event is clearly
separated from the UI logic that generates the event.
Event :It is an object that describes a state change in a
source.
Event Source: It is an object that generates an event.
A source must register listeners , so that they can receive
notifications about a specific type of event.
Event Listener: It is an object that is notified when an
event occurs.
1. It must be registered with a source.
2. It must implement methods to receive & process
these notifications.
Flow
Event Source
Event
Event Listener
generates
listened by
processes event & returns response
Sample Program
import java.awt.*;
import java.awt.event.*;
class MyFrame extends Frame implements ActionListener {
TextField t1; Button b1;
MyFrame() {
t1=new TextField();
b1=new Button(OK);
b1.addActionListener(this);
add(t1);
add(b1); }
public void actionPerformed (ActionEvent e )
{ t1.setText(OK is pressed); }
public static void main(String args[])
{ MyFrame f=new MyFrame();
f.setVisible(true);
} }
Event Handling Summary
Events Generator Listener Interface Method Parameter
Button
List
MenuItem
TextField
ActionListener actionPerformed ActionEvent
Scrollbar AdjustmentListener adustmentValueChanged AdjustmenEvent
CheckBox
CheckBoxMenu
Item
Choice
List
ItemListener itemStateChanged ItemEvent
TextComponent TextListener textValueChanged TextEvent