java by Kamalakar Dandu
-
Upload
kamalakar-dandu -
Category
Documents
-
view
214 -
download
0
Transcript of java by Kamalakar Dandu
-
8/2/2019 java by Kamalakar Dandu
1/284
Core Java Ver 2.0 1 of 284CopyrightWipro Technologies Talent Transformation
Introduction To Java Programming
-
8/2/2019 java by Kamalakar Dandu
2/284
Core Java Ver 2.0 2 of 284CopyrightWipro Technologies Talent Transformation
Goals and Features
Aimed at new kind of devices and applications. Hand-held devices
Car computers
Internet kiosks, etc.
Increasingly used for middleware
Internet based applications
Not to be seen as general purpose programming
language.
-
8/2/2019 java by Kamalakar Dandu
3/284
Core Java Ver 2.0 3 of 284CopyrightWipro Technologies Talent Transformation
Buzzwords of Java
Simple
Small language [ large libraries ]
Small interpreter (40 k), but large runtime libraries
( 175 k). Object Oriented
Supports encapsulation, inheritance, abstraction, and
polymorphism.
Distributed
Libraries for network programming
Remote Method Invocation
-
8/2/2019 java by Kamalakar Dandu
4/284
Core Java Ver 2.0 4 of 284CopyrightWipro Technologies Talent Transformation
Buzzwords of Java
Secure
Difficult to break Java security mechanisms.
Java Bytecode verification.
Signed Applets. Architecture neutral
Java Bytecodes are interpreted by the JVM.
Portable
Primitive data type sizes and their arithmetic behavior
are specified by the language.
Libraries define portable interfaces.
-
8/2/2019 java by Kamalakar Dandu
5/284
Core Java Ver 2.0 5 of 284CopyrightWipro Technologies Talent Transformation
Buzzwords of Java
Multithreaded Threads are easy to create and use (perhaps easier than any
other programming language).
Dynamic Finding Runtime Type Information is easy.
-
8/2/2019 java by Kamalakar Dandu
6/284
Core Java Ver 2.0 6 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
7/284Core Java Ver 2.07 of 284CopyrightWipro Technologies Talent Transformation
The Architecture
Java's architecture arises out of four distinct butinterrelated technologies:
the Java programming language the Java class file format
the Java Application Programming Interface
the Java virtual machine
-
8/2/2019 java by Kamalakar Dandu
8/284Core Java Ver 2.0 8 of 284
CopyrightWipro Technologies Talent Transformation
Compile time environment Run time Environment
B.JavaC.Java
Java compiler
B.Class C.Class
A.Java B.class C.classA.class
JVM
Object.class String.class
A.Class
The Architecture
-
8/2/2019 java by Kamalakar Dandu
9/284Core Java Ver 2.0 9 of 284
CopyrightWipro Technologies Talent Transformation
The Java Virtual machine
A Java virtual machine's main job is to load classfiles and execute the byte codes they contain.
Only those class files from the Java API that areactually needed by a running program are loaded
into the virtual machine.
The byte codes are executed in an execution
engine, which is one part of the VM.
-
8/2/2019 java by Kamalakar Dandu
10/284Core Java Ver 2.0 10 of 284
CopyrightWipro Technologies Talent Transformation
The Java Virtual machine
Class loader
Execution engine
The Java APIclass filesYour program
class files
Byte codes
Basic block diagram of the Java virtual machine
-
8/2/2019 java by Kamalakar Dandu
11/284Core Java Ver 2.0 11 of 284
CopyrightWipro Technologies Talent Transformation
Class loader
Execution engine
The Java APIclass filesYour program
class files
Byte codes
Host operating system
Native method invocations
A Java virtual machine implemented in software on top of a
host operating system
-
8/2/2019 java by Kamalakar Dandu
12/284Core Java Ver 2.0 12 of 284
CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
13/284
Core Java Ver 2.0 13 of 284CopyrightWipro Technologies Talent Transformation
The Class Loader Architecture
One aspect of the Java VM that plays an importantrole in both the security and network mobility is the
class loader architecture.
A Java application can use two types of class loaders
: a bootstrap class loader and user-defined classloaders.
At runtime , a Java application can install class loader
objects that load classes in custom ways, such as bydownloading class files across network.
-
8/2/2019 java by Kamalakar Dandu
14/284
Core Java Ver 2.0 14 of 284CopyrightWipro Technologies Talent Transformation
The Class Loader Architecture
Because of class loader objects , you dont have toknow at compile time all the classes that may
ultimately take part in a running Java application.
They enable you to dynamically extend a Javaapplication at run time.You can download classes
across a network, get them out of some kind of
database or even calculate them on the fly.
-
8/2/2019 java by Kamalakar Dandu
15/284
Core Java Ver 2.0 15 of 284CopyrightWipro Technologies Talent Transformation
Classloader
Classloader
Classloader
Classloader
Objects on the heap
Bootstrap Class Loader
Part of the Java VM implementation
The Class Loader Architecture
-
8/2/2019 java by Kamalakar Dandu
16/284
Core Java Ver 2.0 16 of 284CopyrightWipro Technologies Talent Transformation
The Class Loader Architecture
For each Java VM loads, the Java VM keeps track
of which class loader- whether primordial or
object- loaded the class.
Because the Java VM takes this approach to
loading classes, classes by default, see only other
classes that were loaded by the same class loader.
This way Javas architecture enables you to createmultiple name spaces inside a Java application.
-
8/2/2019 java by Kamalakar Dandu
17/284
Core Java Ver 2.0 17 of 284CopyrightWipro Technologies Talent Transformation
The Class Loader Architecture
By allowing you to instantiate class loader objectsthat know how to download class files across a
network
Javas class loader architecture supports network
mobility. It supports security by allowing you to load class files
from different sources through different class loader
objects.
-
8/2/2019 java by Kamalakar Dandu
18/284
Core Java Ver 2.0 18 of 284CopyrightWipro Technologies Talent Transformation
The Java .class file
The Java class file helps make Java suitable fornetworks mainly in the areas of platform
independence and network mobility.
Its role in platform independence is serving as abinary form for Java programs that is expected by
the Java VM but independent of underlying host
platforms.
The Java class file is a binary file that can run onany hardware platform and OS that hosts the Java
VM.
-
8/2/2019 java by Kamalakar Dandu
19/284
Core Java Ver 2.0 19 of 284CopyrightWipro Technologies Talent Transformation
The Java .class file
A Java compiler translates the instruction of theJava source files into byte codes,the machine
language of the Java VM.
The Java class file plays a critical role in Javasarchitectural support for network mobility. First,
class files were designed to be compact, so they
can move quickly across a network.
Java programs are dynamically linked anddynamically extensible, class files can
downloaded as needed.
-
8/2/2019 java by Kamalakar Dandu
20/284
Core Java Ver 2.0 20 of 284CopyrightWipro Technologies Talent Transformation
The Java API
The Java API is a set of runtime libraries that giveyou a standard way to access the system resources
of a host computer.
When you run a Java program, the VM loads thethe Java API class files that are referred to by your
program class files.
The combination of all ,loaded class files and any
loaded DLL constitutes the full program executed
by the Java VM.
-
8/2/2019 java by Kamalakar Dandu
21/284
Core Java Ver 2.0 21 of 284CopyrightWipro Technologies Talent Transformation
The Java API
The Java API class files provide a Java programwith a standard , platform independent interface
to the underlying host. To the Java program, the
API looks the same and behaves predictably no
matter what platform happens to be underneath.
The internal design of the Java API is also geared
toward platform independence. For Example theGUI library of the Java API, AWT, is deigned to
facilitate the user interfaces that work on all
platforms.
-
8/2/2019 java by Kamalakar Dandu
22/284
Core Java Ver 2.0 22 of 284CopyrightWipro Technologies Talent Transformation
Java App.
Java methods (Java API)
Native methods (Dynamic Libraries)
Host Operating System
The Java API
-
8/2/2019 java by Kamalakar Dandu
23/284
Core Java Ver 2.0 23 of 284CopyrightWipro Technologies Talent Transformation
The Java Programming Language
The Java language allows you to write programs thattake advantage of many software technologies:
object-orientation
multi-threading
structured error-handling garbage collection
dynamic linking
dynamic extension
-
8/2/2019 java by Kamalakar Dandu
24/284
Core Java Ver 2.0 24 of 284CopyrightWipro Technologies Talent Transformation
Garbage Collection
Avoids
Memory leakage
Memory corruption
Increases
Productivity
-
8/2/2019 java by Kamalakar Dandu
25/284
Core Java Ver 2.0 25 of 284CopyrightWipro Technologies Talent Transformation
Summary
The Java language provides a powerful addition to thetools that programmers have at their disposal. Java
makes programming easier because it is object-oriented
and has automatic garbage collection. In addition,
because compiled Java code is architecture-neutral, Javaapplications are ideal for a diverse environment like the
Internet.
-
8/2/2019 java by Kamalakar Dandu
26/284
Core Java Ver 2.0 26 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
27/284
Core Java Ver 2.0 27 of 284
CopyrightWipro Technologies Talent Transformation
The Environment
Hello.java
javac Hello.java
Hello.class
Network
Runtime
Class Loader
Bytecode Verifier
Interpreter
Hardware
-
8/2/2019 java by Kamalakar Dandu
28/284
Core Java Ver 2.0 28 of 284
CopyrightWipro Technologies Talent Transformation
Sample Code
public class Hello {public static void main(String [] args) {
System.out.println(HelloWorld);
}
}
Compilation - javac Hello.java
Execution - java Hello
Hello.java
-
8/2/2019 java by Kamalakar Dandu
29/284
Core Java Ver 2.0 29 of 284
CopyrightWipro Technologies Talent Transformation
Language Basics
Keywords Variables
Conditional Statements
Loops
Data Types
Operators
Coding Conventions
-
8/2/2019 java by Kamalakar Dandu
30/284
Core Java Ver 2.0 30 of 284
CopyrightWipro Technologies Talent Transformation
Data Types
Integral Type
byte 8 bits
short 16 bits
int 32 bits long 64 bits
Textual Type
char 16 bits, UNICODE Character
String
-
8/2/2019 java by Kamalakar Dandu
31/284
Core Java Ver 2.0 31 of 284
CopyrightWipro Technologies Talent Transformation
Data Types
Floating Point Type float 32 bits
double 64 bits
Boolean Type true
false
-
8/2/2019 java by Kamalakar Dandu
32/284
Core Java Ver 2.0 32 of 284
CopyrightWipro Technologies Talent Transformation
Arrays
Upon the completion of this module, you shouldbe able to:
Declare and create arrays of primitive, class or array
types.
Explain why elements of an array are initialized.
Given an array definition, initialize the elements of an
array.
Create a multidimensional array.
Copy arrays
-
8/2/2019 java by Kamalakar Dandu
33/284
Core Java Ver 2.0 33 of 284
CopyrightWipro Technologies Talent Transformation
Declaring Arrays
Group data objects of the same type.
Declare arrays of primitive or class types.
char s[]; or char [] s; Point p[]; or Point [] p;
Create space for reference.
An array is an object, not memory reserved for
primitive types.
-
8/2/2019 java by Kamalakar Dandu
34/284
Core Java Ver 2.0 34 of 284
CopyrightWipro Technologies Talent Transformation
Creating Arrays
Use the new keyword to create an array object.
S = new char[20];
p = new Point[100];
p[0] = new Point();
p[1] = new Point();
.
.
.
-
8/2/2019 java by Kamalakar Dandu
35/284
Core Java Ver 2.0 35 of 284
CopyrightWipro Technologies Talent Transformation
Initializing Arrays
Initialize an array element Create an array with initial values
String names[] = new String[3];
names [0] = Jack;
names [1] = Jill;names [2] = Tom;
MyClass array [] = { new MyClass(), new MyClass() };
-
8/2/2019 java by Kamalakar Dandu
36/284
Core Java Ver 2.0 36 of 284
CopyrightWipro Technologies Talent Transformation
Multi-Dimensional Arrays
Arrays of arrays :
int twoDim [] [] = new int [4] [];
twoDim [0] = new int [5];
twoDim [1] = new int [5];
int twoDim [] [] = new int [] [5]; // illegeal
-
8/2/2019 java by Kamalakar Dandu
37/284
Core Java Ver 2.0 37 of 284
CopyrightWipro Technologies Talent Transformation
Multi-Dimensional Arrays
Non-Rectangular arrays of arraystwoDim [0] = new int[2];twoDim [1] = new int[2];
twoDim [2] = new int[2];
twoDim [3] = new int[2];
Array of four arrays of five integers each :int twoDim[] [] = new int [4] [5];
-
8/2/2019 java by Kamalakar Dandu
38/284
Core Java Ver 2.0 38 of 284
CopyrightWipro Technologies Talent Transformation
Array Bounds
All array subscripts begin with 0 :
int list [] = new int [10];
for (int i = 0; i< list.length; i++) {
System.out.println(list[i]);}
-
8/2/2019 java by Kamalakar Dandu
39/284
Core Java Ver 2.0 39 of 284
CopyrightWipro Technologies Talent Transformation
Array Resizing
Can not resize an array Can use the same reference variable to refer to an entirely
new array
int elements [] = new int [5];
elements = new int [10];
-
8/2/2019 java by Kamalakar Dandu
40/284
Core Java Ver 2.0 40 of 284
CopyrightWipro Technologies Talent Transformation
Copying Arrays
The System.arraycopy() method :// original array
int elements [] = {1, 2, 3, 4, 5, 6};
// new larger array
int hold [] = {10,9,8,7,6,5,4,3,2,1};
// copy all of the elements array to hold array starting// with the 0th. Index
System.arraycopy(elements,0,hold,0,elements.length);
-
8/2/2019 java by Kamalakar Dandu
41/284
Core Java Ver 2.0 41 of 284
CopyrightWipro Technologies Talent Transformation
Object Oriented Programming and
Java
-
8/2/2019 java by Kamalakar Dandu
42/284
Core Java Ver 2.0 42 of 284
CopyrightWipro Technologies Talent Transformation
Analysis and Design
Analysis describes whatthe system needs to do
Modeling the real-world: actors and activities, objects and
behaviors
Design describes how the system does it
Modeling the relationships and interactions between objects and
actors in the system
Finding useful abstractions to help simplify the problem orsolution
-
8/2/2019 java by Kamalakar Dandu
43/284
Core Java Ver 2.0 43 of 284
CopyrightWipro Technologies Talent Transformation
Abstraction
Functions - Write an algorithm once to be used in many
situations
Objects - Group a related set of attributes and behaviors
into a class
Frameworks and APIs - Large groups of objects that
support a complex activity
Frameworks can be used "as is" or be modified to
extend the basic behavior
-
8/2/2019 java by Kamalakar Dandu
44/284
Core Java Ver 2.0 44 of 284
CopyrightWipro Technologies Talent Transformation
Abstract Classes
A class that declares the existence of methods but not the
implementation, is called an abstract class.
You can declare a class as abstract by marking it with the
abstract keyword.
An abstract class can contain member variables and non-
abstract methods.
-
8/2/2019 java by Kamalakar Dandu
45/284
Core Java Ver 2.0 45 of 284CopyrightWipro Technologies Talent Transformation
Classes as Blueprints for Objects
In manufacturing, a blueprint is a description of a
device from which many physical devices are
constructed
In software, a class is a description of an object: A class describes the data that each object includes
A class describes the behaviors that each object exhibits
In Java, classes support three key features of OOP: encapsulation
inheritance
polymorphism
-
8/2/2019 java by Kamalakar Dandu
46/284
Core Java Ver 2.0 46 of 284CopyrightWipro Technologies Talent Transformation
Declaring Java Classes
Basic syntax of a Java class: ::=
class {
*
*
*}
Example:
public class Vehicle {
private double maxLoad;public void setMaxLoad(double value) {
maxLoad = value;
}
}
-
8/2/2019 java by Kamalakar Dandu
47/284
Core Java Ver 2.0 47 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
48/284
Core Java Ver 2.0 48 of 284CopyrightWipro Technologies Talent Transformation
Information Hiding
The Problem:
-
8/2/2019 java by Kamalakar Dandu
49/284
Core Java Ver 2.0 49 of 284CopyrightWipro Technologies Talent Transformation
Information Hiding
The Solution:
-
8/2/2019 java by Kamalakar Dandu
50/284
Core Java Ver 2.0 50 of 284CopyrightWipro Technologies Talent Transformation
Encapsulation
Hides the implementation details of a class
Forces the user to use an interface to access data
Makes the code more maintainable
-
8/2/2019 java by Kamalakar Dandu
51/284
Core Java Ver 2.0 51 of 284CopyrightWipro Technologies Talent Transformation
Declaring Constructors
Basic syntax of a constructor:
::=
(*) {
*
}
Examples:
public class Thing {
private int x;
public Thing() {
x = 47;}
public Thing(int new_x) {
x = new_x;
}
}
-
8/2/2019 java by Kamalakar Dandu
52/284
Core Java Ver 2.0 52 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
53/284
Core Java Ver 2.0 53 of 284CopyrightWipro Technologies Talent Transformation
The Default Constructor
There is always at least one constructor in every class
If the writer does not supply any constructors, the default
constructor will be present automatically
The default constructor takes no arguments
The default constructor has no body
Enables you to create object instances with
newXxx()without having to write a constructor
-
8/2/2019 java by Kamalakar Dandu
54/284
Core Java Ver 2.0 54 of 284CopyrightWipro Technologies Talent Transformation
Identifiers, Keywords, and Types
-
8/2/2019 java by Kamalakar Dandu
55/284
Core Java Ver 2.0 55 of 284CopyrightWipro Technologies Talent Transformation
Comments
Three permissible styles of comment in a Java
technology program are:
[1] // comment on one line
[2] /* comment on one
or more lines */
[3] /** documentation comment */
-
8/2/2019 java by Kamalakar Dandu
56/284
Core Java Ver 2.0 56 of 284CopyrightWipro Technologies Talent Transformation
Primitive Types
The Java programming language defines eight
primitive types:
Logical - boolean
Textual - char
Integral - byte, short, int, and long
Floating - double and float
-
8/2/2019 java by Kamalakar Dandu
57/284
Core Java Ver 2.0 57 of 284CopyrightWipro Technologies Talent Transformation
Logical - boolean
The boolean data type has two literals, true and
false.
For example, the statement:
boolean truth = true;
declares the variable truth as boolean type and
assigns it a value of true.
-
8/2/2019 java by Kamalakar Dandu
58/284
Core Java Ver 2.0 58 of 284CopyrightWipro Technologies Talent Transformation
Textual - char and String
char
Represents a 16-bit Unicode character
Must have its literal enclosed in single quotes(' ')
Uses the following notations:
'a' The letter a
\t' A tab character
\u????' A specific Unicode character, ????, is replaced withexactly four hexadecimal digits (for example, '\u03A6' is the Greek
letter phi)
-
8/2/2019 java by Kamalakar Dandu
59/284
Core Java Ver 2.0 59 of 284CopyrightWipro Technologies Talent Transformation
Textual - char and String
String
Is not a primitive data type; it is a class
Has its literal enclosed in double quotes (" ")
"The quick brown fox jumps over the lazy dog."
Can be used as follows:
String greeting = "Good Morning !! \n";
String errorMessage = "Record Not Found !";
-
8/2/2019 java by Kamalakar Dandu
60/284
Core Java Ver 2.0 60 of 284CopyrightWipro Technologies Talent Transformation
Integral - byte, short, int, and long
Uses three forms - Decimal, octal, or hexadecimal
2 The decimal value is two
077 The leading zero indicates an octalvalue
0xBAAC The leading 0x indicates a hexadecimal
value
Has a default int
Defines long by using the letter L or l
-
8/2/2019 java by Kamalakar Dandu
61/284
Core Java Ver 2.0 61 of 284CopyrightWipro Technologies Talent Transformation
Integral - byte, short, int, and long
Integral data types have the following ranges :
Name / Type Length Range
byte
int
short
long
8 bits
16 bits
32 bits
64 bits
-27 to 27-1
-215 to 215 -1
-231 to 231 -1
-263 to 263 -1
-
8/2/2019 java by Kamalakar Dandu
62/284
Core Java Ver 2.0 62 of 284CopyrightWipro Technologies Talent Transformation
Floating Point - float and double
Default is double
Floating point literal includes either a decimal
point or one of the following:
E or e (add exponential value) F or f (float)
D or d (double)
3.14 A simple floating-point value (a double)
6.02E23 A large floating-point value
2.718F A simple float size value
123.4E+306D A large double value with redundant
-
8/2/2019 java by Kamalakar Dandu
63/284
Core Java Ver 2.0 63 of 284CopyrightWipro Technologies Talent Transformation
Java Reference Types
Beyond primitive types all others are reference types A reference variable contains a "handle" to an object
Example:
1 public class MyDate {2 private int day = 1;
3 private int month = 1;
4 private int year = 2000;
5 }
1 public class TestMyDate {
2 public static void main(String[] args) {
3 MyDate today = new MyDate();
4 }
5 }
-
8/2/2019 java by Kamalakar Dandu
64/284
Core Java Ver 2.0 64 of 284CopyrightWipro Technologies Talent Transformation
Constructing and Initializing Objects
Calling new Xxx() to allocate space for the newobject results in:
Memory Allocation: Space for the new object is
allocated and instance variables are initialized to their
default values (e.g. 0, false, null, and so on)
Explicit attribute initialization is performed
A constructor is executed
Variable assignment is made to reference the object
Example:
Date today = new Date(06, 06, 1975);
-
8/2/2019 java by Kamalakar Dandu
65/284
Core Java Ver 2.0 65 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
66/284
Core Java Ver 2.0 66 of 284CopyrightWipro Technologies Talent Transformation
7
7
0x01234
0x01234
x
y
s
t
Hello
Assignment of reference variables
int x = 7;
int y = x;
String s = Hello;
String t = s;
-
8/2/2019 java by Kamalakar Dandu
67/284
Core Java Ver 2.0 67 of 284
Copyright
Wipro Technologies Talent Transformation
Pass-by-Value
The Java programming language only passesarguments by value
When an object instance is passed as an argumentto a method, the value of the argument is a
reference to the object
The contents of the object can be changed in the
called method, but the object reference is never
changed
Pass-by-Value
-
8/2/2019 java by Kamalakar Dandu
68/284
Core Java Ver 2.0 68 of 284
Copyright
Wipro Technologies Talent Transformation
public class Test { // set the ptValue
float classVar; t. classVar = 101f;
public static void main(String [] args) { // change the float value through obj. reference
String str; t.changeObjVal(t);
int localVal; // print the current value
// create an instance of the class System.out.println(t.tValue);
Test t = new Test(); }
// assign the int value
localVal = 11; // Methods to change the current values// try to change it
t.changeInt(localVal); public void changeInt(int val) {
// get the current value val = 50;
System.out.println(Int value is : + localVal); }
Pass by Value
-
8/2/2019 java by Kamalakar Dandu
69/284
Core Java Ver 2.0 69 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
70/284
Core Java Ver 2.0 70 of 284
Copyright
Wipro Technologies Talent Transformation
The this Reference
Refers to the object on which the method operates.
Can be used to pass the current object as
reference.
In a constructor the this keyword takes on a
different meaning when you give it an argument
list :
it makes an explicit call to the constructor that matchesthat argument list.
-
8/2/2019 java by Kamalakar Dandu
71/284
Core Java Ver 2.0 71 of 284
Copyright
Wipro Technologies Talent Transformation
Inheritance and Advanced class
Features
The is a Relationship
-
8/2/2019 java by Kamalakar Dandu
72/284
Core Java Ver 2.0 72 of 284
Copyright
Wipro Technologies Talent Transformation
The is a Relationship
The Employee class:
The is a Relationship
-
8/2/2019 java by Kamalakar Dandu
73/284
Core Java Ver 2.0 73 of 284
Copyright
Wipro Technologies Talent Transformation
The is a Relationship
The Manager class:
The is a Relationship
-
8/2/2019 java by Kamalakar Dandu
74/284
Core Java Ver 2.0 74 of 284
Copyright
Wipro Technologies Talent Transformation
The is a Relationship
The is a Relationship :
Single Inheritance
-
8/2/2019 java by Kamalakar Dandu
75/284
Core Java Ver 2.0 75 of 284
Copyright
Wipro Technologies Talent Transformation
Single Inheritance
When a class inherits from only one class, it iscalled single inheritance.
Single inheritance makes code more reliable.
Interfaces provide the benefits of multipleinheritance without drawbacks.
Syntax of a Java class:
:: =
class [extends superclass] {*
}
-
8/2/2019 java by Kamalakar Dandu
76/284
Core Java Ver 2.0 76 of 284
Copyright
Wipro Technologies Talent Transformation
Constructors Are Not Inherited
-
8/2/2019 java by Kamalakar Dandu
77/284
Core Java Ver 2.0 77 of 284
Copyright
Wipro Technologies Talent Transformation
Constructors Are Not Inherited
A subclass inherits all methods and variablesfrom the superclass (parent class)
A subclass does not inherit the constructor
from the superclass Two ways to include a constructor are:
Use the default constructor
Write one or more explicit constructors
Polymorphism
-
8/2/2019 java by Kamalakar Dandu
78/284
Core Java Ver 2.0 78 of 284
Copyright
Wipro Technologies Talent Transformation
Polymorphism
Polymorphism is the ability to have many different forms;
for example, the Manager class has access to methods from
Employee class
An object has only one form
A reference variable can refer to objects of different forms
Polymorphism
-
8/2/2019 java by Kamalakar Dandu
79/284
Core Java Ver 2.0 79 of 284
Copyright
Wipro Technologies Talent Transformation
Polymorphism
Employee employee = new Manager() // legal
// Illegal attempt to assign Manager attributeemployee. department = "Sales";
// the variable is declared as a Employee type,// even though the Manager object has that attribute
Heterogeneous Collections
-
8/2/2019 java by Kamalakar Dandu
80/284
Core Java Ver 2.0 80 of 284
Copyright
Wipro Technologies Talent Transformation
Heterogeneous Collections
Collections of objects with the same class type arecalled homogenous collections. MyDate[] dates = new MyDate[ 2];
dates[ 0] = new MyDate( 22, 12, 1964);
dates[ 1] = new MyDate( 22, 7, 1964);
Collections of objects with different class types
are called heterogeneous collections. Employee [] staff = new Employee[ 1024];
staff[ 0] = new Manager();
staff[ 1] = new Employee();
staff[ 2] = new Engineer();
The instanceof Operator
-
8/2/2019 java by Kamalakar Dandu
81/284
Core Java Ver 2.0 81 of 284
Copyright
Wipro Technologies Talent Transformation
The instanceof Operator
public class Employee extends Objectpublic class Manager extends Employee
public class Engineer extends Employee
-------------------------------------------------
public void doSomething( Employee e) {
if (e instanceof Manager) {
// Process a Manager
} else if (e instanceof Engineer) {
// Process an Engineer
} else {
// Process any other type of Employee
}
}
Casting Objects
-
8/2/2019 java by Kamalakar Dandu
82/284
Core Java Ver 2.0 82 of 284
Copyright
Wipro Technologies Talent Transformation
Casting Objects
Use instanceof to test the type of an object
Restore full functionality of an object by casting
Check for proper casting using the following
guidelines: Casts up hierarchy are done implicitly
Downward casts must be to a subclass and checked by
the compiler
The object type is checked at runtime when runtime
errors can occur
Overriding Methods
-
8/2/2019 java by Kamalakar Dandu
83/284
Core Java Ver 2.0 83 of 284
Copyright
Wipro Technologies Talent Transformation
Overriding Methods
A subclass can modify behavior inheritedfrom a parent class
A subclass can create a method with differentfunctionality than the parents method butwith the same:
Name
Return type
Argument list
-
8/2/2019 java by Kamalakar Dandu
84/284
Core Java Ver 2.0 84 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
85/284
Core Java Ver 2.0 85 of 284
Copyright
Wipro Technologies Talent Transformation
Overriding Methods
Virtual method invocation: Employee e = new Manager();
e. getDetails();
Static and Dynamic
Rules About Overridden Methods
-
8/2/2019 java by Kamalakar Dandu
86/284
Core Java Ver 2.0 86 of 284
Copyright
Wipro Technologies Talent Transformation
Rules About Overridden Methods
Must have a return type that is identical to the methodit overrides.
Cannot be less accessible than the method it
overrides.
Cannot throw more exceptions than the method it
overrides.
-
8/2/2019 java by Kamalakar Dandu
87/284
Core Java Ver 2.0 87 of 284
Copyright
Wipro Technologies Talent Transformation
The super Keyword
-
8/2/2019 java by Kamalakar Dandu
88/284
Core Java Ver 2.0 88 of 284
Copyright
Wipro Technologies Talent Transformation
The super Keyword
super is used in a class to refer to its superclass
super is used to refer to the members of superclass, both
data attributes and methods
Behavior invoked does not have to be in the superclass; it
can be further up in the hierarchy
-
8/2/2019 java by Kamalakar Dandu
89/284
Core Java Ver 2.0 89 of 284
Copyright
Wipro Technologies Talent Transformation
Invoking Parent Class Constructors
-
8/2/2019 java by Kamalakar Dandu
90/284
Core Java Ver 2.0 90 of 284
Copyright
Wipro Technologies Talent Transformation
Invoking Parent Class Constructors
To invoke a parent constructor you must place a call tosuper in the first line of the constructor
You can call a specific parent constructor by the arguments
that you use in the call to super
If no this or super call is used in a constructor, then thecompiler adds an implicit call to super() which calls the
parent "default" constructor
If the parent class does not supply a non- private
"default" constructor, then a compiler warning will beissued
-
8/2/2019 java by Kamalakar Dandu
91/284
Core Java Ver 2.0 91 of 284
Copyright
Wipro Technologies Talent Transformation
Overloading Method Names
-
8/2/2019 java by Kamalakar Dandu
92/284
Core Java Ver 2.0 92 of 284
Copyright
Wipro Technologies Talent Transformation
g
It can be used as follows:
public void println( int i)
public void println( float f)
public void println( String s)
Argument lists mustdiffer
Return types canbe different
Overloading Constructors
-
8/2/2019 java by Kamalakar Dandu
93/284
Core Java Ver 2.0 93 of 284
Copyright
Wipro Technologies Talent Transformation
g
As with methods, constructors can beoverloaded
Example:
public Employee( String name, double salary, Date DoB) public Employee( String name, double salary)
public Employee( String name, Date DoB)
Argument lists mustdiffer
The this reference can be used at the first line of a
constructor to call another constructor
Constructing and InitializingObjects ASlight Reprise
-
8/2/2019 java by Kamalakar Dandu
94/284
Core Java Ver 2.0 94 of 284
Copyright
Wipro Technologies Talent Transformation
Objects:ASlight Reprise
Memory is allocated and default initialization occurs
Instance variable initialization uses these steps recursively:
1 Bind constructor parameters.
2 If explicit this(), call recursively and then skip to step 5.
3 Call recursively the implicit or explicit super call, except
for Object .
4 Execute explicit instance variable initializers.
5 Execute body of current constructor.
An Example
-
8/2/2019 java by Kamalakar Dandu
95/284
Core Java Ver 2.0 95 of 284
Copyright
Wipro Technologies Talent Transformation
public class Employee extends Object {
private String name;
private double salary = 15000.00;private Date birthDate;
public Employee(String n, Date DoB) {
// implicit super();
name = n;
birthDate = DoB;
}
public Employee(String n) {
this(n, null);
}
}
public class Manager extends Employee {
private String department;
public Manager(String n, String d) {
super(n);
department = d;
}
}
-
8/2/2019 java by Kamalakar Dandu
96/284
Core Java Ver 2.0 96 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
97/284
Core Java Ver 2.0 97 of 284
Copyright
Wipro Technologies Talent Transformation
The Object Class
-
8/2/2019 java by Kamalakar Dandu
98/284
Core Java Ver 2.0 98 of 284
Copyright
Wipro Technologies Talent Transformation
j
The Object class is the root of all classes in Java
A class declaration with no extends clause,
implicitly uses "extends Object"
public class Employee {...
}
is equivalent to:
public class Employee extends Object {
...
}
Wrapper Classes
-
8/2/2019 java by Kamalakar Dandu
99/284
Core Java Ver 2.0 99 of 284
Copyright
Wipro Technologies Talent Transformation
pp
Look at primitive data elements as objects
Primitive Data Type Wrapper Class
boolean Boolean
byte Byte
char Character
short Short
int Integer
long Longfloat Float
double Double
Access specifiers and modifiers
-
8/2/2019 java by Kamalakar Dandu
100/284
Core Java Ver 2.0 100 of 284
Copyright
Wipro Technologies Talent Transformation
p
private
can be accessed only within the declaring class
protected
can be accessed in the declaring class as well as derived class
default
package scope
public
global scope
Access specifiers and modifiers
-
8/2/2019 java by Kamalakar Dandu
101/284
Core Java Ver 2.0 101 of 284
Copyright
Wipro Technologies Talent Transformation
static
only one copy exists for the entire class.
static methods and blocks may access only static data members.
static methods and blocks can call only static methods.
static methods do not have access to this reference.
Access specifiers and modifiers
-
8/2/2019 java by Kamalakar Dandu
102/284
Core Java Ver 2.0 102 of 284
Copyright
Wipro Technologies Talent Transformation
final
variables must be initialized and can not change their
value.
methods can not be overridden.
arguments can only be read, their value can not be
changed.
classes can not be inherited.
transient
can not be serialized.
Access specifiers and modifiers
-
8/2/2019 java by Kamalakar Dandu
103/284
Core Java Ver 2.0 103 of 284
Copyright
Wipro Technologies Talent Transformation
synchronized A single thread of execution exists for a synchronized
method or block.
Used to obtain the lock for an object.
native
If a method has been declared using the native keyword
in a java source file, it means that the method definition
will be appearing in some external library.
volatile
Optimization not done by the compiler.
-
8/2/2019 java by Kamalakar Dandu
104/284
Core Java Ver 2.0 104 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
105/284
Core Java Ver 2.0 105 of 284
Copyright
Wipro Technologies Talent Transformation
Packages
-
8/2/2019 java by Kamalakar Dandu
106/284
Core Java Ver 2.0 106 of 284
Copyright
Wipro Technologies Talent Transformation
Packages are containers, used to keep the class namespace
compartmentalized.
The Package declaration, if any, must be at the beginning of the
source file and can be preceded only by whitespaces and
comments.
package MyPack;
public class SomeClass {// class body
}
SomeClass.java
Packages
-
8/2/2019 java by Kamalakar Dandu
107/284
Core Java Ver 2.0 107 of 284
Copyright
Wipro Technologies Talent Transformation
Packages
Only one package declaration is permitted and it governs theentire source file.
Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.
The CLASSPATH variable controls the specific location that
the Java compiler looks for as the root of any package.
The import statement is used to bring classes in other
packages into the current namespace.
Creating Packages
-
8/2/2019 java by Kamalakar Dandu
108/284
Core Java Ver 2.0 108 of 284
Copyright
Wipro Technologies Talent Transformation
package MyPack;
public class Balance {String name;
double bal;
public Balance( String n, double b ) {
name = n;
bal = b;
}
public void show( ) {
if ( bal < 0 )
System.out.println ( "----> );
System.out.println ( name + " : $ " + bal );
}
}
Accessing Packages
-
8/2/2019 java by Kamalakar Dandu
109/284
Core Java Ver 2.0 109 of 284
Copyright
Wipro Technologies Talent Transformation
import MyPack.*;
public class AccountBalance {
public static void main(String [] args) {
Balance current[] = new Balance[3];
current[0] = new Balance(Tom",12.12);
current[1] = new Balance("Mary",22.12);
current[2] = new Balance("Jack",32.12);
for ( int i = 0;i < 3;i++ )
current[i].show();
}
}
Interfaces
-
8/2/2019 java by Kamalakar Dandu
110/284
Core Java Ver 2.0 110 of 284
Copyright
Wipro Technologies Talent Transformation
Allow to fully abstract a classes interface from its
implementation.
Pure abstract classes with no implementation of any method.
Only methods and constant declarations are allowed withinan interface ( static final by default).
Classes implement interfaces.
Once defined any number of classes can implement an
interface.
Defining an Interface
-
8/2/2019 java by Kamalakar Dandu
111/284
Core Java Ver 2.0 111 of 284
Copyright
Wipro Technologies Talent Transformation
accessinterfacename {
return-type method-name1(argument list);
..
return-type method-nameN(argument list);
type final-varname1 = value;
type final-varname2 = value;
type final-varnameN = value;}
Defining an Interface
-
8/2/2019 java by Kamalakar Dandu
112/284
Core Java Ver 2.0 112 of 284
Copyright
Wipro Technologies Talent Transformation
access is either public or not used, the default access haspackage scope.
methods are essentially abstract methods.
Variables are final and static and can not be changed by the
implementing classes.
All methods and variables are implicitly public if theinterface itself is declared as public.
The Cloneable Interface
-
8/2/2019 java by Kamalakar Dandu
113/284
Core Java Ver 2.0 113 of 284
Copyright
Wipro Technologies Talent Transformation
e C o eab e te ace
Class Day implements Cloneable{
}
Day bDay = new Day(1999,6,16);
Day d = bDay;
d.advance(100);
Day bDay = new Day(1999,6,16);
Day d = (Day)bDay.clone();
d.advance(100);
-
8/2/2019 java by Kamalakar Dandu
114/284
Core Java Ver 2.0 114 of 284
Copyright
Wipro Technologies Talent Transformation
Exception Handling
-
8/2/2019 java by Kamalakar Dandu
115/284
Core Java Ver 2.0 115 of 284
Copyright
Wipro Technologies Talent Transformation
User Input Error
Device Error
Physical Limitation
Code Errors
Exception Handling
-
8/2/2019 java by Kamalakar Dandu
116/284
Core Java Ver 2.0 116 of 284
Copyright
Wipro Technologies Talent Transformation
p g
java.lang.Object
java.lang.Throwable
java.lang.Exceptionjava.lang.Error
java.lang.RuntimeExceptionjava.lang.IOException
Exception Handling
-
8/2/2019 java by Kamalakar Dandu
117/284
Core Java Ver 2.0 117 of 284
Copyright
Wipro Technologies Talent Transformation
Exception Handling
Error
Indicates a severe problem from which recovery is
difficult, if not impossible eg. running out of memory.
RuntimeException
Indicates a design or implementation error.
Exception Handling
-
8/2/2019 java by Kamalakar Dandu
118/284
Core Java Ver 2.0 118 of 284
Copyright
Wipro Technologies Talent Transformation
Exception Handling
Exceptions that inherit from RuntimeException :
A bad cast
An out-of-bound array access
A null pointer access
Exceptions that do not inherit from RuntimeException :
Trying to read past the end of file
Trying to open a malformed URL
Checked Exceptions
-
8/2/2019 java by Kamalakar Dandu
119/284
Core Java Ver 2.0119 of 284
Copyright
Wipro Technologies Talent Transformation
ClassNotFoundException Class not found
InstantiationException Attempt to create an object ofan abstract class or interface.
IllegealAccessException Access to a class is denied.
NoSuchMethodException A requested method does not
exsist.
NoSuchFieldException A requested field does not
exsist.
InterruptedException One thread has been interrupted
by another thread.
CloneNotSupportedException Attempt to clone an object that
does not implement Cloneable
interface.
Unchecked Exceptions
-
8/2/2019 java by Kamalakar Dandu
120/284
Core Java Ver 2.0120 of 284
Copyright
Wipro Technologies Talent Transformation
p
ArithmeticException Arithmetic error, such as
divide by zero.
NegativeArraySizeException Array created with a negative
size.
NullPointerException Invalid use of a null
reference.
IllegealArgumentException Illegeal argument used toinvoke a method.
ClassCastException Invalid class cast
The Throwable Class
-
8/2/2019 java by Kamalakar Dandu
121/284
Core Java Ver 2.0121 of 284
Copyright
Wipro Technologies Talent Transformation
Throwable fiilInStackTrace() Returns a Throwable object
containing a complete stack
trace.
void printStackTrace() Displays the stack trace.
String toString() Returns a String object
containing a description of the
exception, called by println().
String getMessage() Returns a description of theexception.
Exception Handling
-
8/2/2019 java by Kamalakar Dandu
122/284
Core Java Ver 2.0122 of 284
Copyright
Wipro Technologies Talent Transformation
public class Demo {
public static void main(String [] args) {
int i = 0;
String greetings [] = { Hello,Hi,Bye };
while ( i < 4 ) {
System.out.println(greetings[i]);
i++;
}}
}
Exception Handling
-
8/2/2019 java by Kamalakar Dandu
123/284
Core Java Ver 2.0123 of 284
Copyright
Wipro Technologies Talent Transformation
tryuse the try statement with the code that might throw an
exception.
catch
use the catch statement to specify the exception to catch andthe code to execute if the specified exception is thrown.
finally
used to define a block of code that we always want to execute,
regardless of whether an exception was caught or not.
Exception Handling
-
8/2/2019 java by Kamalakar Dandu
124/284
Core Java Ver 2.0124 of 284
Copyright
Wipro Technologies Talent Transformation
throw
typically used for throwing user defined exceptions.
throws
lists the types of exceptions a method can throw, so that the callers
of the method can guard themselves against the exception.
try and catch
bli l D {
-
8/2/2019 java by Kamalakar Dandu
125/284
Core Java Ver 2.0125 of 284
Copyright
Wipro Technologies Talent Transformation
public class Demo {
public static void main(String [] args) {
int x,y;try {
x = 0;
y = 10/x;
System.out.println(Now What ???);
}
catch(ArithmeticException e) {
System.out.println(Division by zero);
}
System.out.println(Hi I am back!!!);
}
}
-
8/2/2019 java by Kamalakar Dandu
126/284
Core Java Ver 2.0126 of 284
Copyright
Wipro Technologies Talent Transformation
Nested try
public class Demo { catch(ArithmeticException e) {
-
8/2/2019 java by Kamalakar Dandu
127/284
Core Java Ver 2.0127 of 284
Copyright
Wipro Technologies Talent Transformation
public class Demo { catch(ArithmeticException e) {
public static void main(String [] args){ System.out.println(Div by 0);
try{ }//catch
int a = args.length; }//main
int b = 10/a; }//Demo
try{
if ( a == 1)
a = a/(a-a);
if ( a == 2 ) {int c [] = { 1 };
c[10] = 100;
}//if
}//try
catch( ArrayIndexOutOfBoundsException e){
System.out.println(Out ofBounds);
}//catch }//try
The Throws Clausepublic class Demo {
public static void main(String [] args) {finally {
-
8/2/2019 java by Kamalakar Dandu
128/284
Core Java Ver 2.0128 of 284
Copyright
Wipro Technologies Talent Transformation
try { fun1(); }
catch(Exception e) {
System.out.println(In Main);
}
fun2();
}//mainpublic static fun1() throws Exception {
try {
System.out.println(Try of fun1);
throw new Exception();}
catch(Exception e) {
System.out.println(Catch of fun 1);
}
finally {
System.out.println(Finally of
fun 1);}
}// fun 1
public static fun 2() {
System.out.println(Hello);
}// fun 2
}// Demo
-
8/2/2019 java by Kamalakar Dandu
129/284
Core Java Ver 2.0129 of 284
Copyright
Wipro Technologies Talent Transformation
Streams
-
8/2/2019 java by Kamalakar Dandu
130/284
Core Java Ver 2.0130 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
131/284
Core Java Ver 2.0131 of 284
Copyright
Wipro Technologies Talent Transformation
Byte Streams
-
8/2/2019 java by Kamalakar Dandu
132/284
Core Java Ver 2.0132 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
133/284
Core Java Ver 2.0133 of 284
Copyright
Wipro Technologies Talent Transformation
Character Streams
-
8/2/2019 java by Kamalakar Dandu
134/284
Core Java Ver 2.0134 of 284
Copyright
Wipro Technologies Talent Transformation
Character Streams
-
8/2/2019 java by Kamalakar Dandu
135/284
Core Java Ver 2.0135 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
136/284
Core Java Ver 2.0136 of 284
Copyright
Wipro Technologies Talent Transformation
Streams
-
8/2/2019 java by Kamalakar Dandu
137/284
Core Java Ver 2.0137 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
138/284
Core Java Ver 2.0138 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
139/284
Core Java Ver 2.0139 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
140/284
Core Java Ver 2.0140 of 284
Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
141/284
Core Java Ver 2.0
141 of 284Copyright
Wipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
142/284
Core Java Ver 2.0
142 of 284Copyright
Wipro Technologies Talent Transformation
Using FileReader and FileWriter
-
8/2/2019 java by Kamalakar Dandu
143/284
Core Java Ver 2.0
143 of 284Copyright
Wipro Technologies Talent Transformation
import java.io.*;
public class Copy {public static void main(String[] args) throws IOException {
File inputFile = new File(Source.txt");
File outputFile = new File(Target.txt");
FileReader in = new FileReader(inputFile);
FileWriter out = new FileWriter(outputFile);int c;
while ((c = in.read()) != -1)
out.write(c);
in.close();`
out.close();
}
}
File Concatenation
import java io *;
-
8/2/2019 java by Kamalakar Dandu
144/284
Core Java Ver 2.0
144 of 284Copyright
Wipro Technologies Talent Transformation
import java.io. ;
public class Concatenate {
public static void main(String[] args) throws IOException {
ListOfFiles mylist = new ListOfFiles(args);
SequenceInputStream s = new SequenceInputStream(mylist);
int c;while ((c = s.read()) != -1)
System.out.write(c);
s.close();
}
}
File Concatenationimport java.util.*;
i t j i *
-
8/2/2019 java by Kamalakar Dandu
145/284
Core Java Ver 2.0
145 of 284Copyright
Wipro Technologies Talent Transformation
import java.io.*;
public class ListOfFiles implements Enumeration {
private String[] listOfFiles;
private int current = 0;
public ListOfFiles(String[] listOfFiles) {
this.listOfFiles = listOfFiles;
}
public boolean hasMoreElements() {
if (current < listOfFiles.length)
return true;
else
return false;
}
File Concatenationpublic Object nextElement() {
-
8/2/2019 java by Kamalakar Dandu
146/284
Core Java Ver 2.0
146 of 284Copyright
Wipro Technologies Talent Transformation
InputStream in = null;
if (!hasMoreElements())
throw new NoSuchElementException("No more files.");
else {
String nextElement = listOfFiles[current];
current++;
try {
in = new FileInputStream(nextElement);
} catch (FileNotFoundException e) {
System.err.println("ListOfFiles: Can't open " + nextElement);
}
}
return in;
}
}
Serializing Objects
-
8/2/2019 java by Kamalakar Dandu
147/284
Core Java Ver 2.0
147 of 284Copyright
Wipro Technologies Talent Transformation
How to Write to an ObjectOutputStream
Writing objects to a stream is a straight-forward
process. For example, the following gets the current
time in milliseconds by constructing a Date object and
then serializes that object:
FileOutputStream out = new FileOutputStream("theTime");
ObjectOutputStream s = new ObjectOutputStream(out);
s.writeObject("Today");
s.writeObject(new Date());
s.flush();
Serializing Objects
-
8/2/2019 java by Kamalakar Dandu
148/284
Core Java Ver 2.0
148 of 284Copyright
Wipro Technologies Talent Transformation
How to Read from an ObjectOutputStream Once you've written objects and primitive data types to
a stream, you'll likely want to read them out again and
reconstruct the objects.
FileInputStream in = new FileInputStream("theTime");ObjectInputStream s = new ObjectInputStream(in);
String today = (String)s.readObject();
Date date = (Date)s.readObject();
-
8/2/2019 java by Kamalakar Dandu
149/284
Core Java Ver 2.0
149 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
150/284
Core Java Ver 2.0
150 of 284CopyrightWipro Technologies Talent Transformation
Object Serialization File Format
-
8/2/2019 java by Kamalakar Dandu
151/284
Core Java Ver 2.0
151 of 284CopyrightWipro Technologies Talent Transformation
Following is the file format for ObjectSerialization Process :
Every file begins with a 2 byte magicnumber.
This is followed by the version number of the object
serialization format. Followed by a sequence of objects, in the order that
they were saved.
When the object gets serialized, the class of the object
is saved as well.
Obtaining The Fingerprint
-
8/2/2019 java by Kamalakar Dandu
152/284
Core Java Ver 2.0
152 of 284CopyrightWipro Technologies Talent Transformation
Java Runtime Environment gets the fingerprint by : Ordering descriptions of the class, superclass, interfaces,field types and method signatures.
Applying the Secure Hash Algorithm to that data.
The fingerprint is obtained by applying SHA on the classdescription.
The fingerprint is a 20 byte data packet, created by a
sequence of bit operations on the data that makes it certain
that the fingerprint will change if the information is alteredin any way.
-
8/2/2019 java by Kamalakar Dandu
153/284
Core Java Ver 2.0
153 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
154/284
Core Java Ver 2.0
154 of 284CopyrightWipro Technologies Talent Transformation
Inner Classes
-
8/2/2019 java by Kamalakar Dandu
155/284
Core Java Ver 2.0
155 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
156/284
Core Java Ver 2.0
156 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
157/284
Core Java Ver 2.0 157 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
158/284
Core Java Ver 2.0 158 of 284CopyrightWipro Technologies Talent Transformation
Topics
Intro
-
8/2/2019 java by Kamalakar Dandu
159/284
Core Java Ver 2.0 159 of 284CopyrightWipro Technologies Talent Transformation
Intro
History
JFC What makes Swing so Hot?
Lightweight Components
PLAF
MVC
Delegation Event Model
How Do I Use Swing?
Components
JComponent
Root Panes
Layouts
WorkShop Summary
Why Swing?
AWT i t f ti l h f f ll l li ti
-
8/2/2019 java by Kamalakar Dandu
160/284
Core Java Ver 2.0 160 of 284CopyrightWipro Technologies Talent Transformation
AWT is not functional enough for full scale applications
the widget library is small the widgets only have basic functionality
extensions commonly needed
AWT Components rely on native peers
widgets wont perform exactly the same on different platforms
History
P j b l 1996
-
8/2/2019 java by Kamalakar Dandu
161/284
Core Java Ver 2.0 161 of 284CopyrightWipro Technologies Talent Transformation
Project began late 1996
Active development since spring 1997
Beta in late 1997
Initial release march 1998 as part of the JFC
Java Foundation Classes
-
8/2/2019 java by Kamalakar Dandu
162/284
Core Java Ver 2.0 162 of 284CopyrightWipro Technologies Talent Transformation
AWT
Swing
2D API
Drag and Drop
Accessibility
Why is Swing so Hot?
-
8/2/2019 java by Kamalakar Dandu
163/284
Core Java Ver 2.0 163 of 284CopyrightWipro Technologies Talent Transformation
It uses lightweight components
It uses a variant of the Model View Controller
Architecture (MVC)
It has Pluggable Look And Feel (PLAF)
It uses the Delegation Event Model
Heavyweight Components
-
8/2/2019 java by Kamalakar Dandu
164/284
Core Java Ver 2.0 164 of 284CopyrightWipro Technologies Talent Transformation
Used by the AWT
Rectangular Opaque
Rely on native peers Look and Feel tied to operating system
functionality determined by operating system faster, because the OS handles the work
Lightweight Components
-
8/2/2019 java by Kamalakar Dandu
165/284
Core Java Ver 2.0 165 of 284CopyrightWipro Technologies Talent Transformation
Can have transparent portions
Can be any shape
Can overlap each other
Mouse events fall through transparent portionsDo not rely on native peers
Look and Feel drawn at runtime so can vary
functionality is the same on all platforms
slower because Java has to do the work
Lightweight vs Heavyweight
-
8/2/2019 java by Kamalakar Dandu
166/284
Core Java Ver 2.0 166 of 284CopyrightWipro Technologies Talent Transformation
Model View Controller
-
8/2/2019 java by Kamalakar Dandu
167/284
Core Java Ver 2.0 167 of 284CopyrightWipro Technologies Talent Transformation
Model
state data for each component
different data for different models
View
how the component looks onscreen
Controller
dictates how the component reacts to events
Independent elements:
MVC Communication
-
8/2/2019 java by Kamalakar Dandu
168/284
Core Java Ver 2.0 168 of 284CopyrightWipro Technologies Talent Transformation
View determines which
events are passed to controller
Model passes data to view
for rendering
Controller updates model
based on events received
MVC Example
-
8/2/2019 java by Kamalakar Dandu
169/284
Core Java Ver 2.0 169 of 284CopyrightWipro Technologies Talent Transformation
Model: Minimum=0
Maximum=100
Value=0
View:
Controller:
-accept mouse click on end buttons
-accept mouse drag on thumb
MVC in Java
-
8/2/2019 java by Kamalakar Dandu
170/284
Core Java Ver 2.0 170 of 284CopyrightWipro Technologies Talent Transformation
Swing uses the model-delegate design, a similar architecture to MVC.
The View and Controller elements are combined into the UI delegate since Java handlesmost events in the AWT anyway.
Multiple views can be used with a single model.
Changes to a single Model can affect different views.
Components can share a model (JScrollbar and JSlider share the BoundedRangeModel).
MVC in Java
-
8/2/2019 java by Kamalakar Dandu
171/284
Core Java Ver 2.0 171 of 284CopyrightWipro Technologies Talent Transformation
Component UI-delegate
View
Model
Controller
PLAF Features in Swing
Default Metal style
-
8/2/2019 java by Kamalakar Dandu
172/284
Core Java Ver 2.0 172 of 284CopyrightWipro Technologies Talent Transformation
Default Metal style
Can emulate Motif, and Windows styles
Supports Mac style through download
New styles can be designed
Can be reset at runtime
PLAF examples
-
8/2/2019 java by Kamalakar Dandu
173/284
Core Java Ver 2.0 173 of 284CopyrightWipro Technologies Talent Transformation
PLAF Structure
All components have an abstract UI delegate in the swing plaf
-
8/2/2019 java by Kamalakar Dandu
174/284
Core Java Ver 2.0 174 of 284CopyrightWipro Technologies Talent Transformation
All components have an abstract UI delegate in the swing.plafpackage (Jbutton - ButtonUI)
UI delegate is accessed by get/setUI() method
Each Look and Feel has a concrete class for each abstract UI delegate(WindowsButtonUI)
communicate through UIManager class
get/setLookAndFeel()
Delegation Event Model
-
8/2/2019 java by Kamalakar Dandu
175/284
Core Java Ver 2.0 175 of 284CopyrightWipro Technologies Talent Transformation
In JDK 1.0 only component classes have event handlingmethods, and so no other objects can handle events.
Component event handling methods are replaced by eventlistener interfaces and adapter classes
Any class can use listener interfaces or adapter classes.
Swing relies on the Delegation Event Model of JDK 1.1.
JDK 1.0 Event Model
programs must subclass GUI components and override action() or handleEvent()
-
8/2/2019 java by Kamalakar Dandu
176/284
Core Java Ver 2.0 176 of 284CopyrightWipro Technologies Talent Transformation
programs must subclass GUI components and override action() or handleEvent()
many classes are needed
events are propagated up the GUI hierarchy until it is consumed or the root of the
hierarchy is reached
events for a hierarchy can be handled by one container (complex conditional
statement needed)
JDK 1.0 Event Model Problems
subclassing components without changing them is redundant and cumbersome
-
8/2/2019 java by Kamalakar Dandu
177/284
Core Java Ver 2.0 177 of 284CopyrightWipro Technologies Talent Transformation
a g p w a g g a a
no separation of the application model from the GUI is possible (no MVC)
complicated to process different event types since events are handled by the same
methods
events are delivered to components whether or not the components handle them
JDK 1.1 Event Listeners
objects that implement a specific EventListener interface extended
-
8/2/2019 java by Kamalakar Dandu
178/284
Core Java Ver 2.0 178 of 284CopyrightWipro Technologies Talent Transformation
objects that implement a specific EventListener interface extended
from the generic java.util.EventListener define the methods which are to be invoked by the event source in
response to each specific event type handled by the interface
Event Types
Low level
-
8/2/2019 java by Kamalakar Dandu
179/284
Core Java Ver 2.0 179 of 284CopyrightWipro Technologies Talent Transformation
low-level input or window-system occurrence on a visual component on the screen
java.awt.event.ComponentEvent (component resized, moved, etc.)
java.awt.event.KeyEvent (component got key-press, key-release, etc.)
java.awt.event.MouseEvent (component got mouse-down, mouse-move, etc.)
java.awt.event.FocusEvent (component got focus, lost focus)
Event Types
Semantic
-
8/2/2019 java by Kamalakar Dandu
180/284
Core Java Ver 2.0 180 of 284CopyrightWipro Technologies Talent Transformation
related to the semantics of a user interface component's model
java.awt.event.ActionEvent ("do command")
java.awt.event.AdjustmentEvent ("components value adjusted")
java.awt.event.ItemEvent ("item state has changed")
java.awt.event.TextEvent ("the value of the text changed")
Event Sources
-
8/2/2019 java by Kamalakar Dandu
181/284
Core Java Ver 2.0 181 of 284CopyrightWipro Technologies Talent Transformation
Multiple event listeners can be assigned to a source (order not
guaranteed)
Low level
java.awt.Component
addComponentListener(ComponentListener l)
addMouseListener(MouseListener l)
addMouseMotionListener(MouseMotionListener l)
Semantic
java.awt.List
addActionListener(ActionListener l)
addItemListener(ActionListener l)
Adapters
-
8/2/2019 java by Kamalakar Dandu
182/284
Core Java Ver 2.0 182 of 284CopyrightWipro Technologies Talent Transformation
java.awt.event.ComponentAdapter
java.awt.event.ContainerAdapter
java.awt.event.FocusAdapter
java.awt.event.KeyAdapter
java.awt.event.MouseAdapter
java.awt.event.MouseMotionAdapter
java.awt.event.WindowAdapter
These can be extended instead of using interfaces when
the interface has many unused methods
(eg.MouseMotionListener).
The Adapter classes:
New Swing Event Classes
-
8/2/2019 java by Kamalakar Dandu
183/284
Core Java Ver 2.0 183 of 284CopyrightWipro Technologies Talent Transformation
Component Events Description
JPopupMenu PopupMenuEvent User selected a choice JComponent AncestorEvent An event occurred in
an ancestor
JList ListSelectionEvent User double-clicked a list
item
ListDataEvent List's contents were changed
JMenu MenuEvent User selected menu item
JTextComponent CaretEvent Mouse clicked in text
UndoableEditEvent An undoable edit has
occurred
JTable TableModelEvent Items added/removed
from table
TableColumnModelEvent A table column was moved
JTree TreeModelEvent Items added/removed
from tree
TreeSelectionEvent User selected a tree node
TreeExpansionEvent User changed tree node
JWindow WindowEvent User manipulated window
How do I Use Swing?
-
8/2/2019 java by Kamalakar Dandu
184/284
Core Java Ver 2.0 184 of 284CopyrightWipro Technologies Talent Transformation
CLASSPATH
JDK 1.1
JDK
Java 2
AWT
Classes
SwingClasses
JFC
AWT
Classes
Swing
Classes
Packages of Note
javax.accessibility
-
8/2/2019 java by Kamalakar Dandu
185/284
Core Java Ver 2.0 185 of 284CopyrightWipro Technologies Talent Transformation
javax.accessibility
javax.swing javax.border
javax.swing.event
javax.plaf com.sun.java.swing.plaf
JComponent Class
the common root of most of the Swing GUI classes
-
8/2/2019 java by Kamalakar Dandu
186/284
Core Java Ver 2.0 186 of 284CopyrightWipro Technologies Talent Transformation
the common root of most of the Swing GUI classes
provides the guiding framework for GUI objects extends java.awt.Container class
other objects can be added to it (be careful)
Useful Components
-
8/2/2019 java by Kamalakar Dandu
187/284
Core Java Ver 2.0 187 of 284CopyrightWipro Technologies Talent Transformation
Methods Inherited from Component Class
get/setBackground()
-
8/2/2019 java by Kamalakar Dandu
188/284
Core Java Ver 2.0 188 of 284CopyrightWipro Technologies Talent Transformation
is/setEnabled()
get/setFont() get/setForeground()
get/setLayout()
get/setLocationOnScreen()
get/setName()
get/setParent()
is/setVisible()
New Methods
get/setBounds()
i
get/setBorder()
i bl ff d
-
8/2/2019 java by Kamalakar Dandu
189/284
Core Java Ver 2.0 189 of 284CopyrightWipro Technologies Talent Transformation
get/setSize()
get/setLocation() get/setWidth()
get/setHeight()
get/setMaximumSize()
get/setMinimumSize()
get/setPreferredSize()
is/setDoubleBuffered()
getGraphics() get/setToolTipText()
add()
remove()
pack()
Swing Component and Containment Hierarchy
-
8/2/2019 java by Kamalakar Dandu
190/284
Core Java Ver 2.0 190 of 284CopyrightWipro Technologies Talent Transformation
Adding components to containers
-
8/2/2019 java by Kamalakar Dandu
191/284
Core Java Ver 2.0 191 of 284CopyrightWipro Technologies Talent Transformation
frame = new JFrame(...);
button = new JButton(...);
label = new JLabel(...);
pane = new JPanel();
pane.add(button);
pane.add(label);
frame.getContentPane().add(pane,BorderLayout.CENTR);
Root panes
-
8/2/2019 java by Kamalakar Dandu
192/284
Core Java Ver 2.0 192 of 284CopyrightWipro Technologies Talent Transformation
Layout Managers
arrange widgets according to a pattern
-
8/2/2019 java by Kamalakar Dandu
193/284
Core Java Ver 2.0 193 of 284CopyrightWipro Technologies Talent Transformation
g g g p
can update containers to handle resizing of the container orinternal widgets
make complex UIs possible
Default Layout Managers
I AWT th d f lt l t
-
8/2/2019 java by Kamalakar Dandu
194/284
Core Java Ver 2.0 194 of 284CopyrightWipro Technologies Talent Transformation
Container Layout ManagerJApplet BorderLayout (on its content pane)JBox BoxLayout
JDialog BorderLayout (on its content pane)JFrame BorderLayout (on its content pane)JPanel FlowLayoutJWindow BorderLayout (on its content pane)
In AWT, the default layout
for applets wasFlowLayout.
Top-levelwindows use
BorderLayout
Flow Layout
-
8/2/2019 java by Kamalakar Dandu
195/284
Core Java Ver 2.0 195 of 284CopyrightWipro Technologies Talent Transformation
Arranges components from left to right and top to bottom
Fits as many components in a row as possible before making a newrow
lets you specify alignment, horizontal and vertical spacing
1 2 3 4
5
Border Layout
-
8/2/2019 java by Kamalakar Dandu
196/284
Core Java Ver 2.0 196 of 284CopyrightWipro Technologies Talent Transformation
Arranges components according to specified edges or the middle
NORTH
SOUTH
EAST
WEST CENTER
lets you specify horizontal and vertical spacing
C
N
S
W E
contentPanel.setLayout(new BorderLayout(0, 0));
contentPanel.add("Center", oPanel);
contentPanel.add("South", controlPanel);
Grid Layout
-
8/2/2019 java by Kamalakar Dandu
197/284
Core Java Ver 2.0 197 of 284CopyrightWipro Technologies Talent Transformation
Arranges components in a grid with specified rows and columns
rows have same height and columns have same width
0,0 0,1 0,2
1,1 1,3
contentPanel.setLayout(new GridLayout(2, 4));
contentPanel.add(startButton, 0, 0);
contentPanel.add(stopButton, 1, 3);
Gridbag Layout
-
8/2/2019 java by Kamalakar Dandu
198/284
Core Java Ver 2.0 198 of 284CopyrightWipro Technologies Talent Transformation
BoxLay out
-
8/2/2019 java by Kamalakar Dandu
199/284
Core Java Ver 2.0 199 of 284CopyrightWipro Technologies Talent Transformation
-
8/2/2019 java by Kamalakar Dandu
200/284
Core Java Ver 2.0 200 of 284CopyrightWipro Technologies Talent Transformation
Work shop
Case Study: Designing a Basic GUI
-
8/2/2019 java by Kamalakar Dandu
201/284
Core Java Ver 2.0 201 of 284CopyrightWipro Technologies Talent Transformation
Basic User Interface Tasks: Provide help/guidance to the user. Allow input of information. Allow output of information. Control interaction between the user
and device.
Problem Description:Design a GUI for a Javaapplication that converts miles to kilometers. Writethe class that performs the conversions.
GUI Design: Choosing Components
-
8/2/2019 java by Kamalakar Dandu
202/284
Core Java Ver 2.0 202 of 284CopyrightWipro Technologies Talent Transformation
Swing objects for input, output, control, guidance:
Guidance
Input
Output
Control
GUI Design: Layout
-
8/2/2019 java by Kamalakar Dandu
203/284
Core Java Ver 2.0 203 of 284CopyrightWipro Technologies Talent Transformation
prompt:
JTextArea for displaying f ile
JTextField JButton
Convert
JLabelJFrame
Containment Hie rarchy
JFramePrompt JLabel
Display JTextArea
Convert JButton
Input JTextField
*
**
import javax.swing.*; // Packages usedimport java.awt.*;import java.awt.event.*;
public class Converter extends JFrame implements ActionListener{i t JL b l t JL b l("Di t i il ")
Implementing the Converter Class
-
8/2/2019 java by Kamalakar Dandu
204/284
Core Java Ver 2.0 204 of 284CopyrightWipro Technologies Talent Transformation
private JLabel prompt = new JLabel("Distance in miles: ");
private JTextField input = new JTextField(6);private JTextArea display = new JTextArea(10,20);private JButton convert = new JButton("Convert!");
public Converter() {getContentPane().setLayout(new FlowLayout());getContentPane().add(prompt);getContentPane().add(input);
getContentPane().add(convert);getContentPane().add(display);display.setLineWrap(true);display.setEditable(false);convert.addActionListener(this);
} // Converter()
public void actionPerformed( ActionEvent e ) {
double miles = Double.valueOf(input.getText()).doubleValue();double km = MetricConverter.milesToKm(miles);display.append(miles + " miles equals " + km + " kilometers\n");
} // actionPerformed()} // Converter
Instantiating the Top-Level JFrame
-
8/2/2019 java by Kamalakar Dandu
205/284
Core Java Ver 2.0 205 of 284CopyrightWipro Technologies Talent Transformation
public static void main(String args[]) {Converter f = new Converter();f.setSize(400, 300);f.setVisible(true);
// Quit the application
f.addWindowListener(new WindowAdapter() {public void windowClosing(WindowEvent e) {
System.exit(0);}
});} // main()
GUI Design Critique
-
8/2/2019 java by Kamalakar Dandu
206/284
Core Java Ver 2.0 206 of 284CopyrightWipro Technologies Talent Transformation
Extending the GUI: Button Array
-
8/2/2019 java by Kamalakar Dandu
207/284
Core Java Ver 2.0 207 of 284CopyrightWipro Technologies Talent Transformation
prompt:
JTextArea for
displaying file
JTextField JButton
Convert
JLabelJFrame
1 2 3
4 5 6
7 8 9
0 .C
Keypad JPanel
Containment Hierarchy
JFrame
Prompt JLabel
Display JTextArea
Convert JButton
Input JTextField
Keypad JPanel
12 JButtons
Implementing a Button Array
-
8/2/2019 java by Kamalakar Dandu
208/284
Core Java Ver 2.0 208 of 284CopyrightWipro Technologies Talent Transformation
private JPanel keypadPanel; // Holds the buttonsprivate JButton keyPad[]; // An array of buttonsprivate String label[] = // And their labels
{ "1","2","3","4","5","6","7","8","9","C","0","." };
public void initKeyPad() {keyPad = new JButton[NBUTTONS]; // Create the array itselffor(int k = 0; k < keyPad.length; k++) { // For each button
keyPad[k] = new JButton(label[k]); // Create a labeled buttonkeyPad[k].addActionListener(this); // and a listener
keypadPanel.add(keyPad[k]); // and add it to the panel} // for
} // initKeyPad()
Implementing a Button Array (cont)
Keypad events are handled in actionPerformed():
-
8/2/2019 java by Kamalakar Dandu
209/284
Core Java Ver 2.0 209 of 284CopyrightWipro Technologies Talent Transformation
public void actionPerformed(ActionEvent e) {if (e.getSource() == convert || e.getSource() == input) {
double miles = Double.valueOf(input.getText()).doubleValue();double km = MetricConverter.milesToKm(miles);display.append(miles + " miles equals " + km + " kilometers\n");input.setText("");
} else { // A keypad button was pressedJButton b = (JButton)e.getSource();if (b.getText().equals("C"))
input.setText("");else
input.setText(input.getText() + b.getText());}
} // actionPerformed()
GUI Design Critique
-
8/2/2019 java by Kamalakar Dandu
210/284
Core Java Ver 2.0 210 of 284CopyrightWipro Technologies Talent Transformation
The GridLayout Manager
-
8/2/2019 java by Kamalakar Dandu
211/284
Core Java Ver 2.0 211 of 284CopyrightWipro Technologies Talent Transformation
Converter: BorderLayout Design
-
8/2/2019 java by Kamalakar Dandu
212/284
Core Java Ver 2.0 212 of 284CopyrightWipro Technologies Talent Transformation
prompt:
JTextArea for
displaying file at
center of border
layout
JTextField
JButtons
Convert
JLabel
JFrame
1 2 3
4 5 6
7 8 9
0 .C
Keypad Panel
Containment Hierarchy
JFrame (Border)
Prompt JLabel
Display JTextAre a
Convert JButton
Input JTextField
Keypad JPanel (Grid)
12 JButtons
Input JPanel (Flow)
Control JPanel (Border)
Control Panel
Input
Panel
N
C
E
Converter: BorderLayout Implementation
-
8/2/2019 java by Kamalakar Dandu
213/284
Core Java Ver 2.0 213 of 284CopyrightWipro Technologies Talent Transformation
public Converter() {getContentPane().setLayout(new BorderLayout());initKeyPad();JPanel inputPanel = new JPanel(); // Input panelinputPanel.add(prompt);inputPanel.add(input);getContentPane().add(inputPanel,"North");
JPanel controlPanel = new JPanel(new BorderLayout(0, 0)); // ControlscontrolPanel.add(keypadPanel, "Center");controlPanel.add(convert, "South");getContentPane().add(controlPanel, "East");getContentPane().add(display,"Center"); // Output displaydisplay.setLineWrap(true);display.setEditable(false);convert.addActionListener(this);input.addActionListener(this);
} // Converter()
Converter: Final Version
-
8/2/2019 java by Kamalakar Dandu
214/284
Core Java Ver 2.0 214 of 284CopyrightWipro Technologies Talent Transformation
Outputs
Checkboxes
-
8/2/2019 java by Kamalakar Dandu
215/284
Core Java Ver 2.0 215 of 284CopyrightWipro Technologies Talent Transformation
private JCheckBox titles[] = new JCheckBox[NTITLES];private String titleLabels[] =
{"Chess Master - $59.95", "Checkers Pro - $39.95","Crossword Maker - $19.95"};
for(int k = 0; k < titles.length; k++) {titles[k] = new JCheckBox(titleLabels[k]);titles[k].addItemListener(this);choicePanel.add(titles[k]);
}
Radio Buttons
-
8/2/2019 java by Kamalakar Dandu
216/284
Core Java Ver 2.0 216 of 284CopyrightWipro Technologies Talent Transformation
private ButtonGroup optGroup = new ButtonGroup();private JRadioButton options[] = new JRadioButton[NOPTIONS];private String optionLabels[] = {"Credit Card", "Debit Card",
"E-cash"};
for(int k = 0; k < options.length; k++) {options[k] = new JRadioButton(optionLabels[k]);options[k].addItemListener(this);optionPanel.add(options[k]);optGroup.add(options[k] );
}options[0].setSelected(true); // Set the first button on
Design: The Online Order Form
-
8/2/2019 java by Kamalakar Dandu
217/284
Core Java Ver 2.0 217 of 284CopyrightWipro Technologies Talent Transformation
The Order Form Applet
-
8/2/2019 java by Kamalakar Dandu
218/284
Core Java Ver 2.0 218 of 284CopyrightWipro Technologies Talent Transformation
The ItemListener Interface
-
8/2/2019 java by Kamalakar Dandu
219/284
Core Java Ver 2.0 219 of 284CopyrightWipro Technologies Talent Transformation
public void itemStateChanged(ItemEvent e) {display.setText("Your order so far (Payment by: ");for (int k = 0; k < options.length; k++ )
if (options[k].isSelected())display.append(options[k].getText() + ")\n");
for (int k = 0; k < titles.length; k++ )if (titles[k].isSelected())
display.append("\t" + titles[k].getText() + "\n");} // itemStateChanged()
The OrderApplet Class: Initialization
public class OrderApplet extends JApplet implements ItemListener, ActionListener {private final int NTITLES = 3, NOPTIONS = 3;private JPanel mainPanel = new JPanel(),
centerPanel = new JPanel(), import javax.swing.*;
-
8/2/2019 java by Kamalakar Dandu
220/284
Core Java Ver 2.0 220 of 284CopyrightWipro Technologies Talent Transformation
J (),
choicePanel = new JPanel(),optionPanel = new JPanel(),buttonPanel = new JPanel();
public void init() {
mainPanel.setBorder(BorderFactory.createTitledBorder("Acme Software Titles"));mainPanel.setLayout(new GridLayout(3, 1, 1, 1));cancel.addActionListener(this);submit.addActionListener(this);
initChoices();initOptions();buttonPanel.setBorder( BorderFactory.createTitledBorder("Order Today"));buttonPanel.add(cancel);buttonPanel.add(submit);centerPanel.add(choicePanel);centerPanel.add(optionPanel);mainPanel.add( display);mainPanel.add(centerPanel);mainPanel.add( buttonPanel);getContentPane().add(mainPanel);setSize(400,400);
} // init()
} // OrderApplet
import javax.swing. ;
import javax.swing.border.*;import java.awt.*;import java.awt.event.*;
OrderApplet Class: Handling Actions
-
8/2/2019 java by Kamalakar Dandu
221/284
Core Java Ver 2.0 221 of 284CopyrightWipro Technologies Talent Transformation
public void actionPerformed(ActionEvent e){String label = submit.getText();if (e.getSource() == submit) {
if (label.equals("Submit Order")) {display.append("Thank you. Press 'Confirm' to submit for your order!\n");
submit.setText("Confirm Order");} else {
display.append("Thank you. You will receive your order tomorrow!\n");submit.setText("Submit Order");
}} else
display.setText("Thank you. Maybe we can serve you next time!\n");} // actionPerformed()
Menus
-
8/2/2019 java by Kamalakar Dandu
222/284
Core Java Ver 2.0 222 of 284CopyrightWipro Techno