Professional Documents
Culture Documents
BasicJavaProgramming PDF
BasicJavaProgramming PDF
Our Agenda
Introduction to OOPS
What is Java?
Java architecture
Exceptions Handling
You need to familiarize yourself with some terms like Class, Object,
Inheritance, Polymorphism etc etc.
The programming style that you use in C where importance is given for
functions can be called as structured programming
What is a Class?
A class is a blueprint or prototype that defines the variables and the methods
common to all objects of a certain kind.
So what is an Object?
The object diagrams show that the object's variables make up the center,
or nucleus, of the object
Methods surround and hide the object's nucleus from other objects in the
program. Packaging an object's variables within the protective custody of
its methods is called encapsulation
class Employ {
String Name;//attribute
int Age;//attribute
//a behavior
void printDetails(){
System.out.println(Name is+Name);
System.out.println(Age is+Age);
}
}
However, subclasses are not limited to the state and behaviors provided
to them by their superclass.
Subclasses can add variables and methods to the ones they inherit from
the superclass.
You are not limited to just one layer of inheritance. The inheritance
tree, or class hierarchy, can be as deep as needed.
The abstract superclass defines and may partially implement the behavior, but
much of the class is undefined and unimplemented
A general-purpose language
High-level language
Supported today by most of the big players like IBM, Netscape, Oracle,
Inprise etc.
Object-oriented
Simple
Robust
Secure
Multithreaded
Distributed
An interpreted language
System.out.println(Hello World!);
The name of the file must always be the name of the public class
You can have only one public class in a file(i.e. in one .java file)
Every stand alone Java program must have a public static void main
defined
it is the starting point of the program.
If it does not say anything and get the prompt the compilation was successful.
java HelloWorldApp
The result
Once compiled code will run on any platform without recompiling or any
kind of modification.
This is made possible by making use of a Java Virtual Machine a.k.a. JVM
The .class file that is generated is the machine code of this processor.
The interface that the JVM has to the .class file remains the same
irrespective of the underlying platform .
The JVM interprets the .class file to the machine language of the
underlying platform .
The underlying platform processes the commands given by the JVM and
returns the result back to JVM which displays it for you.
JDK or Java Development Kit is a free software that can be used to write
and compile Java programs.
Currently version 1.3 has been released but we will be using version 1.2.2
It has lots of examples and the Standard Java Class Library also called
the API
Constructors
Functions or Methods
Reference type
false
The Java programming language does not support the explicit use of
addresses like other languages do
private
- package
protected
Access specifiers
static
final
abstract
native
synchronized
Copyright 2005, Infosys Technologies 40
Ltd
final Modifier
For variable:
Primitives: read-only
A concrete class can be made abstract by using the modifier for the class
Constructors
Static methods
Private methods
synchronized Modifier
Scope also determines when the system creates and destroys memory
for the variable
The scope of a local variable extends from its declaration to the end of
the code block in which it was declared
Public variables and methods are those which can be accessed from any
where i.e. From the class, outside the class and outside the package.
Private variables are those which can be accessed only within the class.
Protected variables re those which are visible only inside the class and
the children classes of that class.
If your class extends a base class then your derived class will be able to
access the variables and methods of the base class that are declared as
protected
The default Scope i.e. if you dont specify any access modifiers the scope
is package scope.
It means that within the package the class is it will be accessible but
outside the package it is not accessible.
Class B
Class C Class C
Following are the code for the diagram in the slide shown
before :
Class
ClassBBextends
extendsAA Class
Class CC extends
extendsAA, ,BB
{{ {{
}} }}
Class
ClassCCextends
extendsBB
{{
The code written above is
}} not acceptable by Java
Copyright 2005, Infosys Technologies 59
Ltd
Implementing Multiple Inheritance in Java
Class
Class EE implements
implements A,A,B,B,CC
Class E
{{
. .. .. .. .. .. .. .. .. .. .. .. .; ;
}}
Copyright 2005, Infosys Technologies 60
Ltd
Another way of implementing multiple Inheritance
import
import java.io.*
java.io.*; ;
Importing the folder
where myinterface.class import
import mypackage.*
mypackage.*; ;
file is stored Class
Classdemo
demoimplements
implementsmyinterface
myinterface
{{
public
publicvoid
voidadd(int
add(intx.,
x.,int
inty)y)
{{
System.out.println(
System.out.println( ++( (xx++yy ););
}}
}}
Public
Publicstatic
staticvoid
voidmain(String
main(Stringargs[
args[])])
{{
deno
deno dd == new
new demodemo( () ) ; ;
d.add
d.add(10
(10, ,20
20) ); ;
}} 2005, Infosys Technologies
Copyright 63
Ltd
Interfaces Contd
It helps to avoid naming conflicts. When you are working with a number of
classes, it becomes difficult to decide on names of the classes & methods.
At times you would want to use the same name, which belongs to an
another class. Package, basically hides the classes and avoids conflicts in
names.
Packages allow you to protect your classes, data and methods in a larger
way than on a class-to-class basis.
Method to
Some Some
Class Method find area of Method
the circle
javac
javac -d
-d c:\
c:\JavaProgs
JavaProgs Calculate.java
Calculate.java
java . util
Contains classes and interfaces that provide additional utility but
may not be always vital.
Since these are abstract classes, they cannot be used directly but must
be inherited, so that the abstract methods can be implemented.
All I/O stream classes are derived from either of these classes.
The classes derived in Inputstream and Outputstream can only read from
or write to the respective files.
We cannot use the same class for both reading and writing operations.
An exception to this rule is the class RandomAccessFile.
This is the class used to handle files that allow random access and is
capable of mixed reading and writing operations on a file.
There are two additional interface to this package :
Data input
Data output
These classes are used to transfer data other than bytes or
characters
One of the most important package in this package is the class Date,
which can be used to represent or manipulate date and time information.
The statement :
import java.awt.* ;
Will include all the classes available in the awt subdirectory
present in the java directory.
While creating a package, care should be taken that the
statement for creating a package must be written before any
other import statements
LEG ILLEGA
AL L
package mypackage ; import java . io;
import java . io; package mypackage ;
java.io
This package consists of classes that help you for all the
Input and Output operations.
In Java, array are objects and can be of primitive data types or reference
types
Initializing an Array
<elementType>[] <arayName> = {<arrayInitializerCode>};
Example:
int IntArray[] = {1, 2, 3, 4};
IO Streams in Java
Data
InputStream File
InputStream
File
Object
InputStreams are used for reading the data from the source.
int,float,double. Java
program
DataOutputStream dos =
FileOutputStream("item.dat"));
dos.writeFloat(itemPrice);
dos.writeInt(itemQty);
dos.writeChars(itemNo);
LineNumberInputStream
PushBackInputStream
PrintStream
BufferedReader in = new
BufferedReader( new
InputStreamReader(System.in));
Has equals( ) method that should be used to compare the actual string
values
Lot of other methods are available which are for the manipulation of
characters of the string
Properties
HashTable
Vector e.t.c
Vector( )
Vector(int size)
Vector(int size, int incr)
import java.util.Date;
class DateDemo{
public static void main(String args[])
{
//Instantiating a Date Object
Date date=new Date();
System.out.println("current date is"+date);
System.out.println("current day is"+date.getDay());
System.out.println("current month is"+date.getMonth());
System.out.println("current Year is"+date.getYear());
long msec=date.getTime();
System.out.println("Milliseconds since Jan. 1,1970 ="+msec);
}
}
utilities like event handling, user 3. Since applets runs inside the Browser, it
interface, etc. should be explicitly enjoys all the inbuilt facilities of some event
written by the programmer. handling.
. No Control over the low of the program . There is some control over the execution of the
program.
Copyright 2005, Infosys Technologies 108
Ltd
Applet
What is an applet?
import java.applet.Applet;
import java.awt.Graphics;
init( )
Applet
Displayed stop( )
Destroy
Idle Applet
State destroy( )
If start( )
called again Applet
Destroyed
Copyright 2005, Infosys Technologies 110
Ltd
Applet Life Cycle..
The Browser creates an Object of the applet and then it calls a sequence
of methods on that object.
Then repaint().
So there is no need for a public static void main in the applet to work
because the browser creates the object and calls the method on that.
Every time you move out of the HTML that contains your applet and then
come back the start() is called.
When ever you lose scope and return the paint() is called.
You need to override only the methods you want, the others are
redirected to the base class.
Why?????????????
What is an Exception?
The exception handler can attempt to recover from the error or, if it
determines that the error is unrecoverable, provide a gentle exit from the
program.
Throwable
Error Exception
Runtime
Exception
Copyright 2005, Infosys Technologies 121
Ltd
Try catch -finally
try { statement(s)
statement(s) }
finally { statement(s)
ArithmeticException
ClassCastException
IllegalStateExecption
IndexOutOfBoundsException
InstantiationException
NullPointerException
SecurityException
ClassFormatError
InternalError
LinkageError
OutOfMemoryError
StackOverflowError
VirtualMachineError
UnknownError
The Throws keyword is used along with the declaration of a method that
can throw an exception.
This makes it mandatory for anyone calling the method to have it in try
block.
if(accountIsValid()){
continue}
else{
Adding components
Layout
Another Container
Use Containers
containers hold the Components and helps to organize the
components into manageable groups.
provides the basic window and dialog services.
top-level windows are represented by the Frame class.
Grid Layout
Border Layout
Card Layout
GridBag Layout
Event
Generator Listener
MouseListener
MouseMotionListener
WindowListener
Any given program can listen for some, none, or all of these
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
Button
Generates action events when the button is pressed
CheckBox
Generates item events when the check box is selected or deselected
Choice
Generates item events when the choice is changed.
List
Generates action events when an item is double-clicked
Menu Item
Generates action events when a menu item is selected
Scrollbar
Generates adjustment events when the scroll bar is manipulated
Text components
Generates text events when the user enters a character
Window
Generates window events when a window is activated, closed, deactivated,
deiconified, opened,or quit.
MouseListener
void mouseClicked(MouseEvent e)
void mouseEntered(MouseEvent e)
void mouseExited(MouseEvent e)
void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)
WindowListener
void windowActivated(WindowEvent e)
void windowClosed(WindowEvent e)
void windowClosing(WindowEvent e)
void windowDeactivated(WindowEvent e)
void windowDeiconified(WindowEvent e)
void windowIconified(WindowEvent e)
void windowOpened(WindowEvent e)
import java.awt.*;
import java.awt.event.*;
Applets
Exception Handling
Event Handling