SlideShare una empresa de Scribd logo
1 de 80
Programming Approach
Procedural
Break down the problem into smaller parts and solve
each of the smaller problems. Then aggregate to
solve the overall problem
Object Oriented
View problem/system as collection of real world
objects and their interrelationships
Programming Approach – Object Oriented
Terms Used:
Object
An entity that has state, behavior and identity.
state – characteristics of object
behavior – change in characteristic over period of time
identity – unique tag to identify from the other objects
Class
set of objects that share common characteristic and
behaviors
Attribute
state of object maps to attributes
Method
behavior of object maps to methods
Features of Object Orientation:
Abstraction
Difference in the characteristics of the object from
viewer’s perspective
Inheritance
Helps in generalizing common attributes and
behaviors in separate classes from which sub-classes
can be derived
Encapsulation
Helps to hide unnecessary details from the user and
show only those the user can directly use
Polymorphism
Ability to behave differently under different context
Programming Approach – Object Oriented
Programming Approach – Object Oriented
1.Realistic Modeling
2.Reusability
3.Resilience to change
Advantages of Object Orientation:
Programming Approach – Object Oriented
• Applying object oriented methodology for analysis
and design
• Use of object oriented programming language to
implement the design
Effort Required:
What is JAVA ?
Object Oriented Language developed at Sun in 1991
For building platform-independent applications.
Initially being called as OAK, renamed as JAVA in 1995
Features:
1.Object Oriented
2.Multithreaded
3.Architecture-neutral
4.Interpreted
5.Distributed
Important Differences between C++ and JAVA ?
• No Pointer business
• No structures and unions as Class can be used
instead
• Multiple Inheritance not supported
• Operator Overloading not possible
• No global definitions can be given
• Objects are always passed by reference
• No support of delete operator, garbage collection is
automatic
JAVA Application Areas
• Internet (Applet, Servlet, JSP)
• Standalone applications
• Distributed Applications (RMI, EJB)
• Embedded Applications
Tools For Development
• Sun Microsystems J2EE
• SunOne Studio (IDE)
• Java Forte (IDE)
• Oracle’s JDeveloper (IDE)
• Borland’s JBuilder (IDE)
• Many other utilities available as standalone java
editors, compilers, etc
Sun’s version of JAVA
Two latest editions available :
J2SE (Development Tools only)
J2EE (includes Application Server + Development tools)
Installation:
Self Extractable executable is available freely from sun’s
web site. This installs the development and runtime
environment in the path specified.
The directory containing the tools and libraries is basically
referred as JAVA_HOME
Environment Settings:
1.Include JAVA_HOME/bin in the PATH variable
2.Create CLASSPATH variable pointing to
JAVA_HOME/lib/tools.jar or je22.jar (depending on ver)
Programmer’s Environment for JAVA ?
Creating Application (using J2SE/J2EE)
Source Code
(Editor)
Java Compiler
Hello.java Javac.exe
Byte Code
Hello.class
Executing Application (s)
JVM/JRE – Java Virtual Machine (java.exe)
Hello.class
x.class
First JAVA program
1) Write the source code
class Example {
public static void main(String args[])
{
System.out.println(“My First Program”);
}
}
2) Compile the code
javac Example.java
3) Run the application
java Example
Learning core JAVA
Items to be understood for learning core JAVA:
1.General Issues
2.Data Types
3.Variables
4.Operators
5.Control Structures
a)Branching Structures
b)Looping Structures
6.Classes
7.Exception Handling
8.Inheritance
9.Packages and Interfaces
10.Multithreaded Programming
11.Understanding different technologies like Applet,
Servlet, JSP, EJB, …..
Learning core JAVA – Lexical Issues
• Java is free form language – no special indentation
rules
• Java is case sensitive
• Two types of comments are supported:
// single line comment
/* multiline comment
supported by java */
• Semicolon indicates the termination of the java
statement
• Java keywords cannot be used as an identifier
• Identifiers follow rules of naming conventions like
a) cannot start with number
b) no special symbols can be used except
underscore and dollar sign
Learning core JAVA – Data Types
Along with user defined data types, java supports
following simple data types:
Integer – byte (8), short (16), int (32) and long (64)
Floating points – float (32) and double (64)
Characters – char (16) (Unicode storage)
Boolean – boolean (8)
Learning core JAVA – Variables
Variable is the basic storage used in JAVA.
Defined using an identifier, type and an optional initializer.
Declaring Variable:
type identifier [=value] [,identifier[=value]]…] ;
e.g. int a, b, c=0;
char x = ’x’ ;
1. Dynamic initialization is also possible which is done
when it is required
e.g. long x = Math.sqrt(25);
2. Block defines the scope of variable where block is the
opening and closing curly brace
Learning core JAVA – Variables
Type Conversion and Casting of Variable:
• Automatic type conversion happens if:
1.The two types are compatible
2.The destination type is larger than the source type
• Explicit conversion is required for narrow conversions.
It has to be done using general form shown below:
(target-type) value
Learning core JAVA – Variables
Arrays
Group of like-typed variables that are referred to by a
common name. They may have one or more
dimensions. Array indexes start at zero.
One dimensional Arrays:
1) Declaration:
type var-name[];
var-name = new type[size];
or
type var-name[] = new type[size];
e.g int x[] = new int[12];
Two Dimensional Array:
int x[][] = new int[2][4];
Learning core JAVA – Variables
Array Initialization
Two ways:
1. After declaration, setting value for individual elements
of the array
e.g. x[0] =2;
2. At the time of declaration,
e.g. int x[] = {12,10,23,45,58,100};
Alternative Array Declaration Syntax
type[] var-name;
i.e. int[] x = new int[12];
Learning core JAVA – Operators
Four types of operators
Arithmetic
+, -, *, /, %, ++, --, +=, -=, *=, /=, %=
Bitwise
~, &, |, ^, >>, <<, |=, &=
Relational
==, !=, >, <, >=, <=
Logical
&&, ||, !, ?:
Learning core JAVA – Control Structures
Branching Structures
if (cond)
statement
If (cond)
statement1
else
statement2
if (cond1)
statement1
else if (cond2)
statement2
else if (cond3)
statement3
else
statement4
switch (exp)
{
case val1:
//statements
break;
case val2:
//statements
break;
default:
//statements
}
Where ‘exp’ can be byte, short,
int or char
Learning core JAVA – Control Structures
Looping Structures
while (cond)
{
// body of the loop
}
do
{
// body of loop
} while (cond);
for (init; cond; iteration)
{
// body of the loop
}
Learning core JAVA – Control Structures
Jump Statements
1. break
forcibly come out of the loop bypassing the remaining
code in the body of the loop and irrespective of the
loop condition
2. continue
stop processing the remaining portion of the body of
the loop and continue for the next iteration
3. return
passes control back to the calling method terminating
the call at the place return is used
Learning core JAVA – Class Fundamentals
Class in JAVA defines new data type which can be used as
simple data types then after where we can create
variables of the defined data type.
General form of class
class classname
{
type instance-var1;
type instance-var2;
type method1(para-list)
{
//body of the method
}
}
Learning core JAVA – Class Fundamentals
Declaring variable/object of new type called class
e.g. Student tom = new Student();
or
Student tom;
tom = new Student();
Constructors
Method of the class having same name as class and
which is automatically called when the object of the
class is being created.
Used for initializing the instance variables for the object
being created
Learning core JAVA – Class Fundamentals
finalize() method
The method defined in the class is automatically called on
an object when it is about to be collected by the
garbage collector for releasing the memory allocation
This method can be used for cleaning process.
The method has general form as:
void finalize()
{
// finalization code
}
Learning core JAVA – Class Fundamentals
Overloading Methods (Polymorphism)
• Method is said to be overloaded when two or more
methods in class share the same name but their
parameters declarations are different
• Overloaded methods should differ either in type and /
or number of arguments. Having different return type
alone does not overload the method.
Note: As constructors of the class are nothing but
methods, this feature helps in overloading constructors
which further can be used for initializing different
objects with different parameter list.
Learning core JAVA – Class Fundamentals
Access Control Specifiers (Encapsulation)
Access Specifiers help in implementing class as black box
which has methods and data where the data is
accessible only through methods
public
member is accessible by any other code in program
private
member is accessible by only any other member of its
own class
protected
useful at the time of inheritance
Learning core JAVA – Understanding static
Understanding static specifier (global concept)
• Can be applied to the variables and methods
• members declared static can be accessed without
creating objects of the class containing the members
• static members are created at class level
• convention is to use the Class name as prefix when
accessing static members
i.e Box.weight = 20;
• static methods have restrictions as:
1.can only call other static methods
2.can access only static data of the class
Learning core JAVA – Inheritance
Inheritance helps in code reusability where the sub class
can inherit the super class functionality adding its own
additional behavior and attributes to the definition
General form of class declaration that inherits super
class:
class sub-class extends super-class
{
// body of the sub-class
}
Note: JAVA does not support multiple inheritance but
multilevel hierarchy is possible
Learning core JAVA – Inheritance
Constructors execution
When a class hierarchy is created, the constructors are
executed in order of derivation i.e. from superclass to
subclass
Use of super
super keyword has two uses:
1.To call superclass constructors from the subclasses
super(para-list);
2. To access the superclass members which are hidden or
having definition in the subclass
Learning core JAVA – Inheritance
Method Overriding
In a class hierarchy, when a method in subclass has the
same name and type signature as method in
superclass, then the method in the subclass is said to
override the method in superclass.
i.e. method version available in the superclass is
hidden due to method overriding
Helps in local customization of the required method in the
super class
Learning core JAVA – Inheritance
Abstract classes
• Classes created to present just the skeleton and let the
subclass have the implementation
• Forcing the definition of subclass to have certain
functionality
• To declare abstract method, use general form as
abstract type method-name(para-list);
• Any class having an abstract method should be
declared as abstract
• No objects of abstract classes can be instantiated
• Subclass should implement all the abstract methods of
superclass or it otherwise becomes abstract
Learning core JAVA – Understanding final
Understanding final specifier
Can be applied to the member variables, methods and
classes
When applied to:
Variables – prevent its content from modification
(usage similar to const in c++)
e.g. final int PI = 3.17;
Methods – prevents superclass methods from being
overridden in subclass
Classes – prevents class from being inherited
Learning core JAVA – Packages and Interfaces
Package:
Allows to group classes under namespace so that same
name classes can be possible under different name
spaces. This helps in overcoming the situation of
running out convenient descriptive names for the
classes
Defining a package
Include package command as the first statement in the
file containing definition of various classes and all the
classes in that file become part of the package
e.g. package mypack;
We can create hierarchy of packages also.
e.g. package pkg1.pkg2.pkg3
Note: JAVA uses file system directory to store packages
Learning core JAVA – Packages and Interfaces
Importing packages
• Usually java libraries are given in the form of packages.
• The package has to be first imported in the program
and then only the classes defined in the it can be used.
e.g. import pkg1[.pkg2].[classname|*];
Note: Package cannot be renamed until the directory
containing the package is renamed.
Learning core JAVA – Packages and Interfaces
Interface:
• This can be used to specify what class must do but not
how it does.
• They are similar to classes but lack instance variables
and also methods are declared without body.
• Once defined, any number of classes can implement
the interface
• Multiple interfaces can be implemented by one class
• Partial implementation of the interface by the class
make it an abstract class
Learning core JAVA – Packages and Interfaces
Defining an interface
access interface name
{
return-type method-name1(para-list);
return-type method-name2(para-list);
return-type method-name3(para-list);
final type var1;
final type var2;
}
access – can be either public or not used
Implementing an interface
class classname [extends superCls] implements
interface1, interface2 …..
{
}
Learning core JAVA – Packages and Interfaces
Extending an interface
Interfaces can be extended by other interface as
interface B extends A
{
void method1();
}
Now the class implementing interface B has to
implement methods of both the interfaces otherwise it
becomes an abstract class.
Learning core JAVA – Exception Handling
• Exceptions are the conditions which violates the rules
of the java language or the constraints of the java
execution environment.
• Exception in java is an object which is created by the
environment and thrown in the method that has caused
the error. The method may choose to handle or pass on
to the environment back.
• All exception types are subclasses of the built in class
called Throwable which has two branches of
subclasses called Exception and Error. The Error
exception cannot be caught and handled by the
environment.
• Exception handling is done by using five keywords:
try, catch, throw, throws, finally
Learning core JAVA – Exception Handling
• try – catch - finally is used to enclose the code which
may raise an exception and user is interested in
handling the same. finally is the block of code which is
executed irrespective of the exception case occurred or
not. This can be used for clean up operation before
returning from the exception condition.
• throw – used to throw user definable exception
e.g. throw throwableInstance
• throws – method which is capable of throwing an
exception but does not handle it, must specify this
behaviour so that callers can take card if required.
e.g. type methodName(para-list) throws exp_list
{
}
Learning core JAVA – Multithreaded Programming
Multithreaded program consists of two or more parts
which run concurrently. Each part of the program is
called thread and each thread defines a separate
path of execution.
Can be implemented in two ways:
1.Extending Thread class
2.Implementing Runnable interface
Important methods available in Thread class:
isAlive, join, run, sleep, start, stop, suspend, resume
Getting handle to Main Thread:
Whenever java program starts, main thread is
executed and to get handle to that thread
Thread t = Thread.currentThread();
Learning core JAVA – Multithreaded Programming
Implementing Runnable
1.Create class that implements Runnable interface
Class needs to implement single method as
public void run()
Inside run, insert the code that has to be executed
when the thread starts
2. Instantiate an object of the class that has implemented
Runnable interface
Thread(Runnable threadobj, String threadName)
3. After object is created, thread does not start
automatically, so execute
start() - this in turn calls run
Learning core JAVA – Multithreaded Programming
Extending Thread Class
1.Create class that extends Thread
Class needs to override the ‘run’ method
2. Instantiate an object of the class
3. After object is created, thread does not start
automatically, so execute
start() - this in turn calls run
Learning core JAVA – Multithreaded Programming
Thread Priorities
Thread when created start with normal priority. The
priority scale in JAVA goes from 1 to 10 where thread
having 10 gets maximum priority.
setPriority(int level) and getPriority() methods can be
used for changing the priority levels of the threads
created
Note: Thread class does’nt have the constructor which
can be used to create thread with the desired priority
Learning core JAVA – Multithreaded Programming
InterThread Communication
For multiple thread communication, a very simple
mechanism is provided by java and which is part of
Object class,
wait(), notify() and notifyAll() methods
These can be called only from synchronized methods
wait() – tells the calling thread to give up monitor and go
to sleep until some other thread enters the same
monitor and calls notify()
notify() – wakes up the first thread that called wait() on
the same object
notifyAll() – wakes up all the thread that called wait()
I/O In JAVA
I/O in java is stream oriented where stream is defined to
be an logical entity that produces or consumes data.
Streams behave in same manner irrespective of the
physical type
I/O in java is built on four abstract classes:
InputStream and OutputStream – byte/binary oriented
data transfer
Reader and Writer – character oriented data transfer
I/O In JAVA
InputStream Methods:
• int read() - returns -1 if error
• int read(byte buffer[]) – return -1 if EOF
• int available() – returns number of bytes available in
the stream to be read
• long skip(long numBytes)
• void close()
I/O In JAVA
OutputStream Methods:
• void write(int b)
• void write(byte buffer[])
• void flush() – writes everything to stream and clears
the buffer
• void close()
I/O In JAVA
Handling Implicit data type
DataInputStream and DataOutputStream classes –
These are one layer higher and requires base Input and
Output streams to work
Constructors: DataOutputStream(OutputStream os)
DataInputStream(InputStream is)
Methods:
For reading implicit data types using DataInputStream:
readFloat(), readBoolean(), readInt(), readDouble(), …
Similarly for writing using DataOutputStream:
writeFloat(), writeBoolean(), writeInt(), writeDouble(),
etc
I/O In JAVA
Binary File Handling
FileInputStream and FileOutputStream classes –
These classes can be used for raw file handling
Constructors:
FileInputStream(String filename)
FileInputStream(File fileobj)
FileOutputStream(String filename)
FileOutputStream(File fileobj)
FileOutputStream(String filename, boolean append)
Once the object is created, these behave similar to
InputStream/OutputStream classes
I/O In JAVA
PrintStream Class
This class is provided to write the formatted output. It
requires a raw output stream for working
Constructor:
PrintStream(OutputStream os)
Methods:
Along with all implicit data type writing methods, it has
print and println methods also.
I/O In JAVA
Character Streams
Reader Class (Methods):
int read() – read next char or returns -1 on error
int read(char buf[])
long skip(long numchar)
void close()
Writer Class (Methods):
void write(int char)
void write(char buf[])
void flush()
void close()
I/O In JAVA
Character Based File Handling
FileReader and FileWriter classes – These classes can
be used for character based file handling
Constructors:
FileReader(String filename)
FileReader(File fileobj)
FileWriter(String filename)
FileWriter(File fileobj)
FileWriter(String filename, boolean append)
Once the object is created, these behave similar to
Reader/Writer classes
I/O In JAVA
PrintWriter Class
This class is character oriented version of PrintStream
class provided for formatted output.
Constructor:
PrintWriter(Writer wr)
Methods:
Along with all implicit data type writing methods, it has
print and println methods also.
I/O In JAVA
Buffered I/O
JAVA also supports Buffered I/O which can further help in
improving performance
Both the version of buffered I/O has been provided i.e.
binary and character oriented
BufferedInputStream(InputStream is)
BufferedOutputStream(OutputStream os)
BufferedReader(Reader r)
BufferedWriter(Writer w)
As seen, the classes require base I/O streams to work.
I/O In JAVA
Special class - File
File class represents file/folder on file system which can
further used for file management activities i.e. getting
file attributes, deleting, renaming, listing, etc.
Constructor:
File(String filepath)
File(String directory)
File(String dirPath, String filename)
Methods:
isFile(), isDirectory(), exists(), renameTo(File
newName), delete(), list(), getName(), getParent(),
canWrite(), canRead(), lastModified(), length()
I/O In JAVA
Object I/O
Special classes have been provided to have I/O based on
JAVA objects
ObjectInputStream(InputStream is)
ObjectOutputStream(OutputStream os)
Methods like readObject() and writeObject() have been
provided to transfer/receive objects
Note: Object which are serializable only can be
transferred out of JVM to a stream
I/O In JAVA
Object I/O – What is Serializable object?
Serialization is the process of the writing the state of the
created object to a stream. This is useful if the state of
the object is required in later time again or it is
required to be transferred on the network.
How to make Serializable object?
The class of the object to be serialized has to implement
the blank Serializable interface and JAVA takes care of
preserving the context of the object and makes it ready
to put out on the stream.
class GoOut implements Serializable
{
// the definition of the class
}
Socket Programming
Supporting Classes
InetAddress: It encapsulates the IP address and the
domain name of the system. No constructor available,
an instance can be created by calling one of the
following factory methods:
getLocalHost() – get the details of the local host
getByName(String hostname) – returns the said host
details using DNS
Methods those can be used for retrieving information:
1. String getHostName()
2. byte[] getAddress()
Socket Programming
Supporting Classes
URL: Provides a way to identify resource on the Net.
URL(String url)
URL(String protocol, String hostname, String port,
String path)
Methods:
getProtocol(), getPort(), getHost(), getFile(),
openConnection() – creates URL Connection Object
which can be further used for retrieving properties of
the remote object or to have tunneling implemented
Socket Programming
Supporting Classes
URLConnection: Class provided to access the properties
of the remote object and to implement tunneling
Methods:
getDate(), getContentType(), getExpiration(),
getLastModified(), getContentLength(),
getInputStream() – can be used to have socket
communication with web server
Socket Programming
TCP Client Socket
Socket(String hostname, int port)
Socket(InetAddress IP, int port)
This creates socket and connects to the remote host at
the time of object instantiation
Methods:
getPort() – returns remote port
getLocalPort(), getInputStream(), getOutputStream(),
close()
Socket Programming
TCP Server Socket
ServerSocket(int port)
ServerSocket(int port, int Queue)
Used to create socket on the server which is further
used for listening tcp connections
Methods:
Socket accept() - returns client socket which can be
used for further communication
Socket Programming
Datagram Communication
This is implemented using two classes:
DatagramPacket – to send or receive the packet
containing data
DatagramSocket – contains host details for
communication
e.g. Receive Packet
DatagramPacket(byte data[], int size)
Send Packet
DatagramPacket(byte data[], int size, InetAddress
ip, int port)
Socket Programming
Datagram Communication – Contd…
DatagramPacket Methods:
byte[] getData() – retrieves data from the received
packet
int getLength() – returns size of the packet
DatagramSocket – used to create UDP based socket
Methods:
send(DatagramPacket dp)
receive(DatagramPacket dp)
Abstract Windows Toolkit (AWT)
Control Classes Hierarchy
Component
Container
Window Panel
Frame Applet
General methods for handling
Event, colour, font, etc
Additional methods of adding
And removing components
Methods:
add(Component)
remove(Component)
removeAll() Window without
Menu and
Titlebar
All GUI Controls
Abstract Windows Toolkit (AWT)
GUI Controls
1.Labels
2.Push Button
3.CheckBoxes
4.ChoiceLists
5.Lists
6.Text Editing
1. Label
Label(String str)
Label(String str, int how)
where how can be Label.LEFT, Label.RIGHT or
Label.Center
Caption can be changed using:
void setText(String)
String getText()
Abstract Windows Toolkit (AWT)
2. Button
Button(String)
Changing the label on button:
void setLabel(String)
String getLabel()
3. Checkbox
can be individual or in group like radio buttons
Checkbox(String)
Checkbox(String, boolean)
Checkbox(String, CheckboxGroup, Boolean)
for radio buttons
Methods: getState(), setState(), getLabel(), setLabel()
and getSelectedCheckbox() – for radio button
Abstract Windows Toolkit (AWT)
4. Choice Control
Empty constructor for creating object and then use
add(String) for adding elements in the list
Methods:
getSelectedItem() – to get the string of the item
getSelectedIndex() – index of the selected item
getItemCount()
void select(int) – for setting the selected item
5. List Control
List(int nRows) – number of rows to display
All methods of choice control apply.
Abstract Windows Toolkit (AWT)
5. TextComponent
Two sub classes exists of TextComponent for text
editing i.e. TextField and TextArea
TextField:
TextField(), TextField(int nchar), TextField(String)
TextField(String, int)
Methods:
getText(), setText(), setEchoChar(char)
TextArea:
TextArea(int nlines, int nchar)
TextArea(String)
TextArea(String, int nlines, int nchar)
Abstract Windows Toolkit (AWT) – Layout Manager
Layout Manager places component in appropriate place as
defined in the algorithm
All containers have some default layout manager defined
and if required can be changed using
setLayout(LayoutManager) method.
if null is passed for setLayout() then each component
has to be placed using setBounds() method
Some of the supported Layout Manager Classes:
1.FlowLayout
Default layout manager for Panel/Applet places
components at flow of text
FlowLayout()
FlowLayout(int how)
where how can be FlowLayout.LEFT/RIGHT/CENTER
Abstract Windows Toolkit (AWT) – Layout Manager
2. BorderLayout
Divides the total screen area in five sections as shown
below:
North
South
W
e
s
t
E
a
s
t
CENTER
For adding components to appropriate regions,
add(Component comp, int region)
where region can be
BorderLayout.CENTER/SOUTH/NORTH/EAST/WEST
Abstract Windows Toolkit (AWT) – Layout Manager
3. GridLayout
It lays out the components in a two dimensional grid.
GridLayout(int nRows, int nCols)
GridLayout() – Single col grid layout
AWT – Event Handling
Event handling in JAVA is done using Delegation Model
where the interested object registers with the source to
get the notification when particular event has occurred.
The source passes an event object for appropriate event
type to the listener class which has the methods
implemented to handle the notification.
Process:
1. Create a source
2. Register the listener for interested event
method provided:
addTypeListener(TypeListener)
where Type specifies the type of event
3. Create listener class to handle the event implementing
the methods
i.e. to implement the required listener interface
AWT – Event Handling
Listener Interfaces
1. ActionListener - for handling action event
Method:
void actionPerformed(ActionEvent)
2. FocusListener – for handling focussing events
methods:
void focusGained(FocusEvent)
void focusLost(FocusEvent)
3. KeyListener – for handling key events
Methods:
keyPressed(KeyEvent), keyReleased(KeyEvent),
keyTyped(KeyEvent)
The KeyEvent class has the methods to identify key,
getKeyChar(), getKeyCode()
AWT – Event Handling
4. MouseListener - for handling mouse related events
Methods:
void mouseClicked(MouseEvent)
void mouseEntered(MouseEvent)
void mouseExited(MouseEvent)
void mousePressed(MouseEvent)
void mouseReleased(MouseEvent)
MouseEvent class has the methods to get the
location, mouse key, etc like
getX() and getY() – for getting the location of
mouse pointer
5. TextListener – text editing events
Method:
textChanged(TextEvent)
AWT – Event Handling
6. WindowListener - for handling windowing events
void windowActivated(WindowEvent)
void windowClosed(WindowEvent)
void windowClosing(WindowEvent)
and for Deactivated, Deiconified, Iconified and Opened
7. ItemListener – for handling the checbox and list
control events
Method:
itemStateChanged(ItemEvent)
AWT – Event Handling – Adapter Classes
Adapter Classes Requirement ?
Listener interfaces forcing to implement all the methods
even if some of the events user is not interested in.
Adapter classes have all the methods implemented with
blank method code which helps the user to implement
only the required methods.
Available Adapter Classes:
FocusAdapter, KeyAdapter, MouseAdapter,
WindowAdapter, MouseMotionAdapter

Más contenido relacionado

Similar a core_java.ppt

Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2Rakesh Madugula
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for seleniumapoorvams
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardHari kiran G
 
Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | BasicsHùng Nguyễn Huy
 
Learning core java
Learning core javaLearning core java
Learning core javaAbhay Bharti
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptxSajidTk2
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1javatrainingonline
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in javaagorolabs
 
cs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptxcs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptxmshanajoel6
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsAashish Jain
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interviewKuntal Bhowmick
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in javaElizabeth alexander
 
Java quick reference
Java quick referenceJava quick reference
Java quick referenceArthyR3
 

Similar a core_java.ppt (20)

Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
 
Java Basics for selenium
Java Basics for seleniumJava Basics for selenium
Java Basics for selenium
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notes
 
OCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference CardOCP Java (OCPJP) 8 Exam Quick Reference Card
OCP Java (OCPJP) 8 Exam Quick Reference Card
 
Core Java Introduction | Basics
Core Java Introduction  | BasicsCore Java Introduction  | Basics
Core Java Introduction | Basics
 
PPT Lecture-1.4.pptx
PPT Lecture-1.4.pptxPPT Lecture-1.4.pptx
PPT Lecture-1.4.pptx
 
Learning core java
Learning core javaLearning core java
Learning core java
 
Selenium Training .pptx
Selenium Training .pptxSelenium Training .pptx
Selenium Training .pptx
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
Java 102 intro to object-oriented programming in java
Java 102   intro to object-oriented programming in javaJava 102   intro to object-oriented programming in java
Java 102 intro to object-oriented programming in java
 
Java notes
Java notesJava notes
Java notes
 
cs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptxcs213Lecture_1 java programming oopsss.pptx
cs213Lecture_1 java programming oopsss.pptx
 
1
11
1
 
Let's start with Java- Basic Concepts
Let's start with Java- Basic ConceptsLet's start with Java- Basic Concepts
Let's start with Java- Basic Concepts
 
Module 1.pptx
Module 1.pptxModule 1.pptx
Module 1.pptx
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Object oriented programming in java
Object oriented programming in javaObject oriented programming in java
Object oriented programming in java
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Java quick reference
Java quick referenceJava quick reference
Java quick reference
 

Último

Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordAsst.prof M.Gokilavani
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Christo Ananth
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlysanyuktamishra911
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . pptDineshKumar4165
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfRagavanV2
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptDineshKumar4165
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Dr.Costas Sachpazis
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spaintimesproduction05
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Christo Ananth
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 

Último (20)

Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete RecordCCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
CCS335 _ Neural Networks and Deep Learning Laboratory_Lab Complete Record
 
Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...Call for Papers - International Journal of Intelligent Systems and Applicatio...
Call for Papers - International Journal of Intelligent Systems and Applicatio...
 
KubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghlyKubeKraft presentation @CloudNativeHooghly
KubeKraft presentation @CloudNativeHooghly
 
Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Unit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdfUnit 1 - Soil Classification and Compaction.pdf
Unit 1 - Soil Classification and Compaction.pdf
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
Structural Analysis and Design of Foundations: A Comprehensive Handbook for S...
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
NFPA 5000 2024 standard .
NFPA 5000 2024 standard                                  .NFPA 5000 2024 standard                                  .
NFPA 5000 2024 standard .
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
Call for Papers - Educational Administration: Theory and Practice, E-ISSN: 21...
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
(INDIRA) Call Girl Bhosari Call Now 8617697112 Bhosari Escorts 24x7
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 

core_java.ppt

  • 1. Programming Approach Procedural Break down the problem into smaller parts and solve each of the smaller problems. Then aggregate to solve the overall problem Object Oriented View problem/system as collection of real world objects and their interrelationships
  • 2. Programming Approach – Object Oriented Terms Used: Object An entity that has state, behavior and identity. state – characteristics of object behavior – change in characteristic over period of time identity – unique tag to identify from the other objects Class set of objects that share common characteristic and behaviors Attribute state of object maps to attributes Method behavior of object maps to methods
  • 3. Features of Object Orientation: Abstraction Difference in the characteristics of the object from viewer’s perspective Inheritance Helps in generalizing common attributes and behaviors in separate classes from which sub-classes can be derived Encapsulation Helps to hide unnecessary details from the user and show only those the user can directly use Polymorphism Ability to behave differently under different context Programming Approach – Object Oriented
  • 4. Programming Approach – Object Oriented 1.Realistic Modeling 2.Reusability 3.Resilience to change Advantages of Object Orientation:
  • 5. Programming Approach – Object Oriented • Applying object oriented methodology for analysis and design • Use of object oriented programming language to implement the design Effort Required:
  • 6.
  • 7. What is JAVA ? Object Oriented Language developed at Sun in 1991 For building platform-independent applications. Initially being called as OAK, renamed as JAVA in 1995 Features: 1.Object Oriented 2.Multithreaded 3.Architecture-neutral 4.Interpreted 5.Distributed
  • 8. Important Differences between C++ and JAVA ? • No Pointer business • No structures and unions as Class can be used instead • Multiple Inheritance not supported • Operator Overloading not possible • No global definitions can be given • Objects are always passed by reference • No support of delete operator, garbage collection is automatic
  • 9. JAVA Application Areas • Internet (Applet, Servlet, JSP) • Standalone applications • Distributed Applications (RMI, EJB) • Embedded Applications
  • 10. Tools For Development • Sun Microsystems J2EE • SunOne Studio (IDE) • Java Forte (IDE) • Oracle’s JDeveloper (IDE) • Borland’s JBuilder (IDE) • Many other utilities available as standalone java editors, compilers, etc
  • 11. Sun’s version of JAVA Two latest editions available : J2SE (Development Tools only) J2EE (includes Application Server + Development tools) Installation: Self Extractable executable is available freely from sun’s web site. This installs the development and runtime environment in the path specified. The directory containing the tools and libraries is basically referred as JAVA_HOME Environment Settings: 1.Include JAVA_HOME/bin in the PATH variable 2.Create CLASSPATH variable pointing to JAVA_HOME/lib/tools.jar or je22.jar (depending on ver)
  • 12. Programmer’s Environment for JAVA ? Creating Application (using J2SE/J2EE) Source Code (Editor) Java Compiler Hello.java Javac.exe Byte Code Hello.class Executing Application (s) JVM/JRE – Java Virtual Machine (java.exe) Hello.class x.class
  • 13. First JAVA program 1) Write the source code class Example { public static void main(String args[]) { System.out.println(“My First Program”); } } 2) Compile the code javac Example.java 3) Run the application java Example
  • 14. Learning core JAVA Items to be understood for learning core JAVA: 1.General Issues 2.Data Types 3.Variables 4.Operators 5.Control Structures a)Branching Structures b)Looping Structures 6.Classes 7.Exception Handling 8.Inheritance 9.Packages and Interfaces 10.Multithreaded Programming 11.Understanding different technologies like Applet, Servlet, JSP, EJB, …..
  • 15. Learning core JAVA – Lexical Issues • Java is free form language – no special indentation rules • Java is case sensitive • Two types of comments are supported: // single line comment /* multiline comment supported by java */ • Semicolon indicates the termination of the java statement • Java keywords cannot be used as an identifier • Identifiers follow rules of naming conventions like a) cannot start with number b) no special symbols can be used except underscore and dollar sign
  • 16. Learning core JAVA – Data Types Along with user defined data types, java supports following simple data types: Integer – byte (8), short (16), int (32) and long (64) Floating points – float (32) and double (64) Characters – char (16) (Unicode storage) Boolean – boolean (8)
  • 17. Learning core JAVA – Variables Variable is the basic storage used in JAVA. Defined using an identifier, type and an optional initializer. Declaring Variable: type identifier [=value] [,identifier[=value]]…] ; e.g. int a, b, c=0; char x = ’x’ ; 1. Dynamic initialization is also possible which is done when it is required e.g. long x = Math.sqrt(25); 2. Block defines the scope of variable where block is the opening and closing curly brace
  • 18. Learning core JAVA – Variables Type Conversion and Casting of Variable: • Automatic type conversion happens if: 1.The two types are compatible 2.The destination type is larger than the source type • Explicit conversion is required for narrow conversions. It has to be done using general form shown below: (target-type) value
  • 19. Learning core JAVA – Variables Arrays Group of like-typed variables that are referred to by a common name. They may have one or more dimensions. Array indexes start at zero. One dimensional Arrays: 1) Declaration: type var-name[]; var-name = new type[size]; or type var-name[] = new type[size]; e.g int x[] = new int[12]; Two Dimensional Array: int x[][] = new int[2][4];
  • 20. Learning core JAVA – Variables Array Initialization Two ways: 1. After declaration, setting value for individual elements of the array e.g. x[0] =2; 2. At the time of declaration, e.g. int x[] = {12,10,23,45,58,100}; Alternative Array Declaration Syntax type[] var-name; i.e. int[] x = new int[12];
  • 21. Learning core JAVA – Operators Four types of operators Arithmetic +, -, *, /, %, ++, --, +=, -=, *=, /=, %= Bitwise ~, &, |, ^, >>, <<, |=, &= Relational ==, !=, >, <, >=, <= Logical &&, ||, !, ?:
  • 22. Learning core JAVA – Control Structures Branching Structures if (cond) statement If (cond) statement1 else statement2 if (cond1) statement1 else if (cond2) statement2 else if (cond3) statement3 else statement4 switch (exp) { case val1: //statements break; case val2: //statements break; default: //statements } Where ‘exp’ can be byte, short, int or char
  • 23. Learning core JAVA – Control Structures Looping Structures while (cond) { // body of the loop } do { // body of loop } while (cond); for (init; cond; iteration) { // body of the loop }
  • 24. Learning core JAVA – Control Structures Jump Statements 1. break forcibly come out of the loop bypassing the remaining code in the body of the loop and irrespective of the loop condition 2. continue stop processing the remaining portion of the body of the loop and continue for the next iteration 3. return passes control back to the calling method terminating the call at the place return is used
  • 25. Learning core JAVA – Class Fundamentals Class in JAVA defines new data type which can be used as simple data types then after where we can create variables of the defined data type. General form of class class classname { type instance-var1; type instance-var2; type method1(para-list) { //body of the method } }
  • 26. Learning core JAVA – Class Fundamentals Declaring variable/object of new type called class e.g. Student tom = new Student(); or Student tom; tom = new Student(); Constructors Method of the class having same name as class and which is automatically called when the object of the class is being created. Used for initializing the instance variables for the object being created
  • 27. Learning core JAVA – Class Fundamentals finalize() method The method defined in the class is automatically called on an object when it is about to be collected by the garbage collector for releasing the memory allocation This method can be used for cleaning process. The method has general form as: void finalize() { // finalization code }
  • 28. Learning core JAVA – Class Fundamentals Overloading Methods (Polymorphism) • Method is said to be overloaded when two or more methods in class share the same name but their parameters declarations are different • Overloaded methods should differ either in type and / or number of arguments. Having different return type alone does not overload the method. Note: As constructors of the class are nothing but methods, this feature helps in overloading constructors which further can be used for initializing different objects with different parameter list.
  • 29. Learning core JAVA – Class Fundamentals Access Control Specifiers (Encapsulation) Access Specifiers help in implementing class as black box which has methods and data where the data is accessible only through methods public member is accessible by any other code in program private member is accessible by only any other member of its own class protected useful at the time of inheritance
  • 30. Learning core JAVA – Understanding static Understanding static specifier (global concept) • Can be applied to the variables and methods • members declared static can be accessed without creating objects of the class containing the members • static members are created at class level • convention is to use the Class name as prefix when accessing static members i.e Box.weight = 20; • static methods have restrictions as: 1.can only call other static methods 2.can access only static data of the class
  • 31. Learning core JAVA – Inheritance Inheritance helps in code reusability where the sub class can inherit the super class functionality adding its own additional behavior and attributes to the definition General form of class declaration that inherits super class: class sub-class extends super-class { // body of the sub-class } Note: JAVA does not support multiple inheritance but multilevel hierarchy is possible
  • 32. Learning core JAVA – Inheritance Constructors execution When a class hierarchy is created, the constructors are executed in order of derivation i.e. from superclass to subclass Use of super super keyword has two uses: 1.To call superclass constructors from the subclasses super(para-list); 2. To access the superclass members which are hidden or having definition in the subclass
  • 33. Learning core JAVA – Inheritance Method Overriding In a class hierarchy, when a method in subclass has the same name and type signature as method in superclass, then the method in the subclass is said to override the method in superclass. i.e. method version available in the superclass is hidden due to method overriding Helps in local customization of the required method in the super class
  • 34. Learning core JAVA – Inheritance Abstract classes • Classes created to present just the skeleton and let the subclass have the implementation • Forcing the definition of subclass to have certain functionality • To declare abstract method, use general form as abstract type method-name(para-list); • Any class having an abstract method should be declared as abstract • No objects of abstract classes can be instantiated • Subclass should implement all the abstract methods of superclass or it otherwise becomes abstract
  • 35. Learning core JAVA – Understanding final Understanding final specifier Can be applied to the member variables, methods and classes When applied to: Variables – prevent its content from modification (usage similar to const in c++) e.g. final int PI = 3.17; Methods – prevents superclass methods from being overridden in subclass Classes – prevents class from being inherited
  • 36. Learning core JAVA – Packages and Interfaces Package: Allows to group classes under namespace so that same name classes can be possible under different name spaces. This helps in overcoming the situation of running out convenient descriptive names for the classes Defining a package Include package command as the first statement in the file containing definition of various classes and all the classes in that file become part of the package e.g. package mypack; We can create hierarchy of packages also. e.g. package pkg1.pkg2.pkg3 Note: JAVA uses file system directory to store packages
  • 37. Learning core JAVA – Packages and Interfaces Importing packages • Usually java libraries are given in the form of packages. • The package has to be first imported in the program and then only the classes defined in the it can be used. e.g. import pkg1[.pkg2].[classname|*]; Note: Package cannot be renamed until the directory containing the package is renamed.
  • 38. Learning core JAVA – Packages and Interfaces Interface: • This can be used to specify what class must do but not how it does. • They are similar to classes but lack instance variables and also methods are declared without body. • Once defined, any number of classes can implement the interface • Multiple interfaces can be implemented by one class • Partial implementation of the interface by the class make it an abstract class
  • 39. Learning core JAVA – Packages and Interfaces Defining an interface access interface name { return-type method-name1(para-list); return-type method-name2(para-list); return-type method-name3(para-list); final type var1; final type var2; } access – can be either public or not used Implementing an interface class classname [extends superCls] implements interface1, interface2 ….. { }
  • 40. Learning core JAVA – Packages and Interfaces Extending an interface Interfaces can be extended by other interface as interface B extends A { void method1(); } Now the class implementing interface B has to implement methods of both the interfaces otherwise it becomes an abstract class.
  • 41. Learning core JAVA – Exception Handling • Exceptions are the conditions which violates the rules of the java language or the constraints of the java execution environment. • Exception in java is an object which is created by the environment and thrown in the method that has caused the error. The method may choose to handle or pass on to the environment back. • All exception types are subclasses of the built in class called Throwable which has two branches of subclasses called Exception and Error. The Error exception cannot be caught and handled by the environment. • Exception handling is done by using five keywords: try, catch, throw, throws, finally
  • 42. Learning core JAVA – Exception Handling • try – catch - finally is used to enclose the code which may raise an exception and user is interested in handling the same. finally is the block of code which is executed irrespective of the exception case occurred or not. This can be used for clean up operation before returning from the exception condition. • throw – used to throw user definable exception e.g. throw throwableInstance • throws – method which is capable of throwing an exception but does not handle it, must specify this behaviour so that callers can take card if required. e.g. type methodName(para-list) throws exp_list { }
  • 43. Learning core JAVA – Multithreaded Programming Multithreaded program consists of two or more parts which run concurrently. Each part of the program is called thread and each thread defines a separate path of execution. Can be implemented in two ways: 1.Extending Thread class 2.Implementing Runnable interface Important methods available in Thread class: isAlive, join, run, sleep, start, stop, suspend, resume Getting handle to Main Thread: Whenever java program starts, main thread is executed and to get handle to that thread Thread t = Thread.currentThread();
  • 44. Learning core JAVA – Multithreaded Programming Implementing Runnable 1.Create class that implements Runnable interface Class needs to implement single method as public void run() Inside run, insert the code that has to be executed when the thread starts 2. Instantiate an object of the class that has implemented Runnable interface Thread(Runnable threadobj, String threadName) 3. After object is created, thread does not start automatically, so execute start() - this in turn calls run
  • 45. Learning core JAVA – Multithreaded Programming Extending Thread Class 1.Create class that extends Thread Class needs to override the ‘run’ method 2. Instantiate an object of the class 3. After object is created, thread does not start automatically, so execute start() - this in turn calls run
  • 46. Learning core JAVA – Multithreaded Programming Thread Priorities Thread when created start with normal priority. The priority scale in JAVA goes from 1 to 10 where thread having 10 gets maximum priority. setPriority(int level) and getPriority() methods can be used for changing the priority levels of the threads created Note: Thread class does’nt have the constructor which can be used to create thread with the desired priority
  • 47. Learning core JAVA – Multithreaded Programming InterThread Communication For multiple thread communication, a very simple mechanism is provided by java and which is part of Object class, wait(), notify() and notifyAll() methods These can be called only from synchronized methods wait() – tells the calling thread to give up monitor and go to sleep until some other thread enters the same monitor and calls notify() notify() – wakes up the first thread that called wait() on the same object notifyAll() – wakes up all the thread that called wait()
  • 48. I/O In JAVA I/O in java is stream oriented where stream is defined to be an logical entity that produces or consumes data. Streams behave in same manner irrespective of the physical type I/O in java is built on four abstract classes: InputStream and OutputStream – byte/binary oriented data transfer Reader and Writer – character oriented data transfer
  • 49. I/O In JAVA InputStream Methods: • int read() - returns -1 if error • int read(byte buffer[]) – return -1 if EOF • int available() – returns number of bytes available in the stream to be read • long skip(long numBytes) • void close()
  • 50. I/O In JAVA OutputStream Methods: • void write(int b) • void write(byte buffer[]) • void flush() – writes everything to stream and clears the buffer • void close()
  • 51. I/O In JAVA Handling Implicit data type DataInputStream and DataOutputStream classes – These are one layer higher and requires base Input and Output streams to work Constructors: DataOutputStream(OutputStream os) DataInputStream(InputStream is) Methods: For reading implicit data types using DataInputStream: readFloat(), readBoolean(), readInt(), readDouble(), … Similarly for writing using DataOutputStream: writeFloat(), writeBoolean(), writeInt(), writeDouble(), etc
  • 52. I/O In JAVA Binary File Handling FileInputStream and FileOutputStream classes – These classes can be used for raw file handling Constructors: FileInputStream(String filename) FileInputStream(File fileobj) FileOutputStream(String filename) FileOutputStream(File fileobj) FileOutputStream(String filename, boolean append) Once the object is created, these behave similar to InputStream/OutputStream classes
  • 53. I/O In JAVA PrintStream Class This class is provided to write the formatted output. It requires a raw output stream for working Constructor: PrintStream(OutputStream os) Methods: Along with all implicit data type writing methods, it has print and println methods also.
  • 54. I/O In JAVA Character Streams Reader Class (Methods): int read() – read next char or returns -1 on error int read(char buf[]) long skip(long numchar) void close() Writer Class (Methods): void write(int char) void write(char buf[]) void flush() void close()
  • 55. I/O In JAVA Character Based File Handling FileReader and FileWriter classes – These classes can be used for character based file handling Constructors: FileReader(String filename) FileReader(File fileobj) FileWriter(String filename) FileWriter(File fileobj) FileWriter(String filename, boolean append) Once the object is created, these behave similar to Reader/Writer classes
  • 56. I/O In JAVA PrintWriter Class This class is character oriented version of PrintStream class provided for formatted output. Constructor: PrintWriter(Writer wr) Methods: Along with all implicit data type writing methods, it has print and println methods also.
  • 57. I/O In JAVA Buffered I/O JAVA also supports Buffered I/O which can further help in improving performance Both the version of buffered I/O has been provided i.e. binary and character oriented BufferedInputStream(InputStream is) BufferedOutputStream(OutputStream os) BufferedReader(Reader r) BufferedWriter(Writer w) As seen, the classes require base I/O streams to work.
  • 58. I/O In JAVA Special class - File File class represents file/folder on file system which can further used for file management activities i.e. getting file attributes, deleting, renaming, listing, etc. Constructor: File(String filepath) File(String directory) File(String dirPath, String filename) Methods: isFile(), isDirectory(), exists(), renameTo(File newName), delete(), list(), getName(), getParent(), canWrite(), canRead(), lastModified(), length()
  • 59. I/O In JAVA Object I/O Special classes have been provided to have I/O based on JAVA objects ObjectInputStream(InputStream is) ObjectOutputStream(OutputStream os) Methods like readObject() and writeObject() have been provided to transfer/receive objects Note: Object which are serializable only can be transferred out of JVM to a stream
  • 60. I/O In JAVA Object I/O – What is Serializable object? Serialization is the process of the writing the state of the created object to a stream. This is useful if the state of the object is required in later time again or it is required to be transferred on the network. How to make Serializable object? The class of the object to be serialized has to implement the blank Serializable interface and JAVA takes care of preserving the context of the object and makes it ready to put out on the stream. class GoOut implements Serializable { // the definition of the class }
  • 61. Socket Programming Supporting Classes InetAddress: It encapsulates the IP address and the domain name of the system. No constructor available, an instance can be created by calling one of the following factory methods: getLocalHost() – get the details of the local host getByName(String hostname) – returns the said host details using DNS Methods those can be used for retrieving information: 1. String getHostName() 2. byte[] getAddress()
  • 62. Socket Programming Supporting Classes URL: Provides a way to identify resource on the Net. URL(String url) URL(String protocol, String hostname, String port, String path) Methods: getProtocol(), getPort(), getHost(), getFile(), openConnection() – creates URL Connection Object which can be further used for retrieving properties of the remote object or to have tunneling implemented
  • 63. Socket Programming Supporting Classes URLConnection: Class provided to access the properties of the remote object and to implement tunneling Methods: getDate(), getContentType(), getExpiration(), getLastModified(), getContentLength(), getInputStream() – can be used to have socket communication with web server
  • 64. Socket Programming TCP Client Socket Socket(String hostname, int port) Socket(InetAddress IP, int port) This creates socket and connects to the remote host at the time of object instantiation Methods: getPort() – returns remote port getLocalPort(), getInputStream(), getOutputStream(), close()
  • 65. Socket Programming TCP Server Socket ServerSocket(int port) ServerSocket(int port, int Queue) Used to create socket on the server which is further used for listening tcp connections Methods: Socket accept() - returns client socket which can be used for further communication
  • 66. Socket Programming Datagram Communication This is implemented using two classes: DatagramPacket – to send or receive the packet containing data DatagramSocket – contains host details for communication e.g. Receive Packet DatagramPacket(byte data[], int size) Send Packet DatagramPacket(byte data[], int size, InetAddress ip, int port)
  • 67. Socket Programming Datagram Communication – Contd… DatagramPacket Methods: byte[] getData() – retrieves data from the received packet int getLength() – returns size of the packet DatagramSocket – used to create UDP based socket Methods: send(DatagramPacket dp) receive(DatagramPacket dp)
  • 68. Abstract Windows Toolkit (AWT) Control Classes Hierarchy Component Container Window Panel Frame Applet General methods for handling Event, colour, font, etc Additional methods of adding And removing components Methods: add(Component) remove(Component) removeAll() Window without Menu and Titlebar All GUI Controls
  • 69. Abstract Windows Toolkit (AWT) GUI Controls 1.Labels 2.Push Button 3.CheckBoxes 4.ChoiceLists 5.Lists 6.Text Editing 1. Label Label(String str) Label(String str, int how) where how can be Label.LEFT, Label.RIGHT or Label.Center Caption can be changed using: void setText(String) String getText()
  • 70. Abstract Windows Toolkit (AWT) 2. Button Button(String) Changing the label on button: void setLabel(String) String getLabel() 3. Checkbox can be individual or in group like radio buttons Checkbox(String) Checkbox(String, boolean) Checkbox(String, CheckboxGroup, Boolean) for radio buttons Methods: getState(), setState(), getLabel(), setLabel() and getSelectedCheckbox() – for radio button
  • 71. Abstract Windows Toolkit (AWT) 4. Choice Control Empty constructor for creating object and then use add(String) for adding elements in the list Methods: getSelectedItem() – to get the string of the item getSelectedIndex() – index of the selected item getItemCount() void select(int) – for setting the selected item 5. List Control List(int nRows) – number of rows to display All methods of choice control apply.
  • 72. Abstract Windows Toolkit (AWT) 5. TextComponent Two sub classes exists of TextComponent for text editing i.e. TextField and TextArea TextField: TextField(), TextField(int nchar), TextField(String) TextField(String, int) Methods: getText(), setText(), setEchoChar(char) TextArea: TextArea(int nlines, int nchar) TextArea(String) TextArea(String, int nlines, int nchar)
  • 73. Abstract Windows Toolkit (AWT) – Layout Manager Layout Manager places component in appropriate place as defined in the algorithm All containers have some default layout manager defined and if required can be changed using setLayout(LayoutManager) method. if null is passed for setLayout() then each component has to be placed using setBounds() method Some of the supported Layout Manager Classes: 1.FlowLayout Default layout manager for Panel/Applet places components at flow of text FlowLayout() FlowLayout(int how) where how can be FlowLayout.LEFT/RIGHT/CENTER
  • 74. Abstract Windows Toolkit (AWT) – Layout Manager 2. BorderLayout Divides the total screen area in five sections as shown below: North South W e s t E a s t CENTER For adding components to appropriate regions, add(Component comp, int region) where region can be BorderLayout.CENTER/SOUTH/NORTH/EAST/WEST
  • 75. Abstract Windows Toolkit (AWT) – Layout Manager 3. GridLayout It lays out the components in a two dimensional grid. GridLayout(int nRows, int nCols) GridLayout() – Single col grid layout
  • 76. AWT – Event Handling Event handling in JAVA is done using Delegation Model where the interested object registers with the source to get the notification when particular event has occurred. The source passes an event object for appropriate event type to the listener class which has the methods implemented to handle the notification. Process: 1. Create a source 2. Register the listener for interested event method provided: addTypeListener(TypeListener) where Type specifies the type of event 3. Create listener class to handle the event implementing the methods i.e. to implement the required listener interface
  • 77. AWT – Event Handling Listener Interfaces 1. ActionListener - for handling action event Method: void actionPerformed(ActionEvent) 2. FocusListener – for handling focussing events methods: void focusGained(FocusEvent) void focusLost(FocusEvent) 3. KeyListener – for handling key events Methods: keyPressed(KeyEvent), keyReleased(KeyEvent), keyTyped(KeyEvent) The KeyEvent class has the methods to identify key, getKeyChar(), getKeyCode()
  • 78. AWT – Event Handling 4. MouseListener - for handling mouse related events Methods: void mouseClicked(MouseEvent) void mouseEntered(MouseEvent) void mouseExited(MouseEvent) void mousePressed(MouseEvent) void mouseReleased(MouseEvent) MouseEvent class has the methods to get the location, mouse key, etc like getX() and getY() – for getting the location of mouse pointer 5. TextListener – text editing events Method: textChanged(TextEvent)
  • 79. AWT – Event Handling 6. WindowListener - for handling windowing events void windowActivated(WindowEvent) void windowClosed(WindowEvent) void windowClosing(WindowEvent) and for Deactivated, Deiconified, Iconified and Opened 7. ItemListener – for handling the checbox and list control events Method: itemStateChanged(ItemEvent)
  • 80. AWT – Event Handling – Adapter Classes Adapter Classes Requirement ? Listener interfaces forcing to implement all the methods even if some of the events user is not interested in. Adapter classes have all the methods implemented with blank method code which helps the user to implement only the required methods. Available Adapter Classes: FocusAdapter, KeyAdapter, MouseAdapter, WindowAdapter, MouseMotionAdapter