Yashavant Kanetkar [email protected] Solutions Using J2EE / Lecture 01 1 Yashavant...
Transcript of Yashavant Kanetkar [email protected] Solutions Using J2EE / Lecture 01 1 Yashavant...
Enterprise Solutions Using J2EE / Lecture 01 1
Yashavant [email protected]
Objectives
Current software scenarioWhy should we use JavaDifferent Java TechnologiesJava based software development
Software Scenario
Software
Desktop
Web
Embedded
DistributedOS
Compiler
Dev. Dri.
C/ C++
Java / VB / C# / VC++
Enterprise Solutions Using J2EE / Lecture 01 2
Why Java?Easy to develop
Check as you type - Like Spellcheck, GrammarcheckIntellisense - Function parametersVery good examples / samplesExhaustive documentation – http://java.sun.com/docs/
Rapid Application Development (RAD)Media playerEmbedded Web browserEmbedded Excel browser
Same language, same tool for multiple applicationsEasy to manage large projects (1,00,000 lines code)
Source controlDebuggingProject organization
Java Technologies
J2SE J2ME J2EE
Connectivity - Virus SignaturesPluggable interface - Google toolbarFunctionally rich programs
HelpSearchUpdate
J2SE Track
Desktop
Enterprise Solutions Using J2EE / Lecture 01 3
Smaller screensDifferent user-interfacesIntermittent connectivitySynchronization ( address book )
J2ME Track
Embedded
J2EE TrackPortalsThemesModules
Internet
Java Based Software Development
• RAD tool• Wizard generated skeleton code• Debugging help• Industry standard• www.netbeans.org
Java IDEJava Development Kit – Compiler, Linker, etc.Java Runtime Environment
VJ++JBuilderVisual CaféNetBeans
Choices
java.sun.com – JDK 6.0 c:\Program Files\Java\jdk1.6.0
Enterprise Solutions Using J2EE / Lecture 02 1
Constants, Variables, Keywords
Yashavant Kanetkar
ObjectivesLearning stepsConstants and VariablesTypes of constants and VariablesHow to identify typesRules for creating variablesKeywords
In The Beginning...
Alphabets, Digits Alphabets, Digits, Sp. Symbols
Constants, Variables, Keywords
Statements or Instructions
Program
English Java
Paragraph
Sentences
Words, Numbers
Enterprise Solutions Using J2EE / Lecture 02 2
AlphabetsA - Z, a - z
Sp. SymbolsTotal - 32
Alphabets, Digits, Sp. Symbols
Digits0 - 9
Constants & Variables
3 x + 2 y
x = 3y = 5x = 7z = 3.14w = 'A'
Variables Constants
3, 5, 7 - Integer constants3.14 - Real constant'A' - Character constantw, x, y, z - Variables
ConstantsLiterals
VariablesIdentifiers
Integer Constants
4. Valid Range: -2147483648 to +2147483647
Rules:Ex. 421 -62 +45 4096
1. No decimal point
2. May be +ve or -ve. Default: +ve
32,500 4 7 33. No comma or spaces
72 72.0
Enterprise Solutions Using J2EE / Lecture 02 3
Real Constants
1. Must contain a decimal point2. May be +ve or -ve. Default: +ve3. No comma or spaces4. Valid Range: -3.4x 1038 to +3.4 x 10385. Different forms:
Rules:Ex. 427.62 +24.297 -0.00254
427.62+24.295-0.00254
4.2762E22.4295e1-2.54e-3
ExponentMantissa4.2762 2E
Exponential FormFractional Form
Rule : A single character enclosedwithin a pair of ’ ’.
Character Constants
‘Z’’Nagpur’
Ex. ’A’ ’m’ ’3’ ’+’
Are They OK?
Java Data Types ‐ Primitives
charData Type Range Size
byteshortintlong
floatdouble
0 to 65535-128 to +127-32768 to +32767-2147483648 to +2147483647
-9223372036854775808 to +9223372036854775807 -3.4e38 to +3.4e38-1.7e308 to +1.7e308
21248
48
boolean 1-bittrue / false
Fixed but not fixedType determines behaviour not size
Enterprise Solutions Using J2EE / Lecture 02 4
Is it necessary to identify types?Yes.
Variables
How many types?As many as the types of constants.
Why?
y = 4y = ’A’Why?
MemoryWhat Happens in Memory...
xy
z
x = 3
3y = 4z = x + yprint z
VariableAn entity whose value can changeA name given to a location in memory
x = 5
54
7
Would this work?int xyz int abc123int 123abc
33.0’3’abc
How to Identify TypesInteger ConstantReal ConstantCharacter Constant
?
??
int aa = 3 b = 3.0 c = ’3’
float b char c
int, float, char - data types / primitivesa, b, c - variables3, 3.0, '3' - constants / literals
Enterprise Solutions Using J2EE / Lecture 02 5
Cannot begin with a digit
Rest can be alphabets, digits, underscores or $
Ex. pop98 si_int
Rules for Building Var. Names
Any Length
No commas or spaces
Variable names are case sensitive
Ex. abc ABC Abc aBc AbC
_- si-int
si_int
All are different
Java KeywordsHow many?
And How About This...
int float float charfloat = 3 char = 3.14
integer areal bcharacter c
Would This Work?
48
Words whose meaning already stands explainedWhat are Reserved words? Same as keywords
Any examples? int, float, charWhat are Keywords?
1Enterprise Solutions Using J2EE / Lecture 03
First Java ProgramYashavant [email protected]
ObjectivesFirst Java programPrinting valuesGeneral form of println( )Function, Class and PackageType of comments
Where Do We Stand?
Alphabets, Digits, Sp. Symbols
Constants, Variables, Keywords
Statements or Instructions
Program
2Enterprise Solutions Using J2EE / Lecture 03
The First Java Program
p = 1000.50fn = 3 r = 15.5fsi = p * n * r / 100
float p, r, siint n
TipsAll variables must be declared+ - * / are Arithmetic Operators
2 \ 3232 3÷
Printing Values...float p, r, siint n p = 1000.50fn = 3 r = 15.5fsi = p * n * r / 100 System.out.println ( si )
p1000.50 3 15.50
n r
465.25
si
( ) Parentheses Braces[ ] Brackets
Class Object Function
Statement Terminators
float p, r, si ;int n ;
: colon ; semicolon
I am a boy I go to school
float p, r, siint n
Statement Terminator
float p, r, si ;int n ;
float p, r, si ; int n ;
3Enterprise Solutions Using J2EE / Lecture 03
What To Execute
float p, r, si ;int n ;p = 1000.50f ; n = 3 ; r = 15. 5f ;si = p * n * r / 100 ;System.out.println ( si ) ;
public static void main( )
ScopeDelimiters
Function
class SimpleInterest
package simpleinterest ;
Keyword
Keyword
Tips…A Java program is a collection of one or more packagesEach package can contain multiple classesEach class may contain multiple functionsEvery variable should belong to a function Every function must belong to a classEvery class must belong to a packagepackage, class, public, static, void – Keywordspublic static is same as static publicJava is case-sensitive and free-form language
package simpleinterest ;class Simpleinterest
public static void main( )
float p, r, si ;int n ;p = 1000.50f ; n = 3 ; r = 15. 5f ;si = p * n * r / 100 ;System.out.println ( si ) ;
Comments Are Useful/* Calculation of simple interest */
NoteRemark
4Enterprise Solutions Using J2EE / Lecture 03
Types Of CommentsSingle line comments
Documentation comments
Multi-line comments
/* Cal. of simple interestAuthor – Yashavant KanetkarDate – 25 Jun 2008 */
si = p * n * r / 100 ;// calculation of simple interest
si = p * n * r / 100 ; // calculation of simple int.
/*** @param args the command line arguments*/
Tips About CommentsAny number of comments anywhere
Nested comments -/* .............. /* ....... */ ........ */
si = p * n * r / 100 ;/* formula */ /* formula */
Enterprise Solutions Using J2EE / Lecture 04 1
Using NetBeans
Yashavant [email protected]
Objectives
Understanding NetBeans IDECreating a program using NetBeansWhat is Java PlatformJava FAQs
NetBeans IDE
I D ECompiler
InterpreterLinker
Editor typing / editing
Java to Bytecode
Debugger
Bytecode to m/c
Enterprise Solutions Using J2EE / Lecture 04 2
Steps In Using NetBeans
Create a Project Add Code to the Generated Source File Compile the Source File Run the Program
Create New Project
Select Project Type
Enterprise Solutions Using J2EE / Lecture 04 3
Project Name & Location
packagename.classname
Wizard Generated Code
Package pkg
class One class Two
fun1
fun2
fun3
fun4
Realign
Add New Code
float p, r, si ;int n ;p = 1000.50f ; n = 3 ; r = 15. 5f ;si = p * n * r / 100 ;System.out.printf ( "%f", si ) ;
Enterprise Solutions Using J2EE / Lecture 04 4
Build & TestBuild | Build SimpleInterest Project F11
Run | Run SimpleInterest Project F6
What Happens
SimpleInterest.java SimpleInterest.classSimpleInterest
What Is Run Anywhere
SimpleInterest.java
Enterprise Solutions Using J2EE / Lecture 04 5
What Is Java Platform
Hardware
Windows / Mac / Unix
Java Virtual Machine
Java API
SimpleInterest.java
Java Platform
API = Library of classes in form of packages
Enterprise Solutions Using J2EE / Lecture 06 1
Generic Programs
Yashavant [email protected]
Objectives
More general programs
Modulus operator
Command-line arguments
package sample ;import java.io.* ;import java.lang.* ;public class Sample
public static void main ( String[ ] args ) throws Exception
float p ; String str ;BufferedReader b ;b = new BufferedReader ( new InputStreamReader (
System.in ) ) ;str = b.readLine( ) ;p = Float.parseFloat ( str ) ;System.out.printf ( "%f", p ) ;
Receiving Floats
Enterprise Solutions Using J2EE / Lecture 06 2
package simpleint ;import java.io.* ;import java.lang.* ;public class SimpleInt
public static void main ( String[ ] args ) throws Exception
float p, r, si ; int n ;BufferedReader b = new BufferedReader (
new InputStreamReader ( System.in ) ) ;String str ; System.out.println ( "Enter values" ) ;str = b.readLine( ) ;p = Float.parseFloat ( str ) ;
Generic Program
str = b.readLine( ) ;n = Integer.parseInt ( str ) ;str = b.readLine( ) ;r = Float.parseFloat ( str ) ;si = p * n * r / 100 ;System.out.println ( "Simple int. = Rs. " + si ) ;
How To Supply Values
Enterprise Solutions Using J2EE / Lecture 06 3
Interchange Contents of 2 Variables
public static void main( ) throws Exception c d
5 10tx
c d5 10
t5
c d10 10
t5
c d10 5
t5
t = c ;c = d ;d = t ;System.out.println ( c + " " + d )
int c, d, t ;
// receive values in c and d
5 10
10 5
One More Way
c d25 10c d
25 15c d
10 15c = c + d ;d = c - d ;c = c - d ;
c d15 10
public static void main( ) throws Exception
int c, d ;
UtilityRoll nos. in Asc/Desc. orderNames in alphabetical orderDates in chronological order
// receive values in c and d
15 10
System.out.println ( c + " " + d ) ;
10 15
2 6 9 1 3
public static void main( ) throws Exception
int n ;// receive value of n
Sum of Digits
26913
d1 d3d2 d4 d5
.. ..
.. .. 26913 / 10
26913 % 10- Division2691- Modular div.3
Mod
26910
3
10 26913 2691
Enterprise Solutions Using J2EE / Lecture 06 4
Utility
The Whole Picture
public static void main( ) throws Exception
…3 2691d5
n
d4
d3
d2
d1
1
9
6
2
269
26
2
26913
d5 = n % 10 ;
d4 = n % 10 ;
d3 = n % 10 ;
d2 = n % 10 ; d1 = n % 10 ; s = d1 + d2 + d3 + d4 + d5 ;System.out.println ( s ) ;
n = n / 10 ;
n = n / 10 ;
n = n / 10 ;
n = n / 10 ;
21
Leap year or notOdd / EvenPrime or not
System.out.println ( args[ 0 ] ) ; System.out.println ( args[ 1 ] ) ; System.out.println ( args[ 2 ] ) ;
Command Line Arguments
package myargs ;class Myargs
public static void main ( String args[ ] )
Array of String objects
Supplying Command Line Arguments
Enterprise Solutions Using J2EE / Lecture 06 1
Java InstructionsYashavant Kanetkar
Types of Java InstructionsType declaration instructionExpression instructionNuances of boolean, char, int, etc.Mixed mode expressions
Objectives
Type DeclarationExpressionControlSynchronizationGuarding
Where Are We....
Alphabets, Digits, Sp. Symbols
Constants, Variables, Keywords
Statements or Instructions
Program
Enterprise Solutions Using J2EE / Lecture 06 2
Type Declaration InstructionEx. int i, j, k ;
float a, b, c ;char ch ;
int i ;i = 5 ;
int i = 5 ;
int a = 5, b = 10, c = a + b * 5 % 2 ;
int a, b, c, d ;a = b = c = d = 5 ;
int a = b = c = d = 5 ;
order isimportant
Expression InstructionEx. s = d1 + d2 + d3 ;
si = p * n * r / 100 ;+ - * / %
For exponentiation -
double a ;a = Math.pow ( 2, 5 ) ;
Arithmetic Operators
a = b ( c + d ) ; a = b * ( c + d ) ;
i = j * k + 3 ;j * k + 3 = i ;
i = 3 ;3 = i ;
a = 2 ** 5 ;a = 2 ^ 5 ;
boolean a = false ;System.out.println ( "a = " + a ) ;System.out.println ( "Result = " + ( 4 > 3 ) ) ;
Boolean Type
a = false
Result = true
Do not use true / false as variable names
true is not 1 and false is not 0
int a ;a = 3 < 4 ;
boolean b ;b = 3 < 4 ;
Boolean can take a value true or false
Result of a Boolean expression is true / false
Enterprise Solutions Using J2EE / Lecture 06 3
Char Typechar ch = ’A’ ; System.out.print ( ch ) ; - 65 is not stored
- Unicode is stored- Size – 2 bytes
char ch = ’A’ ; char dh = ch + 1 ;System.out.print ( dh ) ;
char is promoted to intbefore arithmeticSolution:
int dh = ch + 1 ;
Integer Type4 types – byte, short, int, longMost common – intbyte and short are used to save spacelong is used to deal with very big integer valuesBy default number without a decimal point is intDuring assignment value being assigned should notexceed the range of the variable
byte a = 300 ;short b = 40000 ;int c = 2200000000 ;
Real Type2 types – float, doubleMost common – floatdouble is used to deal with very big real valuesBy default number with a decimal point is doubleDuring assignment value being assigned should notexceed the range of the variable
Enterprise Solutions Using J2EE / Lecture 06 4
float a = 3.14 ;
int b = 3.14 ;
Mixing Types
int a = ( int ) 3.14f ;Typecasting
float a = 3.14f ;float a = 3.14F ;
short a = ( short ) 32768 ;System.out.println ( a ) ; -32768
Widening conversions take place automaticallylong l = 40000 * 2 ;Narrowing conversions report errorsshort s = 40000 ;
Possible loss of precision is reported as errorshort s ; short s ; int i = 5 ;s = 2 * 5 ; s = 2 * i ;
Enterprise Solutions Using J2EE / Lecture 07 1
Yashavant [email protected]
Precedence & Associativity
What is mixed mode arithmetic?What is precedence of operators?What is associativity of operators?Printing functions and their features
Objectives
Mixed Mode Arithmetic
5 / 2 5.0f / 2 5 / 2.0f 5.0f / 2.0f 2 / 5 2.0f / 5 2 / 5.0f 2.0 / 5.0f
22.52.52.500.40.40.4
Enterprise Solutions Using J2EE / Lecture 07 2
Operand1 Operand2 Result
int intfloat floatint float float int
All Possible Cases
intfloatfloatfloat
Which Is Correct?
float c, f = 212.0f ;
c = 5 / 9 * ( f - 32 ) ;
c = 5 / 9.0f * ( f - 32 ) ;
c = ( f - 32 ) * 5 / 9 ;
Note: Parenthesis matter
0.0
100.0
100.0
Hierarchy/Priority/Precedence
c = a + b * c % 5 - d * 61
Operators
* / %+ -=2
4
6
3
5
Enterprise Solutions Using J2EE / Lecture 07 3
Associativity - I
c = 3 / 2 * 5 ; / * L to R AssociativityLeft - Unambiguous1
23
Right OperandOperator RemarkLeft Operand
L ok, R Not ok3/ 52 or 2 * 5 L Not ok, R ok2 or 3 / 2*
Right OperandOperator RemarkLeft Operand
Associativity - II
a = b = 5 ;
L ok, R Not okb or b = 5a1st =L Not ok, R ok5a or a = b2nd =
12
= R to L AssociativityRight - Unambiguous
Try: a = 2 * 3 / 4 % 5
Output Functions
println( ), print( ), printf( ) – Outputprintln( ) – print and go to new lineprint( ) – print printf( ) – for formatted printing
System.out.print ( "First " ) ; System.out.print ( "Second " ) ; System.out.println ( "Third " ) ; System.out.println ( "Fourth" ) ;
First Second ThirdFourth
Enterprise Solutions Using J2EE / Lecture 07 4
printf( )
General FormS.o.printf ( "format string", list of variables ) ;
S.o.printf ( "Enter values of c and d" ) ;List of variables is optional
S.o.printf ( "%i %i %i", a, 35, 2 + 6 % 3 ) ;List can contain var., const., or expressions
printf( )
S.o.printf ( "format string", list of variables ) ;
System.out.printf ( "\nSimple Interest = Rs. %f", si );
can contain
Format specifiers- int - %d- float - %f- char - %c
Escape sequences
Any othercharacters
Enterprise Solutions Using J2EE / Lecture 08 1
Decision Control Instructions - I
Yashavant [email protected]
ObjectivesWhat are Control Instructions What are decision control instructionif, else keywordRelational operators
InstructionsType Declaration InstructionsExpression InstructionsControl Instructions Synchronization InstructionsGuarding Instructions
Enterprise Solutions Using J2EE / Lecture 08 2
Control InstructionsWhat are they?- Control the sequence of execution of instructions
What different types?- Sequence- Decision- Repetition- Case
Normal Java Programclass sample
public static void main( ) throws Exception
int .... ; float .... ;// receive inputa = .... ;b = .... ;System.out.printf ( .... ) ;
Tip: Sequence CI is the default CI
Decision Control Instruction// Calculation of total expensesclass totalexpenses
public static void main( ) throws Exception
int qty ; float price ;BufferedReader b ;b = new BufferedReader (
new InputStreamReader ( System.in ) ) ;String str ;System.out.println ( "Enter quantity and price" ) ; str = b.readLine( ) ;qty = Integer.parseInt ( str ) ;str = b.readLine( ) ;price = Float.parseFloat ( str ) ;...
Enterprise Solutions Using J2EE / Lecture 08 3
// Calculation of total expenses public static void main( ) throws Exception
int qty ; float price ;
// receive qty and price
if ( qty >= 1000 )dis = 10 ;
- qty * price * dis / 100 ;totexp = qty * priceSystem.out.println ( "Total exp = Rs ", totexp );
200 15.50int dis ; float totexp ;
elsedis = 0 ;
1200 15.50
Tipsif, else - Keywords
General form:if ( condition )
statement1 ;else
statement2 ;
Condition is built using <, >, <=, >=, = =, !=
a = b
a = = b
Relational Operators
Assignment
Comparison
// receive qty and price
// Calculation of Total Expensespublic static void main( ) throws Exception
Tip: else block is optional
if ( qty >= 1000 )dis = 10 ;
int qty ; int dis ;float price ;
totexp = qty * price - qty * price * dis / 100 ;
= 0 float totexp ;
System.out.println ( "Total exp = Rs " + totexp ) ;
200 15.50
1200 15.50
One More Way
Enterprise Solutions Using J2EE / Lecture 08 4
if ( bs >= 1500 )da = bs * 95 / 100 ;
hra = bs * 20 / 100 ;ca = bs * 12 / 100 ;else
da = bs * 92 / 100 ;hra = bs * 15 / 100 ;ca = 200 ;
public static void main( ) throws …
// receive bs
// Calculation of gross salary
float bs, hra, ca, da, gs ;
if ( bs >= 1500 )da = bs * 95 / 100 ;hra = bs * 20 / 100 ;ca = bs * 12 / 100 ;
elseda = bs * 92 / 100 ;hra = bs * 15 / 100 ;ca = 200 ;
gs = bs + hra + da + ca ;System.out.println ( "Gross salary = Rs. " + gs ) ;
only this belongs to if block
only this belongs to else block
Tip: Hanging else not allowed
// Calculation of gross salary public static void main( ) throws Exception
float bs, hra, ca, da, gs ;// receive bsif ( bs >= 1500 )
da = … ; hra = ... ; ca = … ;else
da = … ; hra = ... ; ca = … ;gs = bs + da + hra + ca ;System.out.println ( "Gross salary = Rs " + gs ) ;
Correct Program
One More Formif ( condition )
statement1 ;statement2 ;
else
statement3 ;statement4 ;
Tip: - Default scope of if and else is onlythe next statement after them.
- To override the default scope use
Enterprise Solutions Using J2EE / Lecture 09 1
Decision Control Instructions - IIYashavant [email protected]
Objectives
Program – Leap year or notProgram – First day of any given yearNuances of Modulus OperatorNuances of Comparison Operator
Leap Year or Notclass LeapYear
public static void main( ) throws Exception
System.out.println ( "Enter year" ) ;// receive year
int y ;
…
0
4 1996 4991996
Leap
0
4 2000 5002000
Leap
0
4 1900 4751900
Not Leap
Enterprise Solutions Using J2EE / Lecture 09 2
if ( y % 100 == 0 )
if ( y % 400 == 0 )System.out.println ( "Leap" ) ;
elseSystem.out.println ( "Not Leap" ) ;
else
if ( y % 4 == 0 )System.out.println ( "Leap" ) ;
elseSystem.out.println ( "Not Leap" ) ;
Nested if-elsestatements are legal
class LeapYear
public static void main( ) throws Exception
int y ;// receive year
First Day of Any Yearclass FirstDay
public static void main( ) throws Exception
int y ;System.out.println ( "Enter year" ) ;// receive year. . .
2002
The Logic Behind It
………1/ 1/ 2002
1/ 1/ 1 Monday
15/ 1/ 1 Monday
22/ 1/ 1 Monday
29/ 1/ 1 Monday
?
8/ 1/ 1 Monday
1 /1 / 1 Monday29/ 1 / 1 ?
1/ 1/ 1 to 28/1 / 1
1/ 1/ 1 to 31/ 12/ 2001
28 % 7 0
? ? % 7
Enterprise Solutions Using J2EE / Lecture 09 3
class LeapYear
public static void main( ) throws Exception
System.out.println ( "Enter year" ) ;// receive year
totaldays = normaldays + leapdays ;firstday = totaldays % 7 ;if ( firstday == 0 )
System.out.println ( "Monday" ) ;.. .... ..
leapdays =( y - 1 ) / 4 - ( y - 1 ) / 100 + ( y - 1 ) / 400 ;
int y ;int firstday, normaldays, leapdays, totaldays ;
normaldays = ( y - 1 ) * 365 ;
1/ 1/ 1 to 28/ 1 / 1
28 % 7
0
1/ 1/ 1 to 31/ 12/ 2001
?
? % 7
Are You Sure?4 % 33 % 4
-3 % 43 % -4
-3 % -4
13-33-3
Tip: Sign of remainder is same as sign of numerator
int a = 5, b = 5, c = 5 ;if ( a == b == c )
printf ( "Hello" ) ;else
printf ( "Hi" ) ;
Error
Enterprise Solutions Using J2EE / Lecture 10 1
Logical OperatorsYashavant Kanetkar
Objectives
Nuances of decision control instructionWhat are logical operatorsWhen to use themHierarchy of operators
What Will Be The Outputpackage sample ;class Sample
public static void main( ) throws Exception
int a = 5, b = 10 ;if ( a >= 20 ) ;
b = 30 ;System.out.println ( b ) ;
; - Null statementDoesn’t do anything on execution
30
if ( a >= 20 );
b = 30 ;
Enterprise Solutions Using J2EE / Lecture 10 2
What Will Be The Output
package sample ;class Sample
public static void main( ) throws Exception
int a = 10 ;if ( a = 5 )
System.out.println ( "Hi" ) ;
Error – Boolean expression required
else
if ( per >= 40 )S.o.p ( "Third division" ) ;
elseS.o.p ( "Fail" ) ;
if ( per >= 60 )S.o.p ( "First division" ) ;
else
if ( per >= 50 )S.o.p ( "Second division" ) ;
int m1, m2, m3, m4, m5 ;
class Examination
public static void main( ) throws Exception
// receive m1, m2, m3, m4, m5per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;
int per ;
3 ProblemsMatching if - elseMatching Indentation Level
class Examination
public static void main( ) throws Exception
int m1, m2, m3, m4, m5, per ;// receive m1, m2, m3, m4, m5 per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;if ( per >= 60 )
System.out.println ( "First division" ) ;if ( per >= 50 )
System.out.println ( "Second division" ) ;if ( per >= 40 )
System.out.println ( "Third division" ) ;else
System.out.println ( "Fail" ) ;
Anything Wrong?
?
Enterprise Solutions Using J2EE / Lecture 10 3
class Examination
public static void main( ) throws Exception
int m1, m2, m3, m4, m5, per ;// receive mq, m2, m3, m4, m5per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;if ( per >= 60 )
S.o.println ( "First division" ) ;if ( per >= 50 && per < 60 )
S.o.println ( "Second division" ) ;if ( per >= 40 && per < 50 )
S.o.println ( "Third division" ) ;else
S.o.println ( "Fail" ) ;
Still Anything Wrong?
class Examination
public static void main( ) throws Exception
int m1, m2, m3, m4, m5, per ;// receive m1, m2, m3, m4, m5per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;if ( per >= 60 )
S.o.println ( "First division" ) ;if ( per >= 50 && per < 60 )
S.o.println ( "Second division" ) ;if ( per >= 40 && per < 50 )
S.o.println ( "Third division" ) ;if ( per < 40 )
S.o.println ( "Fail" ) ;
Is This Better?
class Examination
public static void main( ) throws Exception
int m1, m2, m3, m4, m5, per ;// receive m1, m2, m3, m4, m5per = ( m1 + m2 + m3 + m4 + m5 ) / 5 ;if ( per >= 60 )
S.o.p ( "First division" ) ;else if ( per >= 50 )
S.o.p ( "Second division" ) ;else if ( per >= 40 )
S.o.p ( "Third division" ) ;else
S.o.print ( "Fail" ) ;
One More Way
else is working for all three ifs
Enterprise Solutions Using J2EE / Lecture 10 4
Logical Operators
&& - And|| - Or! - Not
Useful in
Checking Ranges
Yes / No Problem
class Insurance
public static void main( ) throws Exception
int age ;System.out.printf ( "Enter age, sex, marital status" ) ;// receive age, s, msif ( ms == m )
S.o.p ( "Insured" ) ;else
if ( s == m )
if ( age > 30 )S.o.p ( "Insured" );
elseS.o.p ( "Not Ins." );
else
char s, ms ;
elseS.o.p ( "Not In." );
26 m u’ ’
’ ’
Not Insured
if ( age > 25 )S.o.p ( "Ins." ) ;
Using Logical Operatorsclass Insurance
public static void main( ) throws Exception
int age ;char s, ms ;S.o.println ( "Enter age, sex, marital status" ) ;// receive age, s, ms
if ( ms = = ’m’ ms = = ’u’ s = = ’m’ age > 30ms = = ’u’ s = = ’f’ age > 25 )
elseSystem.out.println ( "Insured" ) ;
system.out.println ( "Not Insured" ) ;
)(||
||( )
)(&&&&
&&&&
26 m u
Not Insured
Enterprise Solutions Using J2EE / Lecture 10 5
Working of && And ||
cond2cond1
True True
TrueTrue
False FalseFalseFalse
cond1 && cond2 cond1 || cond2
True TrueFalse FalseTrue FalseFalse True
Expression c2 goes to work if
boolean a ;int i = 7, j = 2 ;a = i < 5 && ++j > 6 ;System.out.print ( j ) ;
Short Circuit Operationsboolean a ;a = 2 && 3 ;
boolean a ;int i = 7, j = 2 ;a = i < 5 & ++j > 6 ;System.out.print ( j ) ;
2
3
c1 && c2 c1 & c2c1 || c2c1 | c2
c1 is trueAlwaysc1 is falseAlways
a = -3 + b - 5 ;
Hierarchy of OperatorsOperators Type
! Logical Not* / % Arithmetic
+ - Arithmetic< > <= >= Relational= = != Relational&& Logical And|| Logical Or= Assignment
Increasing Priority
Unary - Binary -
BinaryOperators
Enterprise Solutions Using J2EE / Lecture 11 1
Conditional OperatorsYashavant Kanetkar
Objectives
Working of && and ||Short circuit operationsVariations of decision control instructionWhat are conditional operatorsWhen to use them
Working of && And ||
cond2cond1
True True
TrueTrue
False FalseFalseFalse
cond1 && cond2 cond1 || cond2
True TrueFalse FalseTrue FalseFalse True
Enterprise Solutions Using J2EE / Lecture 11 2
Expression c2 goes to work if
boolean a ;int i = 7, j = 2 ;a = i < 5 && ++j > 6 ;System.out.print ( j ) ;
Short Circuit Operationsboolean a ;a = 2 && 3 ;
boolean a ;int i = 7, j = 2 ;a = i < 5 & ++j > 6 ;System.out.print ( j ) ;
2
3
c1 && c2 c1 & c2c1 || c2c1 | c2
c1 is trueAlwaysc1 is falseAlways
a = -3 + b - 5 ;
Hierarchy of OperatorsOperators Type
! Logical Not* / % Arithmetic
+ - Arithmetic< > <= >= Relational= = != Relational&& Logical And|| Logical Or= Assignment
Increasing Priority
Unary - Binary -
BinaryOperators
Exchanging Blocksclass Sample
public static void main( ) throws Exception
int a = 3, b = 4 ;
if ( a <= b )S.o.p ( "A" ) ;
elseS.o.p ( "B" ) ;
Output: A if ( )
S.o.p ( "B" ) ;else
S.o.p ( "A" ) ;
a > b
Or
Enterprise Solutions Using J2EE / Lecture 11 3
One More Wayclass Sample
public static void main( ) throws Exception
int a = 3, b = 4 ;if ( a <= b )
S.o.println ( "A" ) ;else
S.o.println ( "B" ) ;
Output: A
a <= b a !> b
if ( ! ( a > b ) )S.o.println ( "A" ) ;
elseS.o.println ( "B" ) ;
Or
class sample
public static void main( ) throws Exception
int a = 3, b = 4 ;if ( a > b )
S.o.println ( "B" ) ;else
S.o.println ( "A" ) ;
Output: A
Yet Another Way
Or
if ( ! ( a <= b ) )S.o.p ( "B" ) ;
elseS.o.p ( "A" ) ;
class Sample
public static void main( ) throws Exception
int a = 3, b = 4, c ;if ( a <= b )
c = 10 ;else
c = 20 ;
Cond. Operators
? : - Conditional operatorsOnly Ternary Operators
a <= b ? c = 10 : c = 20 ;
Or
c = a <= b ? 10 : 20 ;
Enterprise Solutions Using J2EE / Lecture 11 4
class Sample
public static void main( ) throws Exception
int a = 3, b = 4, c ;if ( a <= b )
c = 10 ;
How Would You Convert
Error
a <= b ? c = 10 ;
Remove The Error
a <= b ? c =10 : ;
a <= b ? c = 10 : ; ;
Soln: c = a <= b ? 10 : 0 ;
Terminator Null Statement
Dummy
Necessary
Would This Workint a = 2, b = 4, c, d ;d = a <= b ? c = 10 : c = 20 ;System.out.println ( d ) ;
int a = 2, b = 4 ;a <= b ? S.o.println ( "Hi" ) ; S.o.println ( "Bye" ) ;
expression1 ? expression2 : expression3 ;
int a = 2, b = 4, c ;c = a <= b ? 10 : 20.5 ;
of same type
Enterprise Solutions Using J2EE / Lecture 11 5
Moral of The StoryUse one, use anotherDummy expressionNot a replacement for if-else
Only 1 expression in ? partand one in : part
d = a <= b ? ( e = b > a ? 10 : 23 ): 20 ;
Nesting not allowed
Enterprise Solutions Using J2EE / Lecture 12 1
Conversions & ComparisonsYashavant [email protected]
Objectives
Conversion between int and floatConversion between char and floatRepresentation of ints and charsASCII codes and ASCII valuesComparison of real values
int z ;float d = 6.8f ;z = ( int ) d ;
float to intConversions
class Conversions
public static void main( ) throws Exception
int a = 10, b = 20 ;float c = 3.14f , d = 6.8f ;System.out.printf ( "%f %d", a, b ) ;System.out.printf ( "%d %d", c, d ) ;
Don’t use printf( ) for int to float or float to int conversionCarry out narrowing conversions using typecasting
float z ;int a = 10 ;z = a ;
int to float
Illegal format conversion exception
Enterprise Solutions Using J2EE / Lecture 12 2
class Conversions
public static void main( ) throws Exception
int i = 65, j = 90 ;char ch = ’A’, dh = ’Z’ ;System.out.printf ( "%d %d %c %c", i, j, ch, dh ) System.out.printf ( "%c %c", i, j ) ;System.out.printf ( "%d %d", ch, dh ) ;
Conversions Continued...
65 90 A Z
A Z
65 90
int to char conversions are reliablechar to int conversions are reliable
i a ch
int i = 65 ; float a = 3.14 ; char ch = ’A’ ;
01000001 0s & 1s 01000001
Binary Eqv. Binary Eqv. ASCII code
Representation
Same1 * 26 + 1 * 20
Every ASCII code is 8-bit code
S.o.printf ( "%d", ch ) ;
Methods Are Different
S.o.printf ( "%c", i ) ;
65
A
int i = 65 ;char ch = ’A’ ;
Only lower bytegets used
1 * 27 + 1 * 20
ch
Lowest00000000 01000001Highest
00000000 0100000100000000 00000000
i
Highest Lowest00000000 01000001
Enterprise Solutions Using J2EE / Lecture 12 3
Surprised?
float a = 0.7f ;if ( a < 0.7 )
S.o.printf ( "A" ) ;else
S.o.printf ( "B" ) ;
A float a = 5.375f ;if ( a < 5.375 )
S.o.printf ( "A" ) ;else
S.o.printf ( "B" ) ;
B365 0.7
Integer Double
Binary of A Float
Binary of 5.375
Binary of 0.7
<32 - bitRecurring binary equivalent of 0.7
64 - bitRecurring binary equivalent of 0.7
Recurring
Non-Recurring
Truncated after 32/64 bits
==32 - bitNon-Recurring binary of 5.375
64 - bitNon-Recurring binary of 5.375
Similar to 1.333 < 1.333333
Similar to 2.5 == 2.50000
Safetyfloat a = 0.7 ;if ( a < 0.7f )
S.o.p ( "A" ) ;else
S.o.p ( "B" ) ;
B
float a = 5.375 ;if ( a < 5.375f )
S.o.p ( "A" ) ;else
S.o.p ( "B" ) ;
double a = 0.7 ;if ( a < 0.7 )
S.o.p ( "A" ) ;else
S.o.p ( "B" ) ;
double a = 5.375 ;if ( a < 5.375 )
S.o.p ( "A" ) ;else
S.o.p ( "B" ) ;
B
B
B
Compare 2 floats or 2 doubles
Enterprise Solutions Using J2EE / Lecture 12 4
ASCII CodeCharacter Decimal
ASCII Codes
A 01000001B 01000010C 01000011D 01000100E 01000101.. ….
6566676869..
ASCII Values
Characters to be Represented26 Capital letters ( A- Z )26 Smallcase letters ( a - z )10 Digits ( 0 - 9 )32 Special Symbols ( + - * / . : ; etc. )34 Non-printable chars - control chars128 Graphic characters
256 Characters
00000000 To 11111111
ASCII Values26 Capital letters 26 Smallcase letters 10 Digits32 Special Symbols34 Non-printable chars128 Graphic characters
256 Characters
65 - 9097 - 12248 - 57
0 - 33128 - 255
0 - 25509 – Tab13 – Enter27 – Escape32 – Space
Enterprise Solutions Using J2EE / Lecture 13 1
Repetition Control Instruction
Yashavant [email protected]
ObjectivesRepetition Control InstructionGeneral form of whileIncrementation & Decrementation operatorsVariations of ++ and -- operators
Control Instructions
Decision - if - else- ? :- < > <= >= = = !=- && || !- & |
Repetition / Loop control instruction
Sequence
Enterprise Solutions Using J2EE / Lecture 13 2
To Begin With...
S.o.p ( "Simple interest = Rs " + si ) ;
class Loop
public static void main( ) throws Exception
S.o.p ( "Enter values of p, n, r" ) ;// receive valuessi = p * n * r / 100 ;
int p, n ;float r, si ;
Repetition...
S.o.p ( "Enter values of p, n, r" ) ;// receive valuessi = p * n * r / 100 ;S.o.p ( "Simple interest = Rs " + si ) ;
int p, n ; float r, si ;
while ( )
int i ; i = 1 ;
i <= 10
i = i + 1 ;
class Loop
public static void main( ) throws Exception
class Loop
public static void main( )
int i ;i = 1 ;while ( i <= 10 )
/* any logic */i = i + 1 ;
Logic Doesn’t Matter
// Initialisation of loop counter // Testing of loop counter
// Incrementation of loop counter
Loop counters can be int, long int, float or char
Loop counters can be incremented or decremented by any suitable step value
Loop Counter /Index variable
Enterprise Solutions Using J2EE / Lecture 13 3
Another Program// Print numbers from 1 to 10 class PrintNumbers
public static void main( ) throws Exception
int i = 1 ;while ( i <= 10 )
S.o.println ( i ) ;
i = i + 1 ;
i++ ;
Another way
++i ;
Another way
i = i + 1 i++i = i + 2 i+++i = i + 10 ?
++ Increases value of a variable by 1-- Decreases value of a variable by 1**//%%
Incrementation / Decrementation Operators
Don’t makesense
Tip : +++ doesn’t exist
Would This Worki = j---2 ; int i, j = 3 ;
i = --j ;i = --3 ;
i = j----2 ;i = j----2 ;
int i, j = 2, k = 3 ;i = ( j + k )++ ;
i = j-- - -2 ;
j = j - 1
3 = 3 - 1
j + k = j + k + 1
++ and - - can be done only on variables
CompulsoryOptional
i = j-- - 2 ;
Enterprise Solutions Using J2EE / Lecture 14 1
The while LoopYashavant Kanetkar
Objectives
Pre incrementation and Post incrementationNuances of while loopCompound Assignment OperatorsUsage of break keywordRunning sums and products
Is i++ Same As ++i
int i = 1 ;while ( i <= 10 )
S.o.p ( i++ ) ;
int i = 1 ;while ( i <= 10 )
S.o.p ( ++i ) ;
0<
1O/p: 2 3 4……9 10 2 3 4 5……9 10 11O/p:
1 st oper. - Printing2 nd oper. - Incr.
i++ ; ++i ;printf ( "%d", i++ ) ; printf ( "%d", ++i ) ;
1 st oper. - Printing2 nd oper. - Incr.
Enterprise Solutions Using J2EE / Lecture 14 2
Two More Ways
int i = 0 ;while ( i++ < 10 )
S.o.p ( i ) ;
int i = 0 ;while ( ++i <= 10 )
S.o.p ( i ) ;
1 st oper. - Testing2 nd oper. - Incr.
1 st oper. - Incr.2 nd oper. - Testing
Compare
int i = 1 ;while ( i <= 10 )
S.o.p ( i++ ) ;
int i = 0 ;while ( i < 10 )
S.o.p ( ++ i ) ;
int i = 0 ;while ( ++i <= 10 )
S.o.p ( i ) ;
int i = 0 ;while ( i++ < 10 )
S.o.p ( i ) ;
class PrintNum
public static void main( ) throws Exception
int i = 1 ;while ( i <= 10 )
S.o.p ( i ) ;i += 1 ;
Print Nos. From 1 to 10a = a * 10 ;
a *= 10 ;
b = b % 5 ;
b %= 5 ;
+= -= *= /= %= Compound Assignment Oper.
Same as i = i + 1 i++ ++i
Enterprise Solutions Using J2EE / Lecture 14 3
One More Wayclass PrintNum
public static void main( ) throws Exception
int i = 1 ;while ( true ) /* Repeat infinite times */
S.o.p ( i ) ;i++ ;
if ( i > 10 )break ;
Keyword
break - Terminates Loopexit( ) - Terminates Program
if ( i > 10 )System.exit( 1 ) ;
Reason for termination
Calculate
n!nΣ ii = 1
xn
1 * 2 * 3 * 4 *….n
1 + 2 + 3 + 4 +.…n
2 * 2 * 2 * 2 *….n
Running sum
Running product
Running product
s = s + ;
Running Sum & Products
ip = p * i ;pr = pr * 2 ;
s = 0 ; p = 1 ; pr = 1 ;
1 + 2 + 3 + 4 +.…n RS1 * 2 * 3 * 4 *….n RP2 * 2 * 2 * 2 *….n RP
class SumProds
public static void main( ) throws Ex..
// receive nint s, p, pr, i, n ;
i = 1 ;while ( i <= n )
i++ ;
S.o.p ( s + " " + p + " " + pr ) ;
i s1 0
123364105156
5
Enterprise Solutions Using J2EE / Lecture 15 1
The for LoopYashavant Kanetkar
Objectives
Sum of SeriesWorking of for loopComparison of while and for loopVariations of for loop
x1 x3 x5 x7 x9— - — + — - — + — - …………10 terms1! 3! 5! 7! 9!
main( )
// receive x
while ( i <= 10 ) calculate numerator
calculate denominatorterm = numerator / denominatorAdd / subtract alternate terms to/from s
i = 1 ; s = 0 ;
i++ ;print ( s ) ;
Enterprise Solutions Using J2EE / Lecture 15 2
class Series
public static void main( ) throws Exception
// receive xi = 1 ;while ( i <= 10 )
S.o.println ( s ) ;
i++ ; j = j + 2 ;s = ( i % 2 == 0 ) ? s - t : s + t ;
while ( k <= j )
d = d * k ; n = n * x ; k++ ;
k = n = d = 1 ;
t = n / d ;
float x, s, n, d, t ; int i, j, k, n ; x1 x3 x5 .. — - — + — -1! 3! 5! s = 0 ;
j = 1 ;
while ( i <= n - 1 )
if ( n % i == 0 )
S.o.p ( "Not a prime number" ) ;
i++ ;
class PrimeNumber
public static void main( ) throws Exception
int n ;S.o.p ( "Enter a num." ) ;// receive n
if ( i == n )
break ;
S.o.p ( "Prime number" ) ;
13
Prime No.
13
2 3 4 .. .. .. 12
int i = 2 ;
Loop Control Instructionswhilefordo-while
Enterprise Solutions Using J2EE / Lecture 15 3
The while Loopclass WhileLoop
public static void main( ) throws Exception
int m1, m2, m3, avg, i ;i = 1 ;while ( i <= 10 )
// receive m1, m2, m3avg = ( m1 +m2 + m3 ) / 3 ;S.o.p ( avg ) ;i++ ;
Init Test IncrTestTest
IncrIncr
Test Incr.. .... ..
Init Test IncrTestTest
IncrIncr
Test Incr.. .... ..
class ForLoop
public static void main( ) throws Exception
int m1, m2, m3, avg, i ;
// receive m1, m2, m3avg = ( m1 + m2 + m3 ) / 3 ;S.o.p ( avg ) ;
( )
The for Loop
for i++i = 1 ; i <= 10 ;
Comparision - I
int i = 1 ;while ( i <= 10 )
statement1 ;statement2 ;statement3 ;i++ ;
int i ;for ( i = 1 ; i <= 10 ; i++ )
statement1 ;statement2 ;statement3 ;
Finite LoopInfinite Loop
Enterprise Solutions Using J2EE / Lecture 15 4
Comparison II
int i = 1 ;while ( i <= 10 ) ;
statement1 ;statement2 ;statement3 ;i++ ;
int i ;for ( i = 1 ; i <= 10 ; i++ ) ;
statement1 ;statement2 ;statement3 ;
Finite LoopInfinite Loop
Comparison IIIint i = 1 ;while ( )
statement1 ;statement2 ;statement3 ;
int i = 1 ;for ( ; ; )
statement1 ;statement2 ;statement3 ;
Infinite LoopError
Print Nos. From 1 to 10
class PrintNumbers
public static void main( ) throws Exception
int i ;for ( i = 1 ; i <= 10 ; i++ )
S.o.p ( i ) ;
Or i = i + 1 i++ ++i
Enterprise Solutions Using J2EE / Lecture 15 5
Infinite loop
Dropping Init./Incr./Cond.int i = 1 ;for ( ; i <= 10 ; i++ )
S.o.p ( i ) ;
int i = 1 ;for ( ; i <= 10 ; )
S.o.p ( i ) ;i++ ;
int i = 1 ;for ( ; ; )
S.o.p ( i ) ;i++ ;
if ( i > 10 )break ;
S.o.p ( i++ ) ;
if ( ++i > 10 )
; ; Necessary
Enterprise Solutions Using J2EE / Lecture 16 1
More for LoopsYashavant [email protected]
ObjectivesNested for loopsUsage of break and continueMultiple initialisations in for loop
1 1 1
1 1 2
1 1 3
1 3 11 3 21 3 3
1 2 11 2 21 2 3
3 1 1
3 1 2
3 1 3
3 2 1
3 2 2
3 2 3
3 3 1
3 3 2
3 3 3
2 1 1
2 1 2
2 1 3
2 2 1
2 2 2
2 2 3
2 3 1
2 3 2
2 3 3
Combinations
Enterprise Solutions Using J2EE / Lecture 16 2
1 1 11 1 21 1 3
1 3 1
1 3 2
1 3 3
1 2 1
1 2 2
1 2 3
i = 1 ;j = 1 ;for ( k = 1 ; k <= 3 ; k++ )
S.o.p ( i + " " + j + " " + k ) ;
class Combinations
public static void main( ) throws Exception
int i, j, k ;
Starting Off...i j k
class Combinations
public static void main( ) throws Exception
int i, j, k ;i = 1 ;
for ( k = 1 ; k <= 3 ; k++ )S.o.p ( i + " " + j + " " + k ) ;
for ( j = 1 ; j <= 3 ; j++ )
Adding One More Loop
1 1 11 1 21 1 3
1 3 1
1 3 2
1 3 3
1 2 1
1 2 2
1 2 3
i j k
class Combinations
public static void main( ) throws Exception
int i, j, k ;
for ( j = 1 ; j <= 3 ; j ++ )
for ( k = 1 ; k <= 3 ; k++ )S.o.p ( i + " " + j + " " + k ) ;
for ( i = 1 ; i <= 3 ; i ++ )
1 1 1.. .. .... .. ..1 3 3
2 1 1.. .. .... .. ..2 3 3
3 1 1.. .. .... .. ..3 3 3
Finishing Off...
Enterprise Solutions Using J2EE / Lecture 16 3
Unique Combinationsclass Combinations
public static void main( ) throws Exception
int i, j, k ;for ( i = 1 ; i <= 3 ; i++ )
for ( j = 1 ; j <= 3 ; j++ )
for ( k = 1 ; k <= 3 ; k++ )
S.o.p ( i + " " + j + " " + k ) ;
.. .. ..1 2 3.. .. ..1 3 2
.. .. ..2 1 3.. .. ..2 3 1
.. .. ..3 1 2.. .. ..3 2 1
if ( i != j && j != k && k != i )
if ( i != j != k )printf ( "%d %d %d", i, j, k ) ;
class Combinations
public static void main( ) throws Exception
int i, j, k ;for ( i = 1 ; i <= 3 ; i++ )
for ( j = 1 ; j <= 3 ; j++ )
for ( k = 1 ; k <= 3 ; k++ )
S.o.p ( i + " " + j + " " + k ) ;
One More Way
i j k
1 1 1
2 1
13
if ( i = = j || j = = k || k = = i )
elsebreak ;
class Combinations
public static void main( ) throws Exception
int i, j, k ;for ( i = 1 ; i <= 3 ; i++ )
for ( j = 1 ; j <= 3 ; j++ )
for ( k = 1 ; k <= 3 ; k++ )
S.o.p ( i + " " + j + " " + k ) ;
The Correct Wayi j k1 1 1
23
123
24
if ( i = = j || j = = k || k = = i )
elsecontinue ;
Enterprise Solutions Using J2EE / Lecture 16 4
Alternate Wayclass Combinations
public static void main( ) throws Exception
int i, j, k ;for ( i = 1 ; i <= 3 ; i++ )
for ( j = 1 ; j <= 3 ; j++ )
for ( k = 1 ; k <= 3 ; k++ )
S.o.p ( i + " " + j + " " + k ) ;
if ( i = = j || j = = k || k = = i )
elsecontinue ;
for ( .. ; .. ; k++ )
if ( condition )continue ;
elsea = 2 ;
S.o.p ( "Hello" ) ;
Would ; be OK?
coninue abandons rest of the instructions in the loop
Multiple Initializationsint i, j, k ;i = 1 ; j = 3 ;for ( k = 1 ; k <= 5 ; k++ )
……i += 2 ;j *= 4 ;
for ( i = 1, j = 3, k = 1 ; k <= 5 ; i += 2, j *= 4 )
……
MultipleConditions?
Can I Drop k++
Connect using && and ||
Better Way
Enterprise Solutions Using J2EE / Lecture 17 1
do while LoopsYashavant Kanetkar
ObjectivesFlexible declarationsSophisticated break and continuedo-while LoopEffects of break / continue on different loopsRepeating unknown number of times
Flexible Declarationsclass Myscope
public static void main ( String args[ ] )
for ( int i = 0 ; i < 3 ; i++ )
System.out.println ( i ) ;System.out.println ( i ) ;
Enterprise Solutions Using J2EE / Lecture 17 2
Sophisticated breakclass Mybreak
public static void main ( String args[ ] )
for ( int i = 0 ; i < 3 ; i++ )
for ( int j = 0 ; j < 4 ; j++ )
for ( int k = 0 ; k <= 5 ; k++ )
……if ( i + j + k > 21 % 4 )
break ;
first : for ( int i = 0 ; i < 3 ; i++ )
break first ;
Sophisticated continueclass Mycontinue
public static void main ( String args[ ] )
for ( int i = 0 ; i < 3 ; i++ )
for ( int j = 0 ; j < 4 ; j++ )
for ( int k = 0 ; k <= 5 ; k++ )
……if ( i + j + k > 21 % 4 )
continue ;
first : for ( int i = 0 ; i < 3 ; i++ )
continue first ;
Type of Loops
whilefordo - while
Enterprise Solutions Using J2EE / Lecture 17 3
The do-while Loopclass Loop
public static void main( ) throws Exception
int i = 1 ;do
System.out.println ( i ) ;i++ ;
while ( i <= 10 ) ;
Tip1: - NecessaryTip2: ; after while - Necessary
Compare
do
S.o.p ( "Hi" ) ; while ( 4 < 1 ) ;
for ( ; 4 < 1 ; )S.o.p ( "Hi" ) ;
while ( 4 < 1 )S.o.p ( "Hi" ) ;
Hi No output No output
while ( …. )
if ( cond1 )break ;
if ( cond2 )continue ;
for ( .. ; .. ;… )if ( cond1 )
break ;if ( cond2 )
continue ;
do
if ( cond1 )break ;
if ( cond2 )continue ;
while ( …. ) ;
Effects of break & continue
if ( cond )
..
..break ;..
if ( cond )
..
..continue ;..
for ( .. ; .. ; .. )
..
..break ;..
for ( .. ; .. ; .. )
..
..continue ;..
Enterprise Solutions Using J2EE / Lecture 17 4
while ( )
Unknown No. of Times
char ch = ’y’ ;ch == ’y’
class Unknown
public static void main( ) throws Exception
/* some logic */System.out.println ( "Continue y / n" ) ;// receive ch
Try writing same using for / do - while
Foolproof?
while ( ch == ’y’ || ch == ’Y’ )
Enterprise Solutions Using J2EE / Lecture 18 1
case Control InstructionYashavant Kanetkar
Objectivescase Control InstructionNuances of case Control InstructionVariations of case Control Instruction
Control InstructionsSequence DecisionRepetition
- while, for, do-whilebreak, continue
- ++ --- += -= *= /= %=
Case
Enterprise Solutions Using J2EE / Lecture 18 2
class Example
public static void main( ) throws Exception
int n ;S.o.p ( "Enter no. between 1 and 3" ) ;// receive n if ( n = = 1 )
S.o.p ( "You entered 1" ) ;else
if ( n = = 2 )S.o.p ( "You entered 2" ) ;
else
if ( n = = 3 )S.o.p ( "You entered 3" ) ;
elseS.o.p ( "Wrong choice" ) ;
Three Problems
Alternatives- Use &&, II- Use case CI
class Example
public static void main( ) throws Exception
int n ; S.o.p ( "Enter no. between 1 and 3" ) ;// receive n
case 1 :
S.o.p ( "You Entered 1" ) ;case 2 :
S.o.p ( "You Entered 2" ) ;case 3 :
S.o.p ( "You Entered 3" ) ;else
S.o.p ( "Wrong Choice" ) ;
switch ( n )
If a case fails control jumps
to the next case
class Example
public static void main( ) throws Exception
int n ; S.o.p ( "Enter no. between 1 and 3" ) ;// receive n
case 1 :
S.o.p ( "You entered 1" ) ;case 2 :
S.o.p ( "You entered 2" ) ;case 3 :
S.o.p ( "You entered 3" ) ;
switch ( n )
default :S.o.p ( "Wrong Choice" ) ;
2
Output:You entered 2
Enterprise Solutions Using J2EE / Lecture 18 3
class Example
public static void main( ) throws Exception
int n ;// receive nswitch ( n )
case 1 : S.o.p ( "You entered 1" ) ;
case 2 :S.o.p ( "You entered 2" ) ;
case 3 :S.o.p ( "You entered 3" ) ;
default : S.o.p ( "Wrong choice" ) ;
Tip: If a case is satisfied all statements below it upto of switch are executed
Output:You entered 2You entered 3Wrong choice
2
class Example
public static void main( ) throws Exception
int n ;// receive nswitch ( n )
case 1 :S.o.p ( "You Entered 1" ) ;
case 2 :S.o.p ( "You Entered 2" ) ;
case 3 :S.o.p ( "You Entered 3" ) ;
default : S.o.p ( "Wrong choice" ) ;
The Solution
break ;
break ;
break ;
2
- break terminates a switch- are optional even if there are
multiple statements in a case
class Example
public static void main( ) throws Exception
int n ;// receive nswitch ( n )
case 1 :S.o.p ( "You Entered 1" ) ; break ;
case 2 :S.o.p ( "You Entered 2" ) ; continue ;
case 3 :S.o.p ( "You Entered 3" ) ; break ;
default : S.o.p ( "Wrong choice" ) ;
What If continue
2break - Loops, switchcontinue - Loops
Illegal
Enterprise Solutions Using J2EE / Lecture 18 4
class Example
public static void main( ) throws Exception
int n ;// receive n switch ( n )
case 2 :S.o.p ( "You Entered 2" ) ; break ;
case 1 : S.o.p ( "You Entered 1" ) ; break ;
case 3 : S.o.p ( "You Entered 3" ) ; break ;
default :S.o.p ( "Wrong choice" ) ;
Tip: Order of cases is unimportant
class Example
public static void main( ) throws Exception
int n ;// receive nswitch ( n )
default : S.o.p ( "Wrong choice" ) ;
case 2 :S.o.p ( "You Entered 2" ) ; break ;
case 1 : S.o.p ( "You Entered 1" ) ; break ;
case 3 : S.o.p ( "You Entered 3" ) ; break ;
Tip: Even default can bethe very first case
break ;
class Example
public static void main( ) throws Exception
int n ;// receive nswitch ( n )
case 2 :S.o.p ( "You Entered 2" ) ; break ;
case 1 : S.o.p ( "You Entered 1" ) ; break ;
case 3 : S.o.p ( "You Entered 1" ) ;
Tip: default case is optional
Enterprise Solutions Using J2EE / Lecture 19 1
Nuances Of caseControl Instruction
Yashavant [email protected]
Objectives
Nuances of case Control InstructionGeneral form What all can be checkedMenu driven programs
class Example
public static void main( ) throws Exception
char ch ;S.o.p ( "Enter alphabet between A and C" ) ;// receive chch = str.charAt ( 0 ) ;switch ( ch )
case 'A' :S.o.p ( "You entered A" ) ; break ;
case 'B' :S.o.p ( "You entered B" ) ; break ;
case 'C' :S.o.p ( "You entered C" ) ; break ;
What if ‘a’, ‘b’, ‘c’
Enterprise Solutions Using J2EE / Lecture 19 2
class Example
public static void main( ) throws Exception
char ch ;S.o.p ( "Enter alphabet between A and C" ) ;// receive chswitch ( ch )
case 'A' || 'a' : S.o.p ( "You entered A" ) ; break ;
case ’B’ || ’b’ :S.o.p ( "You entered B" ) ; break ;
case ’C’ || ’c’ :S.o.p ( "You entered C" ) ; break ;
Error
class Example
public static void main( ) throws Exception
char ch ;S.o.p ( "Enter alphabet between A and C" ) ;// receive chswitch ( ch )
case ’A’ :S.o.p ( "Entered A" ) ; break ;
case ’B’ :S.o.p ( "Entered B" ) ; break ;
case ’C’ :S.o.p ( "Entered C" ) ; break ;
switch ( ch )
case 23 :case 4 :case -55 :
S.o.p ( ".." ) ;break ;
Acase ’a’ :
case ’b’ :
case ’c’ :
a
Case Conversion not useful for numbers
int n = 2 ;int a = 1, b = 2 ;switch ( n )
case a :…
case b :…
case 3 :…
Would This Work
Enterprise Solutions Using J2EE / Lecture 19 3
n + 3 / a + 24 + 3 / 5 + 2
3 + 2 % 5a + b % c
General Form
switch ( expression )
case constant expression :…
case constant expression :…
case constant expression :…
default : …
Checking switch
intcharlong intfloatdouble
Is switch a replacement for if ?
Which worksfaster ?
class Menu
public static void main( ) throws Exception
S.o.p ( "1. Odd / Even" ) ;S.o.p ( "2. Leap year" ) ;S.o.p ( "3. Prime number" ) ;S.o.p ( "0. Exit" ) ;S.o.p ( "Your choice?" ) ;// receive choice.. ..
int choice ;1. Odd / Even2. Leap Year3. Prime No.0. ExitYour Choice?
Menu Management
Enterprise Solutions Using J2EE / Lecture 19 4
class Menu
public static void main( ) throws Exception
int choice ;// display menu // receive choice
switch ( choice )
case 1 : // odd / even logicbreak ;
case 2 :// leap year logicbreak ;
default :S.o.p ( "wc" ) ;
case 3 ://prime no. logicbreak ;
case 0 :break ;
Odd / Even logicoddeven.java
Ctrl C, Ctrl V
No while, No Menu
while ( 1 )
/*display menu*/// receive choice switch ( choice )
case 1 :…break ;
case 0 :break ;
class Menu
public static void main( ) throws Exception
int choice ;
System.Exit ( 1 ) ;
RequirementsInfinite whileswitch
Conclusion
Any logic can be programmed using: SequenceDecisionRepetitionCase
Enterprise Solutions Using J2EE / Lecture 20 1
FunctionsYashavant Kanetkar
ObjectivesWhat are functionsProgram with multiple functionsHow to define functionsHow to call functionsDifferent types of function calls
Functionsclass Functions
public static void main( )
S.o.p ( "\n I am in main" ) ;public static void bombay( )
S.o.p ( "\n I am in Bombay" ) ;
public static void kanpur( )
S.o.p ( "\n I am in Kanpur" ) ;
Output:I am in main
main( )println( )print( )printf( )exit( )for( )while( )if( )switch( )
Functions
Enterprise Solutions Using J2EE / Lecture 20 2
Calling Functions
public static void main( )
S.o.p ( "\n I am in main" ) ;
public static void bombay( )
S.o.p ( "\n I am in Bombay" ) ;public static void kanpur( )
S.o.p ( "\n I am in Kanpur" ) ;
I am in mainI am in BombayI am in Kanpur
bombay( ) ; kanpur( ) ;
Output :
Function Call
Function Def.
class Functions
Types of Functions
printf( )println( )print( )exit( )
kanpur( )bombay( )main( )
Std. LibraryReady-made
User-definedDefined by us
TipsA Java program can contain one or more classes
Each class can contain multiple functions
Execution always begins with main( ) of Main class
One of the class has to be marked as Main class
Enterprise Solutions Using J2EE / Lecture 20 3
Nobody is Nobody’s Boss
public static void kanpur( )
S.o.p ( "\n I am in Kanpur" ) ; bombay( ) ;
class Functions
public static void main( )
S.o.p ( "\n I am in main" ) ;bombay( ) ; kanpur( ) ;
public static void bombay( )
S.o.p ( "\n I am in Bombay" ) ;kanpur( ) ;
Any function can callany other function
Order, Order !class Functions
public static void bombay( )
S.o.p ( "\n I am in Bombay" ) ;public static void main( )
S.o.p ( "I am in main" ) ;bombay( ) ;
Tip: Functions can bedefined in any order
More Calls, More Billsclass Functions
public static void main( )
int i ;S.o.p ( "\n In main" ) ;for ( i = 1 ; i <= 20 ; i++ )
bombay( ) ;public static void bombay( )
S.o.p ( "\nIn Bombay" ) ;
Tip: More the calls, slower the execution
class Functions
public static void main( )
int i ;S.o.p ( "\n In main" ) ;bombay( ) ;
public static void bombay( )
for ( i = 1 ; i <= 20 ; i++ ) S.o.p ( "\nIn Bombay" ) ;
Better
Enterprise Solutions Using J2EE / Lecture 20 4
Types of Calls// pr1.javapublic static void main( )
bombay( ) ;main( ) ;fun1( ) ;fun2( ) ;
public static void bombay( )
S.o.p ( "\n In Bombay" ) ;
// pr2.javapublic static void fun1( )
..
..
..
// pr3.java on m/c Alpha public static void fun2( )
..
..
HH
Local Call - Recursive Call. Process - RecursionSTD call - Calling function in another fileISD Call - Calling function in another m/c
Happy Hours - Calling function in same file
ISD
STDLC
Enterprise Solutions Using J2EE / Lecture 21 1
Communication Using Functions
Yashavant [email protected]
ObjectivesHow to communicate between functionsPassing values and controlReturning value and controlReturning multiple values from a function
Communicationclass Communication
public static void main( )
int a = 10, b = 20, c = 30 ;calsum( ) ;System.out.println ( s ) ;
public static void calsum( )
int a, b, c, s ;
int s ;
System.out.println ( s ) ;s = a + b + c ;
0
0
Enterprise Solutions Using J2EE / Lecture 21 2
class Communication
public static void main( )
int a = 10, b = 20, c = 30 ; int s ; calsum ( ) ;System.out.println ( s ) ;
public static void calsum ( )
int s ;
System.out.println ( s ) ;s = x + y + z ;
a, b, c
int x, int y, int z
Passing Values
60
Actual & Formal args must match in Number, Order and Type
ActualArguments
Formal Arguments
0
class Communication
public static void main( )
int a = 10, b = 20, c = 30, s ; calsum ( a, b, c ) ;
public static int calsum ( int x, int y, int z )
int ss ;ss = x + y + z ;return ( ss ) ;
S.o.p ( s ) ;
Returning Values
60
return ( ss ) ;return ( 60 ) ;return ( x + y + z ) ;
return ; Returns only control
Returns only value
s = calsum ( a, b, c ) ; Return control and value
x = calsum ( a, 25, d ) ;calsum ( 10 + 2, 25 % 3, d ) ;calsum ( a, calsum ( 25, 10, 4 ), d ) ;d = calsum ( a, 25, d ) * calsum ( a, 25, d ) + 23 ;
Are These Calls OK?
public static int calsum ( int x, int y, int z )
int ss ;ss = x + y + z ;return ( ss ) ;
• Actual arguments - constants / variables / expressions• Formal arguments - variables• Nested calls are legal• Call within an expression is legal
Returned value can be ignored
Enterprise Solutions Using J2EE / Lecture 21 3
class ReturnTwo
public static void main( )
int a = 10, b = 20, c = 30 ;
S.o.p ( s + " " + p ) ;int sumprod ( )int x, int y, int z
ss = x + y + z ;pp = x * y * z ;
sumprod ( a, b, c ) ; s, p = sumprod ( a, b, c ) ;
int ss, pp ;
return ( ss, pp ) ;
Returning More Than 1 Value
int s, p ;
A function can return only 1 value at a time
class ReturnTwo
public static void main( )
int a = 10, b = 20, c = 30 ;int s, p ; s = sumprod ( a, b, c ) ;p = sumprod ( a, b, c ) ;System.out.println ( s + " " + p ) ;
public static int sumprod ( int x, int y, int z )
ss = x + y + z ;pp = x * y * z ;return ( ss ) ;return ( pp ) ;
int ss, pp ;
One More Try
60 60
Redundant
class ReturnTwo
public static void main( )
int a = 10, b = 20, c = 30 ; int s, p ; s = sumprod ( a, b, c ) ;p = sumprod ( a, b, c ) ;System.out.println ( s + " " + p ) ;
, 1, 2
public static int sumprod ( int x, int y, int z, )
ss = x + y + z ; pp = x * y * z ;int ss, pp ;
int code
if ( code == 1 ) return ( ss ) ;
elsereturn ( pp ) ;
The Only Way Out
Sum, Product,Average, VarianceStandard Deviation
60 6000
Enterprise Solutions Using J2EE / Lecture 21 4
A Better Waypublic static int sumprod ( int x, int y, int z, int code )
ss = x + y + z ;pp = x * y * z ;
int ss, pp ;
if ( code == 1 ) return ( ss ) ;
elsereturn ( pp ) ;
code == 1 ? return ( x + y + z ) : return ( x * y * z ) ;
return ( code == 1 ? x + y + z : x * y * z ) ;
Enterprise Solutions Using J2EE / Lecture 21 1
More About FunctionsYashavant [email protected]
ObjectivesExamples of functionsReturning a non-integer valueDifferent return typesBeyond basic Arithmetic
public static void main( ) throws Exception
S.o.println ( "Enter year" ) ;// receive y
int y ;
romanize ( y ) ;public static void romanize ( int yy )
int n, i ;n = yy / 1000 ;for ( i = 1 ; i <= n ; i ++ )
S.o. println ( "m" ) ;
Decimal Roman1000 m
500 d100 c
50 l10 x
5 v1 i
Roman Equivalent1998 m d c c c c l x x x x i i i
1998
v class RomanEqu
Enterprise Solutions Using J2EE / Lecture 21 2
public static void romanize ( int yy )
romanize ( y ) ;
class RomanEqu
public static void main( ) throws Exception
S.o.println ( "Enter year" ) ;// receive y
int y ;
int n, i ;n = yy / j ;for ( i = 1 ; i <= n ; i ++ )
S.o.println ( ) ;
ch
, int j , char ch
return ( yy % j ) ;
, 1000 , ’m’
General Call
y = romanise ( y, 1000, ’m’ ) ;
int
y = romanise ( y, 500, ’d’ ) ;y = romanise ( y, 100, ’c’ ) ;y = romanise ( y, 50, ’l’ ) ;y = romanise ( y, 10, ’x’ ) ;y = romanise ( y, 5, ’v’ ) ;romanise ( y, 1, ’i’ ) ;
, int j , char ch
public static void main( ) throws Exception
..., ’m’
public static int romanize ( int yy )
int n, i ;n = yy / j ;for ( i = 1 ; i <= n ; i ++ )
System.out.println ( ch ) ;return ( yy % j ) ;
y = romanise ( y, 1000 ) ;1998 m d c c c c l x x x x i i i v
Error:Cannot find symbol
seWorks
public static float square ( float x )
b = square ( 2.5f ) ;c = square ( 1.5f ) ;S.o.p ( a + " " + b + " " + c ) ;
a = square ( 2.0f ) ;
Returning a Non-Intclass SquareNum
public static void main( )
float y ;y = x * x ;return ( y ) ;
4.0 6.25 2.25
float a, b, c ;
FunctionCall
FunctionDefinition
Enterprise Solutions Using J2EE / Lecture 21 3
Return Types
Error
Nothing isreturned
Error
Error
public class PrePost
public static void main ( String[ ] args )
int i = 3 ;
S.o.printf ( "%d %d", ++i, i ) ;S.o.printf ( "%d %d", i, ++i ) ;
4 5
Output?
4 4
Beyond Basic Arithmeticjava.lang package contains a Math classMath class contains methods and constantsTypes of methods
Basic methodsExponential and logarithmic methodsTrignometric methods
Enterprise Solutions Using J2EE / Lecture 21 4
public class MathFunctions
public static void main ( String[ ] args )
double a = -792.735, b = 43.74 ;int i = 15, j = 45;
S.o.p ( Math.abs ( a ) ) ;S.o.p ( Math.ceil ( b ) ) ;S.o.p ( Math.floor ( b ) ) ;S.o.p ( Math.rint ( b ) ) ;S.o.p ( Math.max ( i, j ) ) ; S.o.p ( Math.min ( i, j ) ) ;
Basic Arithmetic Functions
792.73544.043.044.04515
public class ExpLogFunctions
public static void main ( String[ ] args )
double a = 3 ;double b = 2 ;
S.o.p ( Math.E ) ;S.o.p ( Math.exp ( a ) ) ;S.o.p ( Math.log ( a ) ) ;S.o.p ( Math.pow ( a, b ) ) ;S.o.p ( Math.sqrt ( a ) ) ;
Exp and Log Functions
2.71828182845904520.0855369231876681.09861228866810989.01.7320508075688772
public class TrigFunctions
public static void main ( String[ ] args )
double d = 45.0 ;double r = Math.torad ( d ) ;
S.o.p ( Math.PI ) ;S.o.p ( Math.sin ( r ) ) ;S.o.p ( Math.cos ( r ) ) ;S.o.p ( Math.tan ( r ) ) ;S.o.p ( Math.toDegrees ( Math.asin ( Math.sin ( r ) ) ) ) ;S.o.p ( Math.toDegrees ( Math.acos ( Math.cos ( r ) ) ) ) ;S.o.p ( Math.toDegrees ( Math.atan ( Math.tan ( r ) ) ) ) ;
Trignometric Functions
3.1415926535897930.70710678118654750.7071067811865476145.045.045.0
Enterprise Solutions Using J2EE / Lecture 21 5
public class RandomNum
public static void main ( String[ ] args )
int num ;num = ( int ) ( Math.Random( ) * 20 ) ;S.o.p ( num ) ;num = 50 + ( int ) ( Math.Random( ) * 10 ) ;S.o.p ( num ) ;
Random Numbers
357
Enterprise Solutions Using J2EE / Lecture 23 1
RecursionYashavant Kanetkar
ObjectivesWhat is Recursion
Programs using Recursion
Pros and Cons of using Recursion
When to use it
Recursion – Different Forms
class Recursion
public static void main( )
fun( ) ;public static void fun( )
System.out.printf ( "Hi" ) ;fun( ) ;
Infinite Loop
Stops when Stack overflow occurs
Enterprise Solutions Using J2EE / Lecture 23 2
More Generalclass SumOfDigits
public static void main( ) throws Exception
int num, sum ;S.o.p ( "Enter a number" ) ;// receive num
public static int sumdig ( int n )
int d ; int s = 0 ; while ( )
n != 0
d = n % 10 ; n = n / 10 ; s = s + d ;return ( s ) ;
31698d5
485d3
n s d327 0 732 7 23 9 30 12
sum = sumdig ( num ) ;S.o.p ( sum ) ; 12
327
class SumOfDigits
public static void main( ) throws Exception
S.o.p ( "Enter a number" ) ;// receive num
int num, sum ;
int rsum ( int n )
int d ; int s ; if ( )
n != 0
d = n % 10 ; s = d + rsum ( n ) ; n = n / 10 ;else
return ( 0 ) ; return ( s ) ;
327sum = rsum ( num ) ;S.o.p ( sum ) ;
4!
4 * 3 * 2 * 1
4 * 3 !
3 * 2 !
2 * 1 !
1 * 0 !
Fresh set of variables are born during each callVariables die when control returns
if ( )
n != 0d =
s =n =
else
return ( 0 ) ; return ( s ) ;
int rsum ( int n )
int rsum ( int n )
if ( )
n != 0d =
s =n =
else
return ( 0 ) ; return ( s ) ;
int rsum ( int n )
if ( )
n != 0d =
s =n =
else
return ( 0 ) ; return ( s ) ;
327 % 10 ;327 / 10 ;7 + rsum ( 32 ) ;
int rsum ( int n )
if ( )
n != 0d =
s =n =
else
return ( 0 ) ; return ( s ) ;
32 % 10 ;32 / 10 ;2 + rsum ( 3 ) ;
3 % 10 ;3 / 10 ;3 + rsum ( 0 ) ;
327
Enterprise Solutions Using J2EE / Lecture 23 3
Factorial Valueclass FactorialOfNum
public static void main( ) throws Exception
System.out.printf ( "Enter a number" ) ;// receive num
int num, fact ;
fact = factorial ( num ) ;S.o.p ( fact ) ;
public static int factorial ( int n )
int p = 1 ; while ( )
n != 0
p = p * n ; n-- ;
return ( p ) ;
Recursive Fact. class FactorialOfNum
public static void main( ) throws Exception
S.o.p ( "Enter no." ) ;// receive num
int num, fact ;
fact = refact ( num ) ;S.o.p ( fact ) ;
public static int refact ( int n )
int p ; if ( )n != 0
p = n * refact ( n - 1 ) ;
return ( p ) ;
elsereturn ( 1 ) ;
Recursion TipsMake recursive call in an ifelse block is escape routeelse contains end cond. logicreturn may not be presentToo many calls – Stack FullAdv. - Ease Speed
Difficult to:UnderstandExplainWrite aboutMaintain
Enterprise Solutions Using J2EE / Lecture 23 4
Peg A Peg B Peg C
3 ! + 1
A B CA to C
A B CA to B
A B CC to B
A B CA to C B to A
A B C
B to CA B C
A to CA B C
Enterprise Solutions Using J2EE / Lecture 24 1
Object Oriented Programming
Yashavant [email protected]
Objectives
What is object-oriented programmingHow OO model applies to programmingDifference between class and object How to create classes and objectsHow to use objects
What is this?It is a vehicle It is my bike Object may contain other objects
Engine, Gearbox, Brake, Lights
Contents
Real-World Model
DataOil Temp.Oil densityRPMTiming detailsType of fuel
FunctionsIgniting fuelMoving pistonOpening valvesEjecting burnt fuelRotating crank
PropertiesProcedures
GenericClass
SpecificObject
Enterprise Solutions Using J2EE / Lecture 24 2
DateTime Class
More Classes and Objects
Datadd, mm, yyh, m, s
Functionsgetdate( )gettime( )setdate( )settime( )
Object d1- 13/12/2007- 12:25:30sd( ), gd( ), …
Object d2- 10/02/2009- 11:10:15sd( ), gd( ), …
Pop
Top
1020
Working Of Stack
EmptyTop
Push 10
Top 10
EmptyTop
Push 20
Top
1020
Pop
Top 10
push( ), pop( ) push( ), pop( )
- 5 elements- top = 4
- 7 elements- top = 6
Object s2Object s1
Stack Class
Stack Class & Stack Objects
DataArrayTop
FunctionsPush( )Pop( )Printall( )
Enterprise Solutions Using J2EE / Lecture 24 3
package classdemo ;public class ClassDemo
public static void main ( String[ ] args)
Sample a, b ;a = new Sample( ) ;a.i = 10 ; a.j = 3.14f ;S.o.p ( a.i + " " + a.j ) ;b = new Sample( ) ;b.i = 20 ; b.j = 6.28f ;S.o.p ( b.i + " " + b.j ) ;
Creation of Classes & Objects
a
i j10 3.14
Objects are created using new operatora, b - References to Objectsa, b contain addresses of objects
class Sample
int i ;float j ;
i j
b
20 6.28
20 6.28
10 3.14
package classdemo ;public class ClassDemo
public static void main ( String[ ] args )
Sample a, b ;a = new Sample( ) ;a.SetData ( 10, 3.14f ) ;a.ShowData( ) ;b = new Sample( ) ;a.SetData ( 20, 6.28f ) ;b.ShowData( ) ;
Better Way... class Sample
private int i ;private float j ;public void SetData ( int ii,
float jj )
i = ii ; j = jj ;public void ShowData( )
S.o.p ( i + " " + j ) ;
a
i j10 3.14
i j
b
20 6.28pri., pub. - Access SpecifiersDefault - publicSafer and Better organised
s2 = new Sample( ) ;// receive x
Which Is Better
if ( x > 0 )
if ( x > 0 )
s1.age = x ;
class Sample
private int age ;public void setdata ( int x )
age = x ;
class Demo
public static void main( )
Sample s1, s2 ; int x ;
if ( x > 0 )
s2.age = x ;
class Sample
public int age ; class Demo
public static void main( )
sample s1, s2 ; int x ;s1 = new Sample( ) ;// receive x
// receive x
s2 = new Sample( ) ;s2.setdata ( x ) ;
s1 = new Sample( ) ;s1.setdata ( x ) ;// receive x
Better
Enterprise Solutions Using J2EE / Lecture 25 1
Classes And Objects
Yashavant [email protected]
Objectives
Handling Complex NumbersDifference between primitive and objectWhere objects are createdStack versus HeapThe this Reference
Handling Complex Numbers
On Addition 3.9 + 3.4i
On Subtraction 0.3 + 1.2i
2.1 + 2.3i1.8 + 1.1i
Real Part Imaginary Part
Function Add
Function Sub
Complex Class
2.1 2.3
Add( ) Sub( )
Complex Object1
1.8 1.1
Add( )
Complex Object2
Sub( )
Generic Unique
Enterprise Solutions Using J2EE / Lecture 25 2
r i
public class ClassDemo
public static void main ( String[ ] args)
Complex a, b ;a = new Complex( ) ;a.SetData ( 2.1f, 2.3f );a.ShowData( ) ;b = new Complex( ) ;b.SetData ( 1.8f, 1.1f ) ;b.ShowData( ) ;
package classdemo ;class Complex
private float r, i ;public void SetData (
float rr, float ii )
r = rr ; i = ii ;public void ShowData( )
S.o.p ( r + " " + i ) ;
Implementation
r i1.8 1.1
2.1 2.3
2.1 2.3
1.8 1.1
private inaccessible from outsideAny class member can access other
a
b
How Many Copies
public void SetData ( .. )
r = rr ; i = ii ;public void ShowData( )
S.o.p ( r + " " + i ) ;
Common
Member FunctionsConceptually - ManyPractically - One
r i1.8 1.1
r i2.1 2.3
a
b
this400500
class ex
private int i ; private float a ;
public void SetData ( int ii, float aa )
this.this.a = aa ;
i = ii ;
The this Reference
i a
500
o2
504
i a
400 404
o1
public static void main( )
ex e1 = new ex( ) ;
e1.SetData ( 5, 5.5f ) ;
e2.SetData ( 10, 10.5f ) ;
ex e2 = new ex( ) ;
class Sample
Can't be modifiedOptional
e1 is also passed
void SetData ( ex final this, int ii, float aa )
Enterprise Solutions Using J2EE / Lecture 25 3
this.this.
Is this Necessary
i a
i a
500
400o2
404
504
o1public void SetData ( int i, float a )
class ex private int i ;
private float a ;
a = a ;i = i ;
public static void main( )
ex e1 = new ex( ) ;ex e2 = new ex( ) ;e1.SetData ( 5, 5.5f ) ;
e2.SetData ( 10, 10.5f ) ;
class Sample
Enterprise Solutions Using J2EE / Lecture 26 1
Java Member FunctionsYashavant [email protected]
ObjectivesWhat are constructorsWhat are overloaded functionsTypes of calls – By value, By referenceGarbage collection
Recap…Classes are like DatatypesObjects are specific instance of a classMultiple objects enjoy different data but share same func.Data is usually privateMember functions are usually publicObjects are namelessObjects are created using newObjects are referred using referencesReferences are created on stackObjects are created on heapthis reference is passed to member functions
Enterprise Solutions Using J2EE / Lecture 26 2
Constructorsclass ex
private int i ; private float j ;
public ex ( int ii, float jj )
class Sample
public static void main( )
ex e1 = new ex ( 10, 3.14f ) ;ex e2 = new ex( ) ;
i = ii ; j = jj ;ex( )
i = 0 ;
j = 0.0f ;
Object CreationAllocate space in memoryCall the constructor
i j
e1
10 3.14
i j
e2
0 0.0
2 ArgumentConstructor
0 ArgumentConstructor
OverloadedFunctions
Constructor TipsName of constructor must be same as name of classCtor is invoked only using newCtor is a functionCtor never returns any typeCtor can be overloadedIf the class is empty compiler inserts a CtorEither I do it or you do it policy
Different return types notenough for overloading
Fun.Overloading static void set ( int i, float j ) static void set ( float jj, int ii )static int set ( float jj, int ii )
class Sample
public static void main( )
set ( 10 ) ;set ( 10, 3 ) ;set ( 10, 3.14f ) ;set ( 3.14f, 10 ) ;set ( 3.14f, 10 ) ;
Arguments must differ in
Number OrderType
static void set ( int i )static void set ( int i, int j )
Enterprise Solutions Using J2EE / Lecture 26 3
Call By valueclass Sample
public static void main( )
int i = 1 ;float f = 3.1f ;fun ( i, f ) ;S.o.p ( i + " " + f ) ;
void fun ( int ii, float ff )
ii = ii * 2 ;ff = ff * 2 ;S.o.p ( ii + " " + ff ) ;
Changing Formal arguments doesn't
change Actual arguments
1 3.1
2 6.2
Call By Referenceclass ex
private int i ; private float f ;
class Sample
public static void main( )
ex e = new ex e.Set ( 1, 2.5f ) ;e.Display( ) ;
void fun ( ex p )
p.Set ( 3, 8.5f ) ;
void Display( )
S.o.p ( i + " " + f ) ;
fun ( e ) ;e.Display( ) ;
public Set ( int x, float y )
i = x ; f = y ;
1 2.5
3 8.5
i j
e
1 2.5
p
Objects are always passed by RefReference is passed by value
3 8.5
References
Complex c1, c2 ; c1 = new Complex( ) ;c2 = c1c1 = null ;
Complex Obj.
i fc1
c2 = null ;
c1 null
GCCommon for all programsPart of Java Runtime Env.
Shallow Copy Destroyed byGarbage Collector
c2
c2 null
Enterprise Solutions Using J2EE / Lecture 27 1
Static FunctionsYashavant [email protected]
ObjectivesHow to share data amongst objectsStatic data and static functionsWhat is a Singleton classNeed for a Singleton classfinalize( ) method
class Ex
private int i ;private static int count = 0 ;
Ex( )
i = 0 ;count += 1 ;
static void ShowCount( )
S.o.p ( count ) ;
class Sample
public static void main( )
Shared Data
• static functions can access only static data• static functions cannot call instance functions
e1 e2
i0 0
i
1
Ex e2 = new Ex( ) ;Ex.ShowCount( ) ;
2
Ex e1 = new Ex( ) ;
2count
Ex.ShowCount( ) ;
Enterprise Solutions Using J2EE / Lecture 27 2
Only one object gets created from a classHint:- Create private constructor- Create static member function to create object
Problem
Singleton Class
Design Pattern
class Singleton
Singleton p ;
static Singleton Create( )
private Singleton( )
class Sample
public static void main( )
Singleton s1 ;s1 = new Singleton( ) ;
Singleton Class
Singleton s2 ;s2 = Singleton.Create( ) ;
s1 = Singleton.Create( ) ;
s1 s2
if ( p == null )p = new Singleton( ) ;
return p ;
static Singleton p ;
p
Circle ClassCreate a Circle classEach Circle object will have a radius and colorProvide a function Area( ) to calculate area of circleCount how many objects of Circle class have been created
3count
3.14PI
colorR
radius1.5
Object1
colorG
radius1.1
Object2
colorB
radius1.4
Object3
Common for all objects
Enterprise Solutions Using J2EE / Lecture 27 3
Circle ( float rr, int cc )
rad = rr ;color = cc ;count += 1 ;
Circle c1, c2, c3 ;c1 = new Circle ( 1.5, 'R' ) ;c2 = new Circle ( 1.1, 'G' ) ;c3 = new Circle ( 1.4, 'B' ) ;c1.Area( ) ;Sample.ShowCount( ) ;
class Circle
private int color ;private float rad ;private static int count ;final float PI = 3.14f ;
static void ShowCount( )
S.o.p ( count ) ;
class Sample
public static void main( )
Implementation
void Area( )
S.o.p ( PI * rad * rad ) ;
Invoked using Object
Access PrivateData / Functions
FunctionType
Within class scope
Instance
Static
Summary
only static
Static functions can be called before creating
an object
class Ex
static int x, y, z ;
static void fun( )
static
x = 10 ; y = 20 ;z = x * 2 + y * 5 ;
class Sample
public static void main( )
Ex.fun( ) ;
Static Block
S.o.p ( x ) ; S.o.p ( y ) ;S.o.p ( z ) ;
10 20 120
Static block gets executed exactly once whenthe class is loaded
Enterprise Solutions Using J2EE / Lecture 27 4
finalize( ) MethodCalled when an object is about to be destroyedDestruction is done by Garbage CollectorUsed to free non-Java resource like file handle of fontCalled by Java Runtime just before garbage collectionNot called when an object goes out of scope
protected void finalize( )
// finalisation code
Enterprise Solutions Using J2EE / Lecture 28 1
ArraysYashavant [email protected]
Objectives
What are Arrays
Need for Arrays
Properties of Arrays
Array Initialisation
Variable Sized Arrays
How Much Java
10 %? 20 % ? 30 %?
Data Typesint charfloat doublelong shortbyte boolean
Control Instr.if elsefor while do break continue switchcase default
Otherthrows classprivate public final importpackage newstatic thisvoid return30 / 48
Enterprise Solutions Using J2EE / Lecture 28 2
Storing Multiple Valuesclass Array
S.o.p ( "Enter Marks" ) ;// receive m1, m2, m3 per = ( m1 + m2 + m3 ) / 3 ;S.o.p ( per ) ;
int m1, m2, m3, per ;
for ( i = 1 ; i <= 10 ; i++ )
int i ;
S.o.p ( per ) ;
public static void main( ) throws Exception
Arraysclass Array
int m1, m2, m3, i ;int per[ ] = new int[ 10 ] ;
S.o.p ( per[ i ] ) ;
S.o.p ( "Enter Marks" ) ;// receive m1, m2, m3 per[ i ] = ( m1 + m2 + m3 ) / 3 ;
for ( i = 0 ; i <= 9 ; i++ )
public static void main( ) throws Exception
for ( i = 0 ; i <= 9 ; i++ )
int [ ] per per = new int [ 10 ] ;
int per[ ] ;per = new int[ 10 ] ;
per - ReferenceArray is created on heap
Array Initialisation
c[ 5 ] = 3 + 7 % 2 ; c[ 6 ] = c[ 1 ] + c[ 3 ] / 16 ;
int a[ ] = 7, 6, 11, -2, 26 ;int b[ ] = new int[ 10 ] ;int c[ ] = 16, 13, -8, -7, 25 ;10S.o.p ( a[ 0 ] + " " + b[ 0 ] ) ;// receive c[ 7 ], c[ 8 ], c[ 9 ]
int i ;i = 2 ; int i = 2 ;
7 0
class Array public static void main( ) throws Exception
compulsory
Enterprise Solutions Using J2EE / Lecture 28 3
Different types of arrays are possible – int, float, etc.
Tips About ArraysCollection of similar elements
30 20 16 18 35a[0] a[1] a[2] a[3] a[4]
402 406 410 414 418int a[ ] = 30, 20, 16, 18, 35 ;
Elements are stored in adjacent memory locations
a[ ] = 2, 1.4, ’A’, 6 ; int
int a[ ] = 11, 3, 6, 9 ;float b[ ] = 1.1f, 1.2f, 1.7f ;
11 3 6 9 1.1 1.2 1.7
Bounds checking is NOT programmer’s responsibility
More Tips…
int a[ ] = 30, 20, 16, 18, 35 ;for ( int i = 0 ; i <= 40 ; i++ )
System.out.println ( a[ i ] ) ; Exception
Instead of array of chars a type called string can be used
char str1[ ] = 'H', 'e', 'l', 'l', 'o' ;for ( int i = 0 ; i < str1.length ; i++ )
System.out.println ( str1[ i ] ) ;
String str2 = "Hello" ;System.out.println ( str2 ) ;
Variable Sized Arrays
int n = 4 ;int a[ ] = new int [ n ] ;
NoteDimension can be a variablen can be scanned through keyboard
HeapStacka
Array of Integers
11 3 6 9
Enterprise Solutions Using J2EE / Lecture 29 1
Enterprise Solutions Using J2EE /
MoreArrays
Yashavant [email protected]
Enterprise Solutions Using J2EE / Lecture 29
Objectives
Selection Sort Algorithm
Bubble Sort Algorithm
Reallocation of Arrays
Deallocation of Arrays
Passing Arrays elements / entire Array
Returning an Array
Enterprise Solutions Using J2EE / Lecture 29
Selection Sort17 6 13 12 2 i6 17 13 12 26 17 13 12 26 17 13 12 22 17 13 12 62 2 2 2 6 2 6
2 6 12
13 17 12 612 17 13 66 17 13 12 1 - 4
13 17 1212 17 13
2 - 32 - 4
13 17 3 - 4
j0 - 10 - 20 - 30 - 41 - 21 - 3
public class SelectionSort
public static void main( )
int a[ ] = 17, 6, 13, 12, 2 ;int i, j, t ;for ( i = 0 ; i <= 3 ; i++ )
for ( j = i + 1 ; j <= 4 ; j++ )
if ( a[ i ] > a[ j ] )
t = a[ i ] ; a[ i ] = a[ j ] ;a[ j ] = t ;
for ( i = 0 ; i <= 4 ; i++ )
System.out.println ( a[ i ] ) ;
Enterprise Solutions Using J2EE / Lecture 29 2
Enterprise Solutions Using J2EE / Lecture 29
13 17
Bubble Sort
17 6 13 12 2 i 6 17 13 12 2 0 - 1
1 - 22 - 33 - 4
6 13 17 12 26 13 12 17 26 13 12 2 17
6 13 12 2 0 - 16 12 13 2 6 12 2 136 12 26 2 12
2 6
1 - 22 - 30 - 11 - 2
12 13 17 0 - 1
i+1
17
13 17
17
17
public class BubbleSort
public static void main( )
int a[ ] = 17, 6, 13, 12, 2 ;int i, j, t ;for ( j = 0 ; j <= 3 ; j++ )
for ( i = 0 ; i <= 3 - j ; i++ )
if ( a[ i ] > a[ i + 1 ] )
t = a[ i ] ; a[ i ] = a[ i + 1 ] ;a[ i + 1 ] = t ;
for ( i = 0 ; i <= 4 ; i++ )
System.out.println ( a[ i ] ) ;
13 17
Enterprise Solutions Using J2EE / Lecture 29
Sorting Procedures
Selection SortBubble SortShell SortShuttle SortHeap SortMerge SortRadix SortQuick Sort
Fastest?
n2
log2n
For n = 10, Order = 3
For n = 10, Order = 100
Recursion
Enterprise Solutions Using J2EE / Lecture 29
Reallocation & Deallocationint a[ ] = 1, 2, 3, 4, 5 ; int b[ ] ;System.out.println ( a ) ;b = a ;a = new int [ 10 ] ;for ( int i = 0 ; i <= 4 ; i++ )
a[ i ] = b[ i ] ;for ( int i = 5 ; i <= 9 ; i++ )
a[ i ] = 20 ;a = null ; System.out.println ( a[ 0 ] ) ;System.out.println ( b[ 0 ] ) ; 1
All arrays are dynamically allocatedArrays can be resized Arrays can be de-allocated during execution
Exception
f548743452
Enterprise Solutions Using J2EE / Lecture 29 3
Enterprise Solutions Using J2EE / Lecture 29
Heap
n Integers11 4 2 9
Stacka
ProblemCreate an array by receiving its size and its values
int n ;S.o.p ( "Enter Size" ) ; // receive nint[ ] a = new int [ n ] ;
Increase size of array by 3 elements, receive all elements again
a = new int [ n + 3 ] ;
for ( i = 0 ; i < a.length ; i++ )
// receive n a[ i ] = n ; S.o.p ( a[ i ] ) ;
Print the values
for ( i = 0 ; i < a.length ; i++ )
// receive n ;a[ i ] = n ;
n + 3 Integers5 4 6 1 0 7 9
Enterprise Solutions Using J2EE / Lecture 29
Passing Array Elementsclass Array
public static void main( )
int[ ] a = 7, 9, 16, -2, 8 ; int i ;display ( a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ] ) ;for ( i = 0 ; i < a.length ; i++ )
display1 ( a[ i ] ) ;static void display ( )
S.o.p ( i + " " + j + " " + k + " " + l + " " + m ) ;static void display1 ( )
S.o.p ( n ) ;
int i, int j, int k, int l, int m
int n
Whichis good?
102 106 110 114 118
a[0] a[1] a[2] a[3] a[4]8-21697
Enterprise Solutions Using J2EE / Lecture 29
display ( b ) ;
public static void main( )
int a[ ] = 7, 9, 16, -2, 8 ;
display ( a ) ;
class PassingArray
static void display ( )int [ ]p
int i ;for ( i = 0 ; i < p.length ; i ++ )
System.out.println ( p[ i ] ) ;
Passing Entire Array
102 106 110 114 118
a[0] a[1] a[2] a[3] a[4]8-21697
int b[ ] = 1, 3, 6, -2, 18, 1, 1, 7, 1, 1 ;
Enterprise Solutions Using J2EE / Lecture 29 4
Enterprise Solutions Using J2EE / Lecture 29
System.out.println ( p[ i ] ) ;
public static void main( )
int p[ ] = fun( ) ;
class ReturningArray
public static int[ ] fun( )
for ( i = 0 ; i < p.length ; i ++ )
Returning An Array
102 106 110 114 118
a[0] a[1] a[2] a[3] a[4]8-21697
int a[ ] = 7, 9, 16, -2, 8 ;return ( a ) ;
Enterprise Solutions Using J2EE / Lecture 30 1
Still More
ArraysYashavant [email protected]
Objectives
Passing array elements / array
Returning an array
Two-Dimensional Arrays
Initialization of 2D Array
Passing 2D Array
Returning 2D Array
Passing Array Elementsclass Array
public static void main( )
int[ ] a = 7, 9, 16, -2, 8 ; int i ;display ( a[ 0 ], a[ 1 ], a[ 2 ], a[ 3 ], a[ 4 ] ) ;for ( i = 0 ; i < a.length ; i++ )
display1 ( a[ i ] ) ;static void display ( )
S.o.p ( i + " " + j + " " + k + " " + l + " " + m ) ;static void display1 ( )
S.o.p ( n ) ;
int i, int j, int k, int l, int m
int n
Whichis good?
102 106 110 114 118
a[0] a[1] a[2] a[3] a[4]8-21697
Enterprise Solutions Using J2EE / Lecture 30 2
display ( b ) ;
public static void main( )
int a[ ] = 7, 9, 16, -2, 8 ;
display ( a ) ;
class PassingArray
static void display ( )int [ ]p
int i ;for ( i = 0 ; i < p.length ; i++ )
System.out.println ( p[ i ] ) ;
Passing Entire Array
102 106 110 114 118
a[0] a[1] a[2] a[3] a[4]8-21697
int b[ ] = 1, 3, 6, -2, 18, 1, 1, 7, 1, 1 ;
System.out.println ( p[ i ] ) ;
public static void main( )
int p[ ] = fun( ) ;
class ReturningArray
public static int[ ] fun( )
for ( i = 0 ; i < p.length ; i++ )
Returning An Array
102 106 110 114 118
a[0] a[1] a[2] a[3] a[4]8-21697
int a[ ] = 7, 9, 16, -2, 8 ;return ( a ) ;
S.o.p ( a[ ][ ] ) ;
2-D Arraypublic static void main( )
int a[ ][ ] = 2, 6, 1, 8, 4 1, 2, 5, 6, 8 7, 9, 8, 7, 21 4, 5, 6, 8, 10
;int i, j ;
2 4for ( i = 0 ; i < a.length ; i++ )
for ( j = 0 ; j < a[ i ].length ; j++ ) System.out.print ( a[ i ][ j ] + " " ) ;
System.out.println( ) ;
21
,
,,
compulsory
class Sample
compulsory
Enterprise Solutions Using J2EE / Lecture 30 3
class Biggest public static void main( )
int a[ ][ ] =
7, 2, 6, 1 , 3, 5, 4, 8 , 6, 2, 9, 50
;
big = a[ 0 ][ 0 ] ; for ( i = 0 ; i < a.length ; i++ )
for ( j = 0 ; j < a[ i ].length ; j++ )
if ( > big )
big = a[ i ][ j ] ;
r = i ; c = j ;
S.o.p ( big ) ; S.o.p ( r + " " + c ) ;
r = 0 ; c = 0 ;int i, j, big ; int r, c ;
Find Biggest...
Find Second Biggestand its Position
a[ i ][ j ]
Initialisation of 2-D Arrays
int a[ ][ ] = new int [3][4] ; a[0][0] = 7 ; a[0][1] = 2 ; a[0][2] = 6 ; a[0][3] = 1 ; a[1][0] = 9 ; a[1][1] = 3 ; a[1][0] = 4 ; a[1][1] = 5 ; a[2][0] = 10 ; a[2][1] = 12 ; a[2][0] = 16 ; a[2][1] = 18 ;
9 3 4 5 10 12 16 181627402 418 434
int a[ ][ ] = 7, 2, 6, 1 , 9, 3, 4, 5 , 10, 12, 16, 18 ;
int [ ][ ]a = new int [3][4] ;
aStack
Row Major
Passing 2D Array
int a[ ][ ] = 1, 2, 3 , 4, 5, 6 ;int sum ;
public static int fun ( int b[ ][ ] )
int i, j ;for ( i = 0 ; i < b.length ; i++ )
for ( j = 0 ; j < b[ i ].length ; j++ )s = s + b[ i ][ j ] ;
return ( s ) ;
class TwoD
public static void main( )
sum = fun ( a )S.o.p ( sum ) ; 21
Enterprise Solutions Using J2EE / Lecture 30 4
S.o.p ( b[ 0 ][ 0 ] + " " + b[ 1 ][ 1 ] ) ;
Returning 2D Array
int b[ ][ ] ;
public static int [ ][ ] fun( )
int i, j ;for ( i = 0 ; i < b.length ; i++ )
for ( j = 0 ; j < b[ i ].length ; j++ )b[ i ][ j ] += 20 ;
return ( b ) ;
class TwoD
public static void main( )
b = fun( ) ;
int b[ ][ ] = 1, 2, 3 , 4, 5, 6 ;
Enterprise Solutions Using J2EE / Lecture 31 1
Types ofArrays
Yashavant [email protected]
Objectives
3D Arrays
Array of References
Jagged Arrays
Passing Jagged Array
Returning Jagged Array
3D Jagged Array
Heap7 1 32 9 6
3D Arrays
aStack 4 5 1
1 3 89 2 2
1 4 32 7 8
1 4 3
int a[ ][ ][ ] = … ;S.o.p ( a[ 3 ][ 1 ][ 2 ] ) ;S.o.p ( a.length + " " + a[0].length + " " + a[0][1].length ) ;
4 2 3
Enterprise Solutions Using J2EE / Lecture 31 2
Accessing
for ( int i = 0 ; i < a.length ; i++ )
for ( int j = 0 ; j < a[ i ].length ; j++ )
for ( int k = 0 ; k < a[ i ][ j ].length ; k++ )S.o.print ( a[ i ][ j ][ k ] ) ;
S.o.println( ) ;
for ( int arr2d[ ][ ] : a )
for ( int arr1d[ ] : arr2d )
for ( int item : arr1d )S.o.print ( item ) ;
S.o.println( ) ;
Or
Heap7 1 32 9 64 5 1
1 3 89 2 2
1 4 32 7 8
1 4 3
Array Of References
Heap
Array of Sample refs
Sample objects
Sample s[ ] ;s = new Sample [ 4 ] ;for ( int i = 0 ; i <= 4 ; i++ )
s[ i ] = new Sample( ) ;
sStack
Represent This...
Enterprise Solutions Using J2EE / Lecture 31 3
Jagged Arrays
int a[ ][ ] = new int [3][ ] ;
a[0][0] = 7 ; a[0][1] = 2 ; a[0][2] = 6 ; a[0][3] = 1 ; a[1][0] = 9 ; a[1][1] = 3 ; a[1][2] = 4 ; a[2][0] = 1 ; a[2][1] = 8 ;
a[0] = new int [4] ;a[1] = new int [3] ;a[2] = new int [2] ;
for ( int i = 0 ; i < a.length ; i++ )
for ( int j = 0 ; j < a[ i ].length ; j++ )System.out.print ( a[ i ][ j ] ) ;
System.out.println( ) ;
HeapStacka
791
2 6 13 48
a - Ref. to arr of Ref.a[0] - Ref. to 1D arra[1] - Ref. to 1D arra[2] - Ref. to 1D arr
public class Jagged
public static void main ( String[ ] args ) throws Exception
int a[ ][ ] = new int [2][ ] ;a[0] = new int [4] ; a[1] = new int [3] ; a[0][0] = 7 ; a[0][1] = 2 ; a[0][2] = 6 ; a[0][3] = 1 ; a[1][0] = 9 ; a[1][1] = 3 ; a[1][2] = 4 ; int sum ;sum = fun ( a ) ; System.out.println ( sum ) ;
public static int fun ( int b[ ][ ] )
int i, j ; int s = 0 ;for ( i = 0 ; i < b.length ; i++ )
for ( j = 0 ; j < b[ i ].length ; j++ )s = s + b[ i ][ j ] ;
return s ;
Passing Jagged Arrays
HeapStacka 7
92 6 13 4
Returning Jag. Arr.public class JaggedArrays
public static void main ( String[ ] args ) throws Exception
int i, j ; int b[ ][ ] ;b = fun( ) ;for ( i = 0 ; i < b.length ; i++ )
for ( j = 0 ; j < b[ i ].length ; j++ )System.out.print ( b[ i ][ j ] ) ;
public static int[ ][ ] fun( )
int a[ ][ ] = new int [2][ ] ;a[0] = new int [4] ; a[1] = new int [3] ;a[0][0] = 7 ; a[0][1] = 2 ; a[0][2] = 6 ; a[0][3] = 1 ; a[1][0] = 9 ; a[1][1] = 3 ; a[1][2] = 4 ; return a ;
Heap
79
2 6 13 4
Enterprise Solutions Using J2EE / Lecture 31 4
Heap
3D Jagged Array
1st 2D Arr - 2C, 4C, 3C0th 2D Arr - 3C, 5C
3D Jagged ArraysStack
arr 1 4 3
8 0 9
1 32 2 7 9 1
2 7 5 6
What isarrarr[ 0 ] arr[ 0 ][ 0 ]
int arr[ ][ ][ ] = new int[ 2 ][ ][ ] ;arr[ 0 ] = new int [ 2 ][ ] ;arr[ 1 ] = new int [ 3 ][ ] ;arr[ 0 ][ 0 ] = new int [ 3 ] ;arr[ 0 ][ 1 ] = new int [ 5 ] ;arr[ 1 ][ 0 ] = new int [ 2 ] ;arr[ 1 ][ 1 ] = new int [ 4 ] ;arr[ 1 ][ 2 ] = new int [ 3 ] ;
Enterprise Solutions Using J2EE / Lecture 32 1
Using NetBeans Effectively
Yashavant [email protected]
ObjectivesWhat are Edit HintsHow to NavigateWhat is Code completion featureWhat is code RefactoringHow to achieve Refactoring in NetBeans
Creating New Project
Enterprise Solutions Using J2EE / Lecture 32 2
NetBeans ViewsProjects View
Add New Class
R
Utility.java – Add throws
Enterprise Solutions Using J2EE / Lecture 32 3
Utility.java
Edit Hints – try-catch
Edit Hints – try-catch
Enterprise Solutions Using J2EE / Lecture 32 4
Edit Hints – try-catch
Edit Hints – try-catch
Edit Hints 2 – import
Enterprise Solutions Using J2EE / Lecture 32 5
Edit Hints 2 – import
Navigation – Ctrl + Mouse
Navigation – Ctrl + Mouse
Enterprise Solutions Using J2EE / Lecture 32 6
Code Completion – Step 1
After typing . complete list appears
Code Completion – Step 2
Code Completion - Result
Enterprise Solutions Using J2EE / Lecture 32 7
Code Completion – Multiple
Ctrl + Spacebar
Refactoring - Rename
R
Enterprise Solutions Using J2EE / Lecture 32 8
R
Enterprise Solutions Using J2EE / Lecture 32 9
Configure – Tools | Options
Configure – Tools | Options
Code Templates
Enterprise Solutions Using J2EE / Lecture 33 1
Bitwise OperatorsYashavant [email protected]
Objectives
Need for using Bitwise operatorsOne's complement operatorBitwise &, |, ^ operatorsBitwise <<, >>, >>> operators
Binary to Hex. is convenient
Binary - 0..1 Octal - 0..7Decimal - 0..9 Hexadecimal - 0...9, A...F
Binary to decimal is inconvenient
Bits etc.
Numbering systems
- 0xFA
- 0x76
Bit - Binary Digit - Basic unit of informationCan take a value 0 or 14 bits = Nibble 8 bits = Byte16 bits = Word 32 bits = DWord
1000 81001 91010 A1011 B1100 C1101 D1110 E1111 F
0000 00001 10010 20011 30100 40101 50110 60111 7
0111 01101111 1010
0111 01101111 1010
- 2+4+16+32+64
- 2+8+16+32+64+128
Enterprise Solutions Using J2EE / Lecture 33 2
Need For Bitwise Operators
int ch = 32 ;
01234567152331
check 1 or 0 set to 0 or 1
One's Complement Operator
int ch = 32 ;S.o.print ( ~ch ) ;
111111111111111111111111111011111
-11111111111111111111111111011110
~
00000000000000000000000000100000~
11111111111111111111111111011111 -ve
00000000000000000000000000100001
-33
-33
Original
And, Or, Xor
& 0 10 0 01 0 1
| 0 10 0 11 1 1
^ 0 10 0 11 1 0
0000000000000000000000000010000111111111111111111111111111100001&
00000000000000000000000000100001
|
1111111111111111111111111100001
11111111111111111111111111000000
^
Mask
New
0000000000000000000000000010000111111111111111111111111111100001
0000000000000000000000000010000111111111111111111111111111100001
Enterprise Solutions Using J2EE / Lecture 33 3
if ( )
Utility of & and I7 6 5 4 2 1 0
& 0 0 0 0 1 0 0 00 0 0 0 0 0 00/1
3
1- - - - - - -1 1 1 1 0 1 1 1- - - - - - -0
S.o.println ( "Enter a no." ) ;// receive n = byte.ParseByte( )
byte n ;
n & 8 == 8
S.o.p ( n ) ;else
S.o.p ( "3rd bit is off" ) ;n = n | 8 ;
n0/1- - - - - - -
n = n & 0xF7 ;
&
S.o.p ( "3rd bit is on" ) ;
& 0 10 0 01 0 1
Utility of &Check whether a bit is on or offPut off a particular bit
0- - - - - - -0 0 0 0 1 0 0 0- - - - - - -1
|
Utility of | Put on a bit
Bitwise CA oper.&= |= ^= <<= >>=
n |= 8 ;
Right Shift >>
int ch = 32 ;System.out.print ( ch >> 2 ) ;System.out.print ( ch ) ;
>> 2
8
32
ch >> 1 Divides by 2, discards remainderSign is not changed
00000000000000000000000000100000
000000000000000000000000001000- -00
System.out.print ( 35 >> 2 ) ; 8
Left Shift <<
int ch = 32 ;System.out.print ( ch << 1 ) ;System.out.print ( ch ) ;
<< 1
32
ch << 1 Multiplies by 2,if 1’s are not lostSign is not changedSign may change
00000000000000000000000000100000
0000000000000000000000000100000-0
<< 2
01000000
00000000
<< 1
01000000
100000001 is lost Sign is changed
64
Enterprise Solutions Using J2EE / Lecture 33 4
Unsigned Shift
int ch = -1 ;System.out.print ( ch >> 1 ) ;System.out.print ( ch >>> 1 ) ;
>> 1
2147483647
>>> Should be used only with int or long intbyte and short are anyway promoted to ints
1111111111111111111111111111111
1111111111111111111111111111111-
System.out.print ( ch ) ;
0111111111111111111111111111111-
-1SignExtended
>>> 1
-1
10011 0001 0011000
Binary
Utility Of <<, >>
( 1999 - 1980 ) * 5121 * 32+
+ 69766
= 9728= 32= 6
yr m d
7 Bits 4 Bits 5 Bits
For every file, Date and Time are stored as two-byte entries
m s
6 Bits 5 Bits5 Bits
hr
1 + 2 + 16 + 1980 = 1999 1 2 + 4 = 6
d, m, y
class Date
public static void main ( .. )
int dt = 9766 ;short d, m, y ;y = ( short ) ( ( dt >> 9 ) + 1980 ) ;m = ( short ) ( ( dt << 23 ) >> 28 ) ;d = ( short ) ( ( dt << 27 ) >> 27 ) ;S.o.println ( d + " " + m + " " + y ) ;
6 1 1999
00000000 00000000 0010011 0001 00110>> 9
00000000 00000000 0010011000000000
00000000 00000000 0010011 0001 00110
m d
4 5
1
InheritanceYashavant [email protected]
Objectives
Cornerstones of OOP
Reuse Mechanisms
What is Containership
What is Inheritance
Object sizes in Inheritance
OO Programming
Encapsulation
Inheritance
Polymorphism
- Hides complexity
- Promotes reuse
- Generalizes actions
Facilitated by Classes and Objects
2
Reuse Mechanisms
Containership Inheritance
Window
Button
StringList
String
"Has a" relationship
"Like a" relationship
Non-OO Lang. - Has aOO Lang. - Has a, Like a
Vehicle
Combination of Relationships
Engine
Vehicle
Car
Car
EngineWhat do you see?
Main W, Project W, Error W, Program WDifferent things in different WindowsBut each specific W is still Like a window
Where are they?All W are contained inside Main Window
Window
Error W Pro Win
Main WindowPro. W.Error W.
O/P W. Prog. W
private int count ;
Index i = new Index ( );
Inheritanceclass Index
count -= 1 ;
class Program
public static void main( .. )
class index1 extends Index
public void decr( )
0
1
0
i.incr( ) ;
i.decr( ) ;
public void display( )
S.o.p ( count ) ;public void incr( )
count += 1 ;
i.display( ) ;
i.display( ) ;
public Index( )
count = 0 ;
protected int count ;
i.display( ) ;
Index1 i = new Index1( ) ;
display( ), incr( ) - Not part of index1
3
class Index
private
protected
public
private
protected
public
Index1 i = new Index1( ) ;
Access
class Index1 extends Index
Index j = new Index( ) ;
All Casesclass base
private
protected
public
private
protected
public
class der extends base
class Myclass
base b ;
derived d ;
base b ;der d ;
Object Sizesclass base1
private int i ;protected int j ;public int k ;
class derv extends base1
private int x ;protected int y ;public int z ;
base1 b = new base1( ) ;derv d = new derv( ) ;
final - Shared by defaultstatic - Is never a part of object
i kj
b
i kj x y z
d
4
Inheritance in real life
Simple mindedGood English oratorToo religious
Simple mindedGood English oratorModerately religiousGood English writing skills
Simple mindedGood English and Hindi oratorScorn for religionGood sportsman
- As it is- As it is- Change
- New
- As it is- Combination
- Change- New
Enterprise Solutions Using J2EE / Lecture 35 1
More InheritanceYashavant Kanetkar
ObjectivesWhat does Inheritance offer us
Practical application of Inheritance
How objects are constructed in Inheritance chain
How to prevent Inheritance
Calls...
S.o.p ( "b.f2" ) ;
public void f3( )
S.o.p ( "b.f3" ) ;public void f4( )
S.o.p ( "b.f4" ) ;
class a
class b extends a
super.f2( ) ;
public void f2( )z.f4( ) ;
Cases
Use ExistingOverrideNew Combinationpublic void f1( )
S.o.p ( "a.f1" ) ;
public void f2( )
S.o.p ( "a.f2" ) ;
class Sample
public static void main ( .. )
b z = new b( ) ;z.f1( ) ;z.f2( ) ;z.f3( ) ;
a.f1b.f2b.f3
a.f2 b.f4
Enterprise Solutions Using J2EE / Lecture 35 2
A Practical ScenarioA company has created software which has several classesAfter a market survey before the next version following requirements have to be met:
A new Auto Update feature should be addedBug was discovered while saving files > 400 kb
Data encryption function is too slowWhile opening a file opening progress should be displayedRest of the functionality is acceptable
New - autoupdate( )Change - save( ), encrypt( )Combination - open( )Use Existing - fun( )
Implementation
public void enc( ) S.o.p ( "Encrypt" ) ;
public void autoupdate( )
S.o.p ( "AU" ) ;
public void save( )
S.o.p ( "Save" ) ;
public void open( )
S.o.p ( "Open" ) ;
news x = new news ( ) ;
public void open( ) // progress barsuper.open( ) ;
class s
public void save( ) // fix bug
class news extends s
x.fun( ) ;x.autoupdate( ) ;
x.save( ) ;
public void fun( )
S.o.p ( "fun" ) ;
public void enc( )
S.o.p ( "Encrypt" ) ;
x.enc( );x.open( ) ;
Ctor Calls
class b extends a
b( )
S.o.p ( "b's 0-arg Ctor" ) ;
class a
a( )
S.o.p ( "a's 0-arg Ctor" ) ;a ( int xx )
S.o.p ( "a's 1-arg Ctor" ) ;
class Myclass
public static void main( .. )
b y = new b( ) ; b z = new b ( 10 ) ;
a’s 0-arg Ctor
b’s 0-arg Ctora’s 1-arg Ctorb’s 1-arg Ctor
b ( int x )
super ( x ) ;s.o.p ( "b's 1-arg Ctor" ) ;
Call to super must be 1st statementIf super( ) is absent a's 0-arg Ctor is calledsuper can also be used to call base class fun.
Enterprise Solutions Using J2EE / Lecture 35 3
Why Base To Derivedclass base
protected int i ;public base( )
i = 4 ;
class der extends base
int j ;public der( )
j = i * 4 ;
class Program
public static void main ( .. )
der d = new der( ) ;
Construction always proceedsfrom base towards derived
Conflict...
class derived extends base
int i = 9 ;
class base
protected int i = 13 ;…
public void fun( )
System.out.println ( i + " " + super.i ) ;
9 13
class shape
final void draw( )
S.o.p ( "shape" ) ;
class circle extends shape
void draw( )
S.o.p ( "circle" ) ;
Error
final class shape
void draw( )
S.o.p ( "shape" ) ;
class circle extends shape
void draw( )
S.o.p ( "circle" ) ;
Error
final fun. can’t be overriddenfinal class cannot be inherited
Prevent Inheritance
Enterprise Solutions Using J2EE / Lecture 35 4
Inheritance SummaryBase class - Super class, Parent classDerived class - Sub class, Child classDerived class object contains all base class dataDer. class obj. may not be able to access all base class dataIn inheritance chain construction happens from B to DInheritance facilitates - Inherit, Suppress, ExtendInherit - Do nothingSuppress - Hide base class implementationExtend - super.Baseclassmethod( )final - Prevent inheritance
Enterprise Solutions Using J2EE / Lecture 36 1
Exception Handling - IYashavant Kanetkar
ObjectivesWhen things may go wrongWhat can go wrong during executionTypes of ExceptionsWays to tackle Exceptional ConditionDifference between Checked & UncheckedHow to tackle Checked Exceptions
Wishful Thinking
I am a good Programmer
Everything isgoing to go well
"My" program would anyway work correctly
Enterprise Solutions Using J2EE / Lecture 36 2
Examples
When Things May Go Wrong
Short of memoryDivide by zeroExceeding the bounds of an arrayStack overflowArithmetic over flow or under flowAttempt to use an unassigned referenceFile not foundUnable to connect to Server
Reported by - CompilerAction - Debug program
Reported by - LinkerAction - Proper imports
Reported by - Java RuntimeAction - Tackle it on the fly
During Compilation
During Linking
During Execution
What Can Go Wrong During Execution
Occurrence of Exceptional Condition
Due to Internal Cond.
Due to External Cond.
Can be anticipated
Recovery possible
Can't be anticipated
Recovery Impossible
File not found Insufficient memory
Passing null instead of filename
Disk failure while reading
k/a Checked Exceptions
k/a Runtime Exceptions k/a Errors
Tackling Exceptional Condition• Exceptional conditions occur during method execution• All Exceptional Conditions are tackled in OO manner• Info @ exceptional condition is packed into an object• Java provides a class hierarchy to represent Exc. cond.
Object
Throwable
Error Exception
RuntimeException...
...
...
External Unchecked
Internal Unchecked
Checked Cond.
Enterprise Solutions Using J2EE / Lecture 36 3
Tackling Checked ExceptionsMethod called from client code is executing
Exceptional Condition occurs
Pack exception info. in an object
Let Java Runtime pack exception info. in an object
Throw the object
Do nothing Catch the object in client code
Rectify & continue Graceful exitDefault exception handlerCatches the object
Prints Stack Trace& terminates
Case 3Case 2
Case 1
import java.io.* ;public class Case1
public static void main ( String[ ] args ) throws Exception
int i ;BufferedReader b ;b = new BufferedReader ( new InputStreamReader (
System.in ) ) ;System.out.println ( "Enter a number: " ) ;i = Integer.parseInt ( b.readLine( ) ) ;
Case 1: Do Nothing
Exception in thread "main" java.lang.NumberFormatException: For input string: "abc"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)at java.lang.Integer.parseInt(Integer.java:447)at java.lang.Integer.parseInt(Integer.java:497)at Sample.Case1.main(Case1.java:24)
ClumsyBad practice
Why?
Case 2: Recover & Cont.import java.io.* ;public class Case2
public static void main (String[ ] args ) throws Exception
int i ;BufferedReader b ;b = new BufferedReader (
new InputStreamReader ( System.in ) ) ;while ( true )
try
System.out.println ( "Enter a number: " ) ;i = Integer.parseInt ( b.readLine( ) ) ;break ;
catch ( NumberFormatException e )
System.out.println ( "Incorrect Input" ) ;
System.out.println ( "You entered: " + i ) ;
Hope for the best, prepare for the worst policy
Enterprise Solutions Using J2EE / Lecture 36 4
Case 3: Graceful Exitimport java.io.* ;public class Case3
public static void main ( String[ ] args) throws Exception
int i ;BufferedReader b ;b = new BufferedReader ( new
InputStreamReader ( System.in ) ) ;try
System.out.println("Enter a number: ");i = Integer.parseInt ( b.readLine( ) ) ;System.out.println ( "You entered: " + i ) ;
catch ( NumberFormatException e )
System.out.println ( "Incorrect Input." ) ;
Enterprise Solutions Using J2EE / Lecture 37 1
Exception Handling - IIYashavant Kanetkar
ObjectivesA quick recap...How to catch multiple exceptionsHow finally block worksWhat is the purpose of the finally blockHow to tackle unchecked exceptionsNested try statements
Recap...Exceptions are treated as objectsChecked & Unchecked Exceptions3 choices When an exception occurs
Do nothing, Rectify and continue, Graceful exitEnclose code where you anticipate error in try blockCatch the thrown exception in catch blockcatch block must immediately follow the try blockWhen exception is thrown, control goes to catch blockAfter catch block is executed, control goes to the next line after catch block(s) unless there is a return or throw in the catch blockOn calling a method that has advertised that it will throw an excep., you have to either catch or rethrow
Enterprise Solutions Using J2EE / Lecture 37 2
Catching Multiple Exceptionsimport java.io.* ;import java.lang.* ;public class MultipleExceptions
public static void main ( String[ ] args )
int i, j ;BufferedReader b = new BufferedReader (
new InputStreamReader ( System.in ) ) ;try
S.o.p ( "Enter i: " ) ;i = Integer.parseInt ( b.readLine( ) ) ;S.o.p ( "Enter j: ");j = Integer.parseInt ( b.readLine( ) ) ;S.o.p ( "You entered: %d, %d\n", i, j ) ;S.o.p ( "Result: %d\n", i / j ) ;
Contd...
catch ( NumberFormatException ne )
S.o.p ( "Incorrect Input." ) ; catch ( ArithmeticException ae )
S.o.p ( "Arithmetic Exc. / by zero." ) ; catch ( Exception e)
S.o.p ( "Unknown Error: " + e ) ;
...Contd.
Multiple catch blocks are OKAt a time only one catch block goes to work Order of catch blocks is important - Derived to Base
import java.io.*;import java.lang.*;public class Case5
public static void main ( .. )
FileWriter fw = null ;try
fw = new FileWriter ( "a.txt" ) ;fw.write ( "Hello World\n" ) ;
catch ( IOException ie )
S.o.p ( "Encountered IO Error" ) ; finally
finally Block
Contd...
Enterprise Solutions Using J2EE / Lecture 37 3
if ( fw != null )
try
fw.close( ) ; catch ( IOException ex )
S.o.p ( "Cannot close file" ) ;
...Contd.
Code in finally always runs, no matter what!Even if a return or break occurs firstException: System.exit( )
Placed after catch blocks (if they exist)try block must have catch block and/or finally blockfinally clause is optional
Not checked at compilation timeThese are never advertised by methodsTwo types:
Tackling Unchecked Exceptions
Error or its Subclasses
Don't catchYou don't know what to do
- Use Checked exceptions for recoverable conditions - Use Runtime exceptions for programming errors
Runtime or its Subclasses
Ex. Internal Error
Ex. VM Error
Shouldn't happen, Fixed while testingSimilar to Assert( ) macro
Ex. Division by 0
Ex. Improper array index
A try statement can be inside the block of another tryEach time control enters a try, the context of that exception is pushed on the stackIf inner try doesn't have a catch, then the outer try'scatch handlers are inspected for a matchIf method called from a try block has try block withinit, then then it is also nested try
Nested Try Statements
Enterprise Solutions Using J2EE / Lecture 38 1
User-defined ExceptionsYashavant Kanetkar
ObjectivesWhat are user-defined exceptionsWhen do we need to create themHow to create them – ExamplesException etiquettes
User-defined ExceptionsException
Customer
Name Acc No. Bal.
withdraw( )
getbalance( )
myexcep
myexcep( )
message( )
ClientWhile withdrawing, if balance goes below
Rs. 500, throw an exception
Enterprise Solutions Using J2EE / Lecture 38 2
import java.io.* ;public class Customer
private String name ;private int accno ;private int balance ;
public Customer ( String n, int a, int b )
name = n ; accno = a ; balance = b ;public void withdraw ( int amt ) throws BankException
if ( balance - amt <= 500 )throw new BankException ( accno, balance ) ;
balance -= amt ;
Customer Class
Means Need has arisen, so throw
Means If needed would throwIf not, won't throw
public class Client
public static void main ( String[ ] args )
Customer c = new Customer ( "Rahul", 2453, 900 ) ;try
c.withdraw ( 450 ) ; catch ( BankException ex )
System.out.println ( "Transaction failed" ) ;ex.inform( ) ;
Client Class
class BankException extends Exception
private int acc ;private int bal ;public BankException ( int a , int b)
acc = a ;bal = b ;
public void inform( )
System.out.printf ( "Acc. No.: %d\n", acc ) ;System.out.printf ( "Balance: %d\n", bal ) ;
BankException Class
Enterprise Solutions Using J2EE / Lecture 38 3
Exception
Stack
One More Example
push( )pop( )
getSize( )
data[ ]capacity
size
StackException
StackException( )
StackException ( String )
VinodSanjay
353.14
main( )
Create Stack object
push elements
pop elements
package stacktest ;class StackTest
public static void main ( .. )
Stack s = new Stack ( 3 ) ;try
s.push ( "Vinod" ) ;s.push ( "Sanjay" ) ;s.push ( new Integer ( 25 ) ) ;s.push ( new Float ( 3.14f ) ) ;
catch ( StackException x )
S.o.p ( x ) ;
try
while ( s.getSize( ) > 0 )S.o.p ( s.pop( ) ) ;
catch ( StackException x )
S.o.p ( x ) ;
StackTest Class
class Stack
private int capacity ;private int size ;private Object[ ] data ;
public Stack ( int cap )
data = new Object [ cap ] ;capacity = cap ; size = 0 ;
public void push ( Object o ) throws StackException
if ( size == capacity )throw new StackException ( "Stack full" ) ;
data[ size++ ] = o ;
Stack Class
Contd...
Enterprise Solutions Using J2EE / Lecture 38 4
public Object pop( ) throws StackException
if ( size <= 0 )throw new StackException ( "Stack empty" ) ;
return data [ --size ] ;
public int getSize( )
return size ;
...Contd.
class StackException extends Exception
StackException( )
StackException ( String msg )
super ( msg ) ;
StackException Class
Exception EtiquetteSet val. in a public static var. (like global) in some classReturn a boolean, int, string or an object from a methodDon’t catch & ignore
Don't use exception handling for cosmetic purposeDon't catch everything using ExceptionAlways try to distinguish between types of exceptionsMake it optimally elaborate – not too much, not too little
catch ( Exception e )
Enterprise Solutions Using J2EE / Lecture 39 1
Abstract ClassesYashavant Kanetkar
Objectives
♦ What is dynamic despatch mechanism
♦ What are abstract classes
♦ How to construct abstract classes & methods
♦ Example programs to demonstrate abstract Classes
♦ What can be / cannot be done using abstract classes
class Shape
void Draw( ) class Circle extends Shape
void Draw( )
S.o.p ( "Circle" ) ;
class Rect extends Shape
void Draw( )
S.o.p ( "Rectangle" ) ;
public class Myclass
public static void main ( String args[ ] )
Circle c1, c2, c3 ;c1 = new Circle( ) ;...rect r1, r2, r3 ;r1 = new Rect( ) ;...Shape s[ ] = c1, r2, … ;for ( int i = 0 ; i <= 5 ; i++ )
s[ i ].Draw( ) ;
Dynamic Dispatch Mechanism
Calls suitabledraw( )How to prevent creation of Shape objects
Enterprise Solutions Using J2EE / Lecture 39 2
Example I
PrinterCtor( )print( )
String name
LaserPrinter
Ctor( )print( )
InkjetPrinter
Ctor( )print( )
♦ Every printer uses its own way to print♦ Application should be able to print to any printer♦ Application need to know only name of the printer to print♦ To do the printing application should merely call print( )
Abstract class
Derived classes
Usagepackage abstractdemo ;import java.io.* ;public class AbstractDemo
public static void main ( String[ ] args )
Printer p = new LaserPrinter ( "LaserJet 1100" ) ;p.print ( "hello1.pdf" ) ; p = new InkjetPrinter ( "IBM 2140" ) ;p.print ( "hello2.doc" ) ;
Abstract Classabstract class Printer
protected String name ;public Printer ( String n )
name = n ;public abstract void print ( String docName ) ;
♦ Object cannot be created from abstract class♦ An abstract class can contain abstract & non-abstract fun.♦ Abstract class may contain instance & static variables♦ These variables may be inherited♦ Abstract methods do not have a body♦ Abstract classes can participate in inheritance♦ If a class contains abstract methods class has to be abstract
Partial Implementation
Enterprise Solutions Using J2EE / Lecture 39 3
class LaserPrinter extends Printer
public LaserPrinter ( String n ) super ( n ) ; public void print ( String docName )
System.out.println ( " >> LaserPrinter.print" ) ;
class InkjetPrinter extends Printer
public InkjetPrinter ( String n ) super ( n ) ; public void print ( String docName )
System.out.println ( " >> InkjetPrinter.print" ) ;
Derived Classes
Example II
Image
filename
GIFImage
Ctor( )Load( )
JPEGImage
Ctor( )Load( )
♦ Each image format is different♦ Design classes to load / save different images♦ It should be possible to extend design to accommodate
new images in future
Create( )setImage( )
Load( )Save( )
Usagepackage abstractimagedemo ;import java.io.* ;
public class AbstractImageDemo
public static void main ( String[ ] args )
Image i = Image.Create ( "test.jpg" ) ;i.Load( ) ;i = Image.Create ( "test.gif" ) ;i.Load( ) ;
Class factory function
Creates appropriate object based on extension
Upcasting
Dyn. dispacth
Enterprise Solutions Using J2EE / Lecture 39 4
Abstract Classabstract class Image
protected String fileName ;public void setImage ( String f )
this.fileName = f ;public static Image Create ( String f )
if ( f.toLowerCase( ).endsWith ( ".jpg" ) ) return new JPEGImage ( f ) ;
else if ( f.toLowerCase( ).endsWith ( ".gif" ) ) return new GIFImage ( f ) ;
return null ;
Contd...
public void Save ( char[ ] buf ) throws IOException
FileWriter fw = new FileWriter ( fileName ) ;fw.write ( buf ) ;fw.close( ) ;
public abstract void Load( ) ;
...Contd. Need not be abstract
How to save is same for any image
Should be abstract
Each type of image is loaded differently
Derived Classesclass JPEGImage extends Image
public JPEGImage ( String f ) setImage ( f ) ;
public void Load( )
System.out.println ( " >> JPEGImage.Load" ) ;
class GIFImage extends Image
public GIFImage ( String f ) setImage ( f ) ;
public void Load( )
System.out.println ( " >> GIFImage.Load" ) ;
Enterprise Solutions Using J2EE / Lecture 40 1
InterfacesYashavant [email protected]
Objectives
♦ What are interfaces♦ How are they different than abstract classes♦ In which different situations can we use interfaces♦ Sample programs to demonstrate the situations
What Are Interfaces♦ Collections of functions declarations♦ Fun. are defined in classes that implement the int.
interface Mouse
void lbtndn ( Point p ) ;void rbtndn ( Point p ) ;
class GeniusM implements Mouse
public void lbtndn ( Point p )
S.o.p ( "Left Button" ) ;public void rbtndn ( Point p )
S.o.p ( "Right Button" ) ;
♦ Different classes may implement the same interface♦ A class can implement any number of interfaces
Keyword
What a class must do
How to do it
Enterprise Solutions Using J2EE / Lecture 40 2
Interfaces V/s Abstract Classes
♦ Abstract class functions may have a body ♦ Interface functions never have a body♦ Abstract class may contain instance variables
♦ These variables may be inherited♦ Interface may contain variables
♦ These variables can be accessed♦ These variables are by default static and final
Interface ScenariosI. Permit focused view of a large implementation
Encrypt( )Decrypt( )
Compress( )Decompress( )
Authorize( )Authenticate( )
II. Provide different implementation of same tasks
III. Inherit desired qualities from unrelated sources
Count( ), Insert( )Add( ), Remove( )
ArrayCount( ), Insert( )Add( ), Remove( )
Linked List
♦ I want looks of John Abraham♦ I want character of Dr. Kalam
♦ I only want character of Dr. Kalam
I. Different Implementationpackage diffimpl ;import java.io.* ;public class DiffImpl
public static void main ( String[ ] args )
IListMethods i ;i = new MyArray( ) ;i.Add ( 1 ) ; i.Remove ( 1 ) ; i.Count( ) ;i = new MyLL( ) ;i.Add ( 1 ) ; i.Remove ( 1 ) ; i.Count( ) ;
1/4
Enterprise Solutions Using J2EE / Lecture 40 3
Interface
interface IListMethods
public int Count( ) ;public void Add ( Object o ) ;public void Remove ( Object o ) ;
2/4
Array Implementationclass MyArray implements IListMethods
public int Count( )
System.out.println ( " >> MyArray.Count" ) ;return 0 ;
public void Add ( Object o )
System.out.println ( " >> MyArray.Add" ) ;public void Remove ( Object o )
System.out.println ( " >> MyArray.Remove" ) ;
3/4
Linked List Implementationclass MyLL implements IListMethods
public int Count( )
System.out.println ( " >> MyLL.Count" ) ;return 0 ;
public void Add ( Object o )
System.out.println ( " >> MyLL.Add" ) ;public void Remove ( Object o )
System.out.println ( " >> MyLL.Remove" ) ;
4/4
Enterprise Solutions Using J2EE / Lecture 40 4
II. Focussed Viewpublic class InterfaceDemo
public static void main ( String[ ] args )
FocussedView o = new FocussedView( ) ;IEncrypt ie = o ;ie.Encrypt( ) ;ie.Decrypt( ) ; ICompress ic = o ;ic.Compress( ) ;ic.Decompress( ) ;IAuth ia = o ;ia.Login( ) ;ia.Logout( ) ;// ia.Compress( ) ; compiler error
1/3
Interfacespackage ooconcepts ;import java.io.* ;interface IEncrypt
public void Encrypt( ) ;public void Decrypt( ) ;
interface ICompress
public void Compress( ) ;public void Decompress( ) ;
interface IAuth
public void Login( ) ;public void Logout( ) ;
2/3
Implementationpublic class FocussedView
implements IEncrypt, ICompress, IAuth
public void Encrypt( )
S.o.p ( " >> Encrypt" ) ;public void Decrypt( )
S.o.p ( " >> Decrypt" ) ;public void Compress( )
S.o.p ( " >> Compress" ) ;
public void Decompress( )
S.o.p ( " >> Decomp." ) ;public void Login( )
S.o.p ( " >> Login" ) ;public void Logout( )
S.o.p ( " >> Logout" ) ;
3/3
Enterprise Solutions Using J2EE / Lecture 40 5
III. Qualitiespackage ooconcepts ;import java.io.* ;public class Qualities
public static void main ( String[ ] args )
Model m ;Actor myself ;myself = new Actor( ) ;m = myself ; m.style( ) ; ICharacter ch ;ch = myself ;ch.patriotism( ) ;
1/3
Interface & Model Class
interface ICharacter
public void patriotism( ) ;
class Model
protected String hairstyle ;public void style( )
System.out.println ( ">> Model.style" ) ;
2/3
Actor Classclass Actor extends Model implements ICharacter
public void doActing( )
System.out.println ( ">> Actor.doActing" ) ;public void style( )
super.style( ) ;System.out.println ( ">> Actor.style" ) ;
public void patriotism( )
System.out.println ( ">> Character.patriotism" ) ;
3/3
Enterprise Solutions Using J2EE / Lecture 41 1
Interfaces IIYashavant Kanetkar
Objectives
♦ Interface recap...♦ Bow and Arrow - Class Design♦ Bow and Arrow - Program
Recap...♦ Interfaces are not derived from Object class♦ Interfaces are not derived from any base interface♦ Interfaces contains only method declarations♦ Interfaces may contain static and final data♦ Objects cannot be created from interfaces♦ A class can implement multiple interfaces♦ Interfaces can be inherited♦ Multiple interface inheritance is allowed♦ Class cannot implement an interface partially♦ Interface can be used in three situations:
♦ Focused view♦ Different implementation of same task♦ Alternative for multiple inheritance
Enterprise Solutions Using J2EE / Lecture 41 2
Bow & Arrow
Set steps for Shooter and BalloonsMake movement for Shooter and Balloons
Classes
Bow & Arrow
Shooter TimerBalloon
setstep( )move( )
setstep( )move( )
TargetTimerPerson
Possible Solution
Shooter s1 = new Shooter( ) ;Balloon b1 = new Balloon( ) ;Balloon b2 = new Balloon( ) ;Timer t [ ] = s1, b1, b2 ;
for ( int i = 0 ; i < 3 ; i++ )t [ i ] . setstep ( r . nextInt ( 5 ) ) ;
for ( int i = 0 ; i < 3 ; i++ )t [ i ] . move( ) ;
Random r = new Random( ) ;
Problems :
Unnatural relationshipNo Multiple Inheritance
Shooter Balloon
Enterprise Solutions Using J2EE / Lecture 41 3
Correct Solution
TargetITimerPerson
Shooter BalloonImplement
Timer Interfaceinterface ITimer
void setstep ( int n ) ;void move( ) ;
class Shooter extends Person implements ITimer
private int step ;public void setstep ( int s )
step = s ;
public void move( )
S.o.p ( "Shooter moved: " + step ) ;step++ ;
Shooter Class
Enterprise Solutions Using J2EE / Lecture 41 4
class Balloon extends Target implements ITimer
private int step ;public void setstep ( int s )
step = s ;
public void move( )
S.o.p ( "Balloon moved: " + step ) ;step++ ;
Balloon Class
public class BowAndArrow
static public void main ( String args[ ] )
Shooter s1 = new Shooter( ) ;Balloon b1 = new Balloon( ) ;Balloon b2 = new Balloon( ) ;ITimer t [ ] = s1, b1, b2 ;Random r = new Random( ) ;for ( int i = 0 ; i < 3 ; i++ )
t [ i ] . setstep ( r . nextInt ( 5 ) ) ;for ( int i = 0 ; i < 3 ; i++ )
t [ i ] . move( ) ;
BowAndArrow Class
Enterprise Solutions Using J2EE / Lecture 42 1
Packages - IYashavant Kanetkar
Objectives♦ Anatomy of a NetBeans Project♦ What are packages♦ What do we gain from using packages♦ How to create packages and use them
Anotomy Of A NetBeans Project
C:\Users\Kanetkar\JavaPrograms\J43C:\Documents and Settings\Kanetkar\JavaPrograms\J43
Vista
Project NamePath
XP
Enterprise Solutions Using J2EE / Lecture 42 2
Project Contents
.java Files .class Files .jar + javadoc Files
ant Script (build-impl.xml)
For customizing ant Script
Test classes
Version info
NetBeans ViewsProject View Files View
Package PkgWhat Are Packages
Package acts as a container for related typesPackage provides access protectionPackage makes is easy to locate and use typesPackage helps in avoiding naming conflicts
fun1( )fun2( )
var1var2
fun3( )fun4( )
var3var4
Class A Class B Enumeration
fun5( ) ;
Interface I
fun6( ) ;
fun7( ) ;Annotation
Enterprise Solutions Using J2EE / Lecture 42 3
What Do We Gain
Intuitive indication for everyone that these types are relatedIndication of where to find graphics-related functions. Package creates a new namespace Helps avoid conflict of type-names with names in other pkgTypes in the pkg have unrestricted access to one anotherYet lets restrict access to types outside the package
Package Graphics
class Rectangle
class Freehand
class Spline
class Circle
package simpleinterest ;public class SimpleInterest
public float calculateSi ( float p, int n, float r )
float si ;si = p * n * r / 100 ;return ( si ) ;
Package Declaration
To access a type outside the package it should be public
A file can have only one public type in itNames of .java file and public type in it should be same
Must be first line Only 1 package stat. per file
Applies to all types in this file
Package Usage 1/3
Enterprise Solutions Using J2EE / Lecture 42 4
2/3
3/3
C:\Documents and Settings\kanetkar\JavaPrograms\J43\src\j43C:\Documents and Settings\kanetkar\JavaPrograms\J43\src\sample
Result
Sample.java
public class Sample
public void show( )
S.o.p ( "Hello" ) ;
Client.java
public class Client
public static void main( .. )
Sample a = new Sample( ) ;
package sample ; package client ;import sample.Sample ;
a.show( ) ;
If import is not done, use fully qualified name sample.Sample a = new sample.Sample( ) ;
Enterprise Solutions Using J2EE / Lecture 42 5
Package FAQs
How do I ensure uniquenessUse reversed Internet domain name com.ksetindia.simpleinterestcom.ksetindia.quest
What if package name is absent?All types in the file belong to default package
Should package name be in small case?Good idea. Used by NetBeansAvoids name conflict with class / interface names
Pkgs in the Java language itself begin with java. or javax.
what if there is a name conflict within the companyEvolve a convention to resolve it
What if there is a hyphen in domain namereplace it with underscorecom.google-ads com.google_ads
Enterprise Solutions Using J2EE / Lecture 43 1
Packages - IIYashavant Kanetkar
Objectives♦ What are split packages♦ How to access types in multiple packages♦ How to create and use nested packages♦ Access control mechanisms
public class Sample1
public void show( )
S.o.p ( "Hello" ) ;
package sample ;public class Sample2
public void display( )
S.o.p ( "Hi" ) ;
package sample ;
Split Package
C:\Docume~1\kanetkar\JavaPrograms\J44\src\sample\sample1.javaC:\Docume~1\kanetkar\JavaPrograms\J44\src\sample\sample2.java
C:\Docume~1\......................\J44\build\classes\sample\sample1.classC:\Docume~1\......................\J44\build\classes\sample\sample2.class
File | New File, Type and Save
Enterprise Solutions Using J2EE / Lecture 43 2
Using Split Package
class Client
public static void main ( String args[ ] )
Sample1 s1 = new Sample1( ) ;
import sample.Sample2 ;import sample.Sample1 ;
Sample2 s2 = new Sample2( ) ;s1.show( ) ;
s2.display( ) ;
package j44 ;
A package can be split over multiple filesEach file can contain only one public type
import sample.*
* means import all public types present in sample package
Multiple Packages
public class Sample
public void show( )
S.o.p ( "Hello" ) ;
package sample1 ;public class Sample
public void display( )
S.o.p ( 'Hi" ) ;
package sample2 ;
C:\Docume~1\kanetkar\JavaPrograms\J45\src\sample1\sample.javaC:\Docume~1\kanetkar\JavaPrograms\J45\src\sample2\sample.java
C:\Docume~1\......................\J45\build\classes\sample1\sample.classC:\Docume~1\......................\J45\build\classes\sample2\sample.class
File | New File, Type and Save
Using Multiple Packages
class Client
public static void main ( String args[ ] )
sample1.Sample s1 = new sample1.Sample( ) ;
import sample2.Sample ;import sample1.Sample ;
sample2.Sample s2 = new sample2.Sample( ) ;s1.show( ) ;
s2.display( ) ;
package J45 ;import sample1.* ;import sample2.* ;
Can be deleted as we are using fully qualified names
True in all cases
Enterprise Solutions Using J2EE / Lecture 43 3
Nested Packages
public class Sample
public void show( )
S.o.p ( "Hello" ) ;
package sample ;public class Trial
public void display( )
S.o.p ( "Hi" ) ;
package sample.trial ;
Using Nested Packages
class Client
public static void main ( String args[ ] )
Sample s = new Sample( ) ;
import sample.trial.Trial ;import sample.Sample ;
Trial e = new Trial( ) ;s.show( ) ;
e.display( ) ;
import sample.*
import FAQs
Are the following set of statements same
Which packages are imported by default?default package, java.lang, current package
Which packages would get imported by import graphics.A*;None. Compilation error.
Import all public types from dir C:\.....\example\ex1Import all public types from dir C:\.....\example\ex2\ex3
What do the following import statements mean? import example.ex1.* ;import example.ex2.ex3.* ;
import java.awt.shape.*import java.awt.color.* import java.awt. *
If a class is present in 2 packages will the code compileYes. Till we don't start using it
Enterprise Solutions Using J2EE / Lecture 43 4
Same Package's Classpackage p1 ;public class First
staticpublic void main ( .. )
Myclass m = new Myclass( ) ;S.o.p ( m.pri ) ;
package p1 ;class Myclass
private int pri = 10 ;public int pub = 20 ;protected int pro = 30 ;int no = 40 ;Myclass( )
S.o.p ( m.pub ) ;S.o.p ( m.pro ) ;S.o.p ( m.no ) ;
DefaultError
Works
For same package's subclass the behaviour is same
Different Package's Classpackage p2 ;import p1.Myclass ;public class Second
public static void main ( .. )
Myclass m = new Myclass( ) ;S.o.p ( m.pri ) ;S.o.p ( m.pub ) ;S.o.p ( m.pro ) ;S.o.p ( m.no ) ;
package p1 ;public class Myclass
private int pri = 10 ;public int pub = 20 ;protected int pro = 30 ;int no = 40 ;public Myclass( )
WorksError
Different Package's SubClasspackage p1 ;public class Myclass
private int pri = 10 ;public int pub = 20 ;protected int pro = 30 ;int no = 40 ;public Myclass( )
package p2 ;import p1.Myclass ;public class Second
extends Myclass
public static void main ( .. )
Second m = new Second( ) ;S.o.p ( m.pri ) ;S.o.p ( m.pub ) ;S.o.p ( m.pro ) ;S.o.p ( m.no ) ;
ErrorWorks
Enterprise Solutions Using J2EE / Lecture 43 5
Summary
Same Class
Same Package Class
Different package Class
Different package Subclass
Same Package Subclass
Private No modifier Protected PublicAccessible to
Enterprise Solutions Using J2EE / Lecture 44 1
Effective IO - IYashavant Kanetkar
Objectives♦ Expectations from an IO system♦ How does Java meet these expectations♦ What is stream-based IO model♦ Different types of streams♦ Program to illustrate the difference
Expectations From An IO SystemI should be able to comm. with diff. sources & destination
I should be capable to I/O varied entities
FileKeyboardConsole
Network Port
Printer
Java Program
BytesCharacters
Lines Numbers
RecordsObjects
Java Program
Enterprise Solutions Using J2EE / Lecture 44 2
Expectations From An IO SystemI should be able to communicate in multiple ways
I should be capable of dealing with underlying file system
Sequential AccessRandom Access
Java Program
Permissions
Paths
Times Dates
Files Directories
Java Program
♦ A program can read from a stream or write to a stream♦ Streams hide the details of communication from you♦ Streams are linked to physical devices by Java IO system♦ Streams are implemented using classes in java.io package
Java Solution♦ Perform all IO using Streams♦ Stream is a sequence of bytes that travel from
source to destination over a communication path
Source Java Program
Input Stream
001011
DestinationJava Program
Output Stream
110011
Impl. changes as per deviceMethods used are same
♦ Two types of streams – Byte and Character♦ Byte streams perform i/o one byte at a time♦ Character streams perform i/o one char (2 bytes) at a time♦ Byte streams are used to i/o binary data♦ Character stream are used to i/o text data♦ java.io package has many classes for these streams♦ File utility classes are also present
Byte & Character Streams
Expectations 1,2,3
Expectation 4
Enterprise Solutions Using J2EE / Lecture 44 3
Object
Byte Streams (Binary IO)
FileOutputStream
FilterOutputStream
...
FileInputStream
FilterInputStream
...DataInputStream
BufferedInputStream
DataOutputStream
BufferedOutputStream
PrintStream
♦ InputStream, OutputStream - Abstract classes♦ FileInputStream, FileOutputStream - R/W streams of bytes from file♦ FilterInputStream - Uses some input stream as source of data
It filters data for contained stream♦ BufferedInputStream - Provides buffering ability♦ DataInputStream - Provides ability to read Java primitives
InputStream
OutputStream
Character Streams (Text IO)
Object
FileReader
FileWriter
Reader
Writer
BufferedReader
InputStreamReader
...
BufferedWriter
OutputStreamWriter
PrintWriter
...
♦ Reader, Writer - Abstract classes♦ InputStreamReader, OutputStreamWriter - R/W char from/to stream♦ FileReader, FileWriter - R/W characters from/to file♦ PrintWriter - Formatted writing in text representation
package basicio ;import java.io.* ;public class BasicIO
public static void main ( String[ ] args ) throws IOException
int i = 123456 ;RawWrite ( i ) ; CharWrite ( i ) ; UnicodeWrite ( i ) ;
static void RawWrite ( int i ) throws IOException
DataOutputStream ds = new DataOutputStream ( new FileOutputStream ( "Stream.txt" ) ) ;
ds.writeInt ( i ) ; ds.close( ) ; S.o.p ( new File ( "Stream.txt" ).length( ) ) ;
Difference - Byte & Char Streams
Contd...
FileOutputStream
DataOutputStream
4614
Enterprise Solutions Using J2EE / Lecture 44 4
static void CharWrite ( int i ) throws IOException
FileWriter fw = new FileWriter ( new File ( "Char.txt" ) ) ; fw.write ( ( ( Integer ) i ).toString( ) ) ; fw.close( ) ; S.o.p ( new File ( "Char.txt" ).length( ) ) ;
static void UnicodeWrite ( int i ) throws IOException
OutputStreamWriter ow = new OutputStreamWriter ( new FileOutputStream ( "CharU.txt" ), "UTF-16" ) ;
ow.write ( ( ( Integer ) i ).toString( ) ) ; ow.close( ) ; S.o.p ( new File ( "CharU.txt" ).length( ) ) ;
... Contd.
File
FileWriter
FileOutputStreamOutputStreamWriter
Necessary
Enterprise Solutions Using J2EE / Lecture 45 1
Effective IO - IIYashavant Kanetkar
Objectives
♦ Meaning of common IO code snippets♦ Working of Stream IO♦ Reading Strings♦ Record IO
What Were We Using...
import java.io.* ;
System.out.println ( "Hello" ) ;System.out.print ( "Hi" ) ;
int ch ;ch = System.in.read( ) ;
Package
Class PrintStream obj. reference
InputStream obj. reference
public static data members
Derived from OutputStream
Enterprise Solutions Using J2EE / Lecture 45 2
InputStreamReader ir ;ir = new InputStreamReader ( System.in ) ;BufferedReader b ;b = new BufferedReader ( ir ) ;String s ;s = b.readLine( ) ;
What Happens When...
BufferedReader
InputStreamReader
System.inConverts bytes to charsFilters out CR & LF
Reads bytes - stream
Buffers filtered characters
public class Charread
static public void main ( String args[ ] )
class ISR
InputStream q ;ISR ( InputStream p )
q = p ;
class BR
ISR j ;BR ( ISR i )
j = i ;
class InputStream
readLine( )
ISR ir ;ir = new ISR ( System.in ) ;BR b ;b = new BR ( ir ) ;
fun1( )
q.readLine ( str ) ;
s = b.readLine( ) ;
readLine( )
j.fun1( ) ;
// filter CR & LF and returns str
// put chars into buffer & ret.
// reads byte // from stream// and returns it
BufferedReader
InputStreamReader
System.in
public class ReadTest
public static void main ( String[ ] args ) throws IOException
File f = new File ( "src/readtest/ReadTest.java" ) ;if ( f.exists( ) && f.canRead( ) )
BufferedReader br = null ;try
br = new BufferedReader ( new FileReader ( f ) ) ;String line ;while ( ( line = br.readLine( ) ) != null )
System.out.println ( line ) ;
Reading Strings From File
Contd...
Don't put this in try block
Might throw FileNotFoundException
Might throw IOException
Enterprise Solutions Using J2EE / Lecture 45 3
catch ( FileNotFoundException ex )
S.o.p ( "Can't open " + f.getName( ) + " for rdg." ) ; finally
if ( br != null )br.close( ) ;
…Contd.
import java.io.* ;public class Empinfo
static public void main ( String args[ ] ) throws IOException
FileOutputStream fos ;fos = new FileOutputStream ( "emp.dat" ) ;BufferedOutputStream bos ;bos = new BufferedOutputStream ( fos ) ;DataOutputStream dos ;dos = new DataOutputStream ( bos ) ;
Record IO
InputStreamReader isr1 ;isr1 = new InputStreamReader ( System.in ) ;BufferedReader br1 = new BufferedReader ( isr1 ) ;
FormattedBuffered o/p
Contd...
DataOutputStream
BufferedOutputStream
FileOutputStreamBuffers data
Writes to a file
Writes Std. data
For Console input
String choice = "y", temp ;while ( choice.equals ( "y" ) )
S.o.p ( "Enter employee id: " ) ;temp = br1.readLine( ) ;dos.writeInt ( Integer.parseInt ( temp ) ) ;
S.o.p ( "Enter employee salary: " ) ;temp = br1.readLine( ) ;dos.writeDouble ( Double.parseDouble ( temp ) ) ;
S.o.p ( "Enter employee name: " ) ;temp = br1.readLine( ) ;dos.writeBytes ( temp + "\n" ) ;
S.o.p ( "Want another ( y/n ): " ) ;choice = br1.readLine( ) ;
dos.close( ) ;
…Contd.
Contd...
Enterprise Solutions Using J2EE / Lecture 45 4
FileInputStream fis ;fis = new FileInputStream ( "emp.dat" ) ;BufferedInputStream bis ;bis = new BufferedInputStream( fis ) ;DataInputStream dis ;dis = new DataInputStream( bis ) ;
FormattedBuffered
input
For readingString
InputStreamReader isr2 ;isr2 = new InputStreamReader ( dis ) ;BufferedReader br2 ;br2 = new BufferedReader ( isr2 ) ;
…Contd.
Contd...
String s ;int i = 1 ;S.o.p ( "\nEmployees Info: " ) ;while ( true )
S.o.p ( dis.readInt( ) ) ;S.o.p ( dis.readDouble( ) ) ;dis.mark ( 0 ) ;s = br2.readLine( ) ;S.o.p ( s ) ;dis.reset( ) ;dis.skipBytes ( s.length( ) + 1 ) ;br2.skip ( 12 ) ;i++ ;
…Contd.
Enterprise Solutions Using J2EE / Lecture 46 1
Enterprise Solutions Using J2EE / Lecture 46
Effective IO - IIIYashavant Kanetkar
Enterprise Solutions Using J2EE / Lecture 46
Objectives
♦ How to recursively list files♦ How to access Filesystem attributes♦ How to create our own filters
Enterprise Solutions Using J2EE / Lecture 46
package dirread ;import java.io.* ;public class DirRead
static final long OneKb = 1000L ;static final long OneMeg = 1000000L ;static final long OneGig = 1000000000L ;public static void main ( String[ ] args )
listFiles ( new File ( "." ), "" ) ;
Listing Files build/classes/fileio/BasicIO.class [ 1K ]DirRead.class [ 2K ]FileIOTest.class [ 1K ]ReadTest.class [ 1K ]SysPropTest.class [ 588 ]WriterTest.class [ 3K ]
depcache/dependencies.txt [ 1K ]
dist/FileIO.jar [ 12K ]README.TXT [ 1K ]
Recursive Function
Contd...
Directories
Size
Enterprise Solutions Using J2EE / Lecture 46 2
Enterprise Solutions Using J2EE / Lecture 46
public static void listFiles ( File f, String indent )
System.out.println ( indent + f.getName( ) + "/" ) ;File[ ] list ;try
list = f.listFiles( ) ; catch ( SecurityException se )
return ;for ( File ch : list )
if ( !ch.isDirectory( ) ) System.out.println ( indent + " " +
ch.getName( ) + " [ " + getSize ( ch ) + " ]" ) ;
build/classes/fileio/BasicIO.class [ 1K ]DirRead.class [ 2K ]FileIOTest.class [ 1K ]ReadTest.class [ 1K ]SysPropTest.class [ 588 ]WriterTest.class [ 3K ]
depcache/dependencies.txt [ 1K ]
dist/FileIO.jar [ 12K ]README.TXT [ 1K ]
Contd...
Enterprise Solutions Using J2EE / Lecture 46
for ( File ch : list )
if ( ch.isDirectory( ) )listFiles ( ch, indent + " " ) ;
build/classes/fileio/BasicIO.class [ 1K ]DirRead.class [ 2K ]FileIOTest.class [ 1K ]ReadTest.class [ 1K ]SysPropTest.class [ 588 ]WriterTest.class [ 3K ]
depcache/dependencies.txt [ 1K ]
dist/FileIO.jar [ 12K ]README.TXT [ 1K ]
Contd...
…Contd.
Enterprise Solutions Using J2EE / Lecture 46
public static String getSize ( File f )
String szStr = "" ; long size = f.length( ) ;if ( size < OneKb )
return Long.toString ( size ) ;if ( size > OneGig )
szStr = szStr + Long.toString ( size / OneGig ) + "," ;size = size % OneGig ;
if ( size > OneMeg )
szStr = szStr + Long.toString ( size / OneMeg ) + "," ;size = size % OneMeg ;
if ( size > OneKb )
szStr = szStr + Long.toString ( size / OneKb ) + "K" ;return szStr ;
Enterprise Solutions Using J2EE / Lecture 46 3
Enterprise Solutions Using J2EE / Lecture 46
package fileiotest ;import java.io.* ;import java.security.* ;public class FileIOTest
public static void main ( String[ ] args ) throws IOException
String fName = "FileIOTest.txt" ;File f = new File ( fName ) ; try
f.createNewFile( ) ;f.setReadOnly( ) ;// Following statement should generate an exceptionFileWriter fw = new FileWriter ( f ) ;fw.close( ) ;
File Class Usage
Contd...
Enterprise Solutions Using J2EE / Lecture 46
catch ( FileNotFoundException fne )
f.setWritable ( true, true ) ; // Make writable for owner onlyFileWriter fw = null ;try
fw = new FileWriter ( f ) ;fw.write ( "Hello World\n" ) ;S.o.p ( "Wrote to " + fName ) ;S.o.p ( f.getAbsolutePath( ) ) ;File d ;d = new File ( "d1" ) ;d.mkdir( ) ;// Recursively build entire pathd = new File ( "d2/d3/d4" ) ;d.mkdirs( ) ;
…Contd.
finally
fw.close( ) ;
Enterprise Solutions Using J2EE / Lecture 46
Filter Streams
BufferedReader
UppercaseReader
FileReader
abcdefghijk
ABCDEFGHIJK
Upper-case Filter
Reader
FilterReader
Abstract
Enterprise Solutions Using J2EE / Lecture 46 4
Enterprise Solutions Using J2EE / Lecture 46
Uppercase Filterpackage uppercasereader ;import java.io.* ;public class UppercaseReader extends FilterReader
public static void main ( String[ ] args ) throwsFileNotFoundException, IOException
File f = new File ( "src/fileio/UppercaseReader.java" ) ;if ( f.exists( ) && f.isFile( ) && f.canRead( ) )
BufferedReader br = new BufferedReader ( newUppercaseReader ( new FileReader ( f ) ) ) ;
String line ;while ( ( line = br.readLine( ) ) != null )
System.out.println ( line ) ;
BufferedReader
UppercaseReader
FileReader
Enterprise Solutions Using J2EE / Lecture 46
public UppercaseReader ( Reader in )
super ( in ) ;private int transform ( int ch )
if ( ch != -1 && Character.isLowerCase ( ch ) ) return Character.toUpperCase ( ch ) ;
return ch ;public int read( ) throws IOException
int ch = in.read( ) ;return transform ( ch ) ;
Helper Functions
Reads one char
Underlying characterinput stream
protected Reader in In FilterReader
Enterprise Solutions Using J2EE / Lecture 46
public int read ( char[ ] cbuf, int off, int len ) throws IOException
int rc = in.read ( cbuf, off, len ) ;for ( int i = off ; i < off + rc ; i++ )
cbuf [ i ] = ( char ) transform ( cbuf [ i ] ) ;return rc ;
Helper FunctionsReads characters in
a portion of array- Start from where- Read how many
Returns how many charsare read succesfully
Enterprise Solutions Using J2EE / Lecture 47 1
Filter & Other StreamsYashavant Kanetkar
Objectives
♦ Input and Output Filters♦ How to create output filters♦ What are predefined streams♦ Streams overview♦ Tokenizer program
Interface ITransform
int transform ( int ch ) ;
Encrypt / Decrypt Filter
abcdefghijk
fhkzmdcbnoy
Common Filter
Encrypt
Decrypt
Uses Substitution Cipher
Encrypt Decrypt
Enterprise Solutions Using J2EE / Lecture 47 2
Encryptionpackage fileio ;import java.io.* ;interface ITransform
int transform ( int ch ) ;class Encrypt implements ITransform
static final String str = "xyfagchbimpourvnqsdewtkjzl" ;public int transform ( int ch )
if ( Character.isLowerCase ( ch ) )ch = str.charAt ( ch - 'a' ) ;
return ch ;
Returns charin the string
If ch = 'b'
ch – 'a'
1
y
Decryption
class Decrypt implements ITransform
static final String str = "xyfagchbimpourvnqsdewtkjzl" ;public int transform ( int ch )
if ( Character.isLowerCase ( ch ) ) ch = str.indexOf ( ch ) + 'a' ;
return ch ;
Must be sameas in Encrypt( )
Returns positionin the string
If ch = 'y'
1
1 + 'a'
b
TransformWriter Class
public class XformWriter extends FilterWriter
public static void main ( String[ ] args) throws IOExceptiondoEncDec ( "src/fileio/XformWriter.java", "enc.txt", true ) ;doEncDec ( "enc.txt", "dec.txt", false ) ;
// more functions here
XformWriter.java enc.txtEncrypt
dec.txtDecrypt
Enterprise Solutions Using J2EE / Lecture 47 3
public static void doEncDec ( String s, String t, boolean flag ) throws IOException
XformWriter out = new XformWriter ( new PrintWriter ( t ),
flag ? new Encrypt( ) : new Decrypt( ) ) ;File f = new File ( s ) ;BufferedReader br = new BufferedReader ( new FileReader ( f ) );String line ;
String sep = System.getProperty ( "line.separator" ) ;while ( ( line = br.readLine( ) ) != null )
out.write ( line + sep ) ;out.close( ) ;
private ITransform trans = null ;public XformWriter ( PrinterWriter out, ITransform t )
super ( out ) ; this.trans = t ;
Driver Fun.
XformWriter
PrintWriter
BufferedReader
FileReader
write( )spublic void write ( int c ) throws IOException
out.write ( trans.transform ( c ) ) ;public void write ( char[ ] ch, int off, int len )
throws IOException
for ( int i = off ; i < off + len ; i++ )ch [ i ] = ( char ) trans.transform ( ch[ i ] ) ;
super.write ( ch, off, len ) ;public void write ( String str, int off, int len )
throws IOException
char[ ] ch = str.toCharArray( ) ;write ( ch, off, len ) ;
The Predefined streams
♦ java.lang package defines a class called System♦ It contains three predefined public static var. - in, out, err♦ They are accessible from any part of the program ♦ System.out refers to standard output stream (console)♦ System.in refers to standard input stream (keyboard)♦ System.err refers to standard error stream (console)♦ These streams are already open & ready to supply/accept
input/output data
Enterprise Solutions Using J2EE / Lecture 47 4
Streams Overview
♦ Five group of classes are defined in java.io♦ For building different types of byte & character streams♦ For filtering and piping♦ For reading/writing primitive values and strings♦ For Interacting with files♦ For object serialization
♦ Reader provides a char.stream analogous to byte stream InputStream♦ Writer provides a char. stream analogous to byte stream OutputStream♦ Methods of Reader mirror those of InputStream♦ Methods of Writer mirror those of OutputStream♦ InputStreamReader & OutputStreamWriter are converter classes♦ They translate between character and byte streams ♦ They use either a specified character set encoding or the default
encoding for the local system
♦ Streams that have i/o pairs + byte stream & character stream variants♦ Filter streams♦ Buffered streams
♦ In-memory streams:♦ ByteArray streams♦ CharArray streams♦ String streams
♦ I/O Streams that have no O/I counterpart:♦ The Print streams♦ LineNumberReader♦ SequenceInputStream
♦ Streams that are useful for building parsers♦ Pushback streams♦ Tokenizer streams
Specials Streams
- Parse input stream into "tokens"- Allows tokens to be read one at a time
Represents concatenationof underlying input streams
- Lets you push back, or “unread” chars- Useful for breaking input into tokens
Simple Tokenizer
Gomadic charged us 27.50$ for Ipaq charger.(However they didn't provide the Tracking number.)
Tokens.txt
(1) Gomadic(1) charged(1) us(1) 27.5(1) $(1) for(1) Ipaq(1) charger(1) .(2) ((2) However(2) they(2) didn't(2) provide(2) the(2) Tracking(2) number(2) .(2) )
Enterprise Solutions Using J2EE / Lecture 47 5
Program
package mytokenizer ;import java.io.* ;public class MyTokenizer
public static void main ( String args[ ] ) throws Exception
FileReader fr = new FileReader ( "tokens.txt" ) ;BufferedReader br = new BufferedReader ( fr ) ;StreamTokenizer st = new StreamTokenizer ( br ) ;
st.ordinaryChar ( '.' ) ;st.wordChars ( '\'', '\'' ) ;while ( st.nextToken( ) != StreamTokenizer.TT_EOF )
switch ( st.ttype )
Recognizes:IdentifiersNumbersStringsComments
Treat . as a ordinary character
Treat ' as part of word
case StreamTokenizer.TT_WORD :S.o.p ( "(" + st.lineno( ) + ") " + st.sval ) ;break ;
case StreamTokenizer.TT_NUMBER :S.o.p ( "(" + st.lineno( ) + ") " + st.nval ) ;break ;
default :S.o.p ( "(" + st.lineno( ) + ") " + ( char ) st.ttype ) ;
fr.close( ) ;
Enterprise Solutions Using J2EE / Lecture 48 1
SerializationYashavant Kanetkar
Objectives
♦ What is Serialization & Deserialization♦ Where is it useful♦ How to Serialize selectively♦ Problems in selective Serialization♦ How to overcome the selective Serialization problems♦ Program to illustrate Serialization of a collection
Serialization
♦ Storing objects persistently♦ Store in a form that Restoration becomes possible♦ While reconstructing, Ctor is not called♦ Use 1 - Inter-process communication becomes simple♦ Use 2 - Storing objects in database♦ Use 3 - Profiles / Preferences - Example myYahoo
Time of obj. creationIdNamePrice
Cart.datSerialization
Deserialization
Enterprise Solutions Using J2EE / Lecture 48 2
Programpackage serialization1 ;import java.io.* ;import java.util.* ;public class Serialization1
static final String fname = "cart.dat" ;public static void main ( String[ ] args ) throws IOException,
ClassNotFoundException, InterruptedException
Product p1, p2 ;p1 = new Product ( 1, "Quest", 500.0f ) ;saveObject ( p1 ) ;Thread.sleep ( 2000 ) ;p2 = restoreObject( ) ;System.out.println ( p1 ) ;System.out.println ( p2 ) ;
[ Wed Oct 24 14:25:24 IST 2007, 1, Quest, 500.0 ][ Wed Oct 24 14:25:24 IST 2007, 1, Quest, 500.0 ]
Do nothing for next 2 seconds
Save and Restore
static void saveObject ( Product p ) throws IOException
ObjectOutputStream out ;out = new ObjectOutputStream( new FileOutputStream(fname));out.writeObject ( p ) ;out.close( ) ;
static Product restoreObject( ) throws IOException,
ClassNotFoundException
ObjectInputStream in ;in = new ObjectInputStream ( new FileInputStream ( fname ) ) ;Product p = ( Product ) in.readObject( ) ;in.close( ) ;return p ;
Product Classclass Product implements Serializable
private int id ; private String Name ;private float price ; private Date creationTime ;public Product( )
creationTime = new Date( ) ; S.o.p ( " 0-arg Ctor" ) ;public Product ( int num, String name, float p )
creationTime = new Date( ) ;id = num ; Name = name ; price = p ; S.o.p ( "3-arg Ctor" ) ;
public String toString( )
return "[ " + creationTime + ", " + id + ", " +Name + ", " + price + " ]";
Enterprise Solutions Using J2EE / Lecture 48 3
Transient Dataclass Product implements Serializable
private int id ; private String Name ; private float price ; transient private Date creationTime ;public Product( )
..public Product ( int num, String name, float p )
..public String toString( )
..
[ Wed Oct 24 14:35:15 IST 2007, 1, Quest, 500.0 ][ null, 1, Quest, 500.0 ]
Solutionclass Product implements Serializable
private int id ; private String Name ; private float price ;transient private Date creationTime ;
// 0-arg Ctor// 3-arg Ctor// toString( ) method
private void readObject ( ObjectInputStream in )throws IOException, ClassNotFoundException
in.defaultReadObject( ) ;creationTime = new Date( ) ;
[ Wed Oct 24 14:34:28 IST 2007, 1, Quest, 500.0 ]
[ Wed Oct 24 14:34:30 IST 2007, 1, Quest, 500.0 ]
Product List Serializationpackage serialization2 ;import java.io.* ;import java.util.* ;public class Serialization2
static final String fname = "cart.dat" ;public static void main ( String[ ] args )
throws IOException, ClassNotFoundException, InterruptedException
ProductList pl1 = new ProductList( ) ;saveObjectList ( pl1 ) ;Thread.sleep ( 2000 ) ;ProductList pl2 ;pl2 = restoreObjectList( ) ;System.out.println ( pl1 ) ;System.out.println ( pl2 ) ;
[[ [ Wed Oct 24 14:41:25 IST 2007, 0, Quest0, 550.0 ][ Wed Oct 24 14:41:25IST 2007, 1, Quest1, 550.0 ] ]][[ [ Wed Oct 24 14:41:27 IST 2007, 0, Quest0, 550.0 ][ Wed Oct 24 14:41:27IST 2007, 1, Quest1, 550.0 ] ]]
Enterprise Solutions Using J2EE / Lecture 48 4
Save & Restorestatic void saveObjectList ( ProductList p ) throws IOException
ObjectOutputStream out ;out = new ObjectOutputStream ( new FileOutputStream (
fname ) ) ;out.writeObject ( p ) ;out.close( ) ;
static ProductList restoreObjectList( ) throws IOException,
ClassNotFoundException
ObjectInputStream in ;in = new ObjectInputStream ( new FileInputStream( fname ));ProductList p = ( ProductList ) in.readObject( ) ;in.close( ) ;return p ;
...Contd.
Product Classclass Product implements Serializable
private int id ; private String Name ; private float price ;transient private Date creationTime ;public Product( )
creationTime = new Date( ) ;public Product ( int num, String name, float p )
creationTime = new Date( ) ;id = num ; Name = name ; price = p ;
public String toString( )
return "[ " + creationTime + ", " + id + ", " +Name + ", " + price + " ]";
Contd...
Product Class Contd.
private void readObject ( ObjectInputStream in )throws IOException, ClassNotFoundException
in.defaultReadObject( ) ;creationTime = new Date( ) ;
...Contd.
Enterprise Solutions Using J2EE / Lecture 48 5
ProductList Classclass ProductList implements Serializable
Product[ ] plist = new Product [ 2 ] ;public ProductList( )
for ( int i = 0 ; i < plist.length ; i++ )plist[ i ] = new Product ( i, "Quest" + i, 550.0f ) ;
public String toString( )
StringBuilder sb = new StringBuilder( ) ;sb.append ( "[[ " ) ;for ( int i = 0 ; i < plist.length ; i++ )
sb.append ( plist [ i ] ) ;sb.append ( " ]]" ) ;return sb.toString( ) ;
Enterprise Solutions Using J2EE / Lecture 49 1
Collection ClassesYashavant Kanetkar
Objectives
Ω Why do we need Collections
Ω Cornerstones of Collections
Ω Advantages of using Collections
Ω Types of Collections
Ω Using the Vector collection
Store n Integers
55 63 28 45 60 N
No point in implementing Array and Linked List ourselves
Array of n itemsn Variables Linked List
Too tedious Wastage, Resizing Difficult
Data Link
Enterprise Solutions Using J2EE / Lecture 49 2
Philosophy
Access
Storage
Operations
LinearNon-linear
setgetaddremoveinsert
subsetsort, searchreversecopyfrequencymin, maxfill, zero...
Solution - Collections
Reduced effort – Don't reinvent the wheelPerformance – Efficient AlgorithmsSimilarity – Similar operations on diff. types / collectionsExtensibility – Easy adaptation for new objectsReuse – Different libraries use same collection classes
WhereWhat Why
ObjectGroup > 1 element
Store, RetrieveModify, Transmit Performance
Similarity
Reduced effort
ReuseExtensibility
Collection Types
IndexedOrdered Mapped
IO is order based
Stack, Queue
IO is index based
ArrayList, Vector
IO is key based
HashT, Tree Map
Enterprise Solutions Using J2EE / Lecture 49 3
How To Represent & Manage Collections
Interfaces
Declarations
Implementations
Collection classes
Algorithms
Static Methods
Interfaces
Collection
Iterable Iterator Map
ListIterator SortedMap
DequeueSortedSet
ListSet Queue
Iterable – iterator( ) - Returns the Iterator objectIterator – hasNext( ), next( ), remove( )Map – <key, value> pairs. Ex. Dictionary, Address bookListIterator – hasPrevious( ), previous( ), ..
Collection Classes
AbstractCollection PriorityQueueAbstractQueue
AbstractList
AbstractSet
Stack
LinkedList
HashSet
TreeSet
Abs.Seq.List
ArrayList
Vector
Enterprise Solutions Using J2EE / Lecture 49 4
Algorithms
CollectionsArrays
binarySearch( )
copyRange( )
sort( )
fill( )
...
max( )
reverse( )
min( )
copy( )
shuffle( )
...
package collections ;import java.io.* ;import java.util.* ;public class VectorTest
public static void main ( String[ ] args )
Vector v1 = new Vector( ) ;v1.add ( 'b' ) ; v1.add ( 4 ) ;Vector v2 = new Vector( ) ;v2.add ( "Hello" ) ; v2.add ( "World" ) ;v1.addAll ( v2 ) ; v1.add ( 8.7 ) ;v1.add ( "Rahul" ) ; v1.add ( 1 , "Deepti" ) ;
S.o.p ( v1.size( ) ) ;S.o.p ( v1.capacity( ) ) ;if ( v1.contains ( "Deepti" ) )
S.o.p ( "Found Deepti" ) ;v1.remove ( "Rahul" ) ;Iterator e = v1.iterator( ) ;while ( e.hasNext( ) )
S.o.p ( e.next( ) ) ;
Vector
Count: 7Capacity: 10
Add items from v2
bDeepti4HelloWorld8.7
Variable len. arrayResizableOrdered CollectionThread-safe
Enterprise Solutions Using J2EE / Lecture 50 1
Collections & Inner ClassesYashavant Kanetkar
Objectives
Ω How to use ArrayList CollectionΩ Collection of user-defined typesΩ Relationship between Inner Classes and CollectionsΩ How to use key-value collections
ArrayList Collectionpackage collections ;import java.util.* ;import java.io.* ;public class ArrayListTest
public static void main ( String[ ] args )
ArrayList arr = new ArrayList( ) ;arr.add ( 'a' ) ;arr.add ( 43 ) ;arr.add ( 6.7 ) ;arr.add ( "Rahul" ) ;arr.add ( true ) ;arr.add ( 1, "Deepti" ) ;S.o.p ( "Count: " + arr.size( ) ) ;arr.remove ( "Rahul" ) ;
Count: 6
Variable length arrayResizableOrdered CollectionNot thread-safeCan be synchronized
Boxed
Contd...
Enterprise Solutions Using J2EE / Lecture 50 2
S.o.p ( "Index of 6.7 : " + arr.indexOf ( 6.7 ) ) ;S.o.p ( "Element at Index 0 : " + arr.get ( 0 ) ) ;
Iterator e = arr.iterator( ) ;while ( e.hasNext( ) )
S.o.p ( e.next( ) ) ;
Collections.reverse ( arr ) ;e = arr.iterator( ) ;while ( e.hasNext ( ) )
S.o.p ( e.next( ) ) ;
aDeepti436.7True
True6.743Deeptia
IteratorInterfacePermits AccessCan modify
..Contd. Index of 6.7 : 3Element at Index 0 : a
ConcurrentModificationException
TreeSetpackage collections ;import java.util.* ;import java.io.* ;public class TreeSetTest
public static void main ( String[ ] args )
TreeSet ts = new TreeSet( ) ;ts.add ( new Product ( 3, "J2EE" ) ) ;ts.add ( new Product ( 2, "Data Structures" ) ) ;ts.add ( new Product ( 4, "C#" ) ) ;ts.add ( new Product ( 1, "Embedded" ) ) ;Iterator e = ts.iterator( ) ;while ( e.hasNext( ) )
System.out.println ( e.next( ) ) ;
Contd...
Ordered CollectionSorted by nat. orderNo duplication
class Product implements Comparable
private int id ;private String name ;
public Product ( int i , String n )
this.id = i ; this.name = n ;
public String toString( )
return "< " + this.id + ", " + this.name + " >" ;
..Contd.
Contd...
Enterprise Solutions Using J2EE / Lecture 50 3
public int compareTo ( Object o )
assert o instanceof Product ;Product p2 = ( Product ) o ;return name.compareTo ( p2.name ) ;
public boolean equals ( Object o )
assert o instanceof Product ;Product p2 = ( Product ) o ;return name == p2.name && id == p2.id ;
..Contd. assert – keywordinstanceof – keyword
For Interface
For Base Class
Inner Classesclass Outer
int x = 100 ;class Inner
int y = 50 ;void display( )
S.o.p ( y + " " + x ) ;
public class Sample
public staticvoid main ( String args[ ] )
Inner i = new Inner( ) ;i.display( ) ;S.o.p ( i.y ) ;Outer o = new Outer( ) ;o.fun( ) ;
void fun( )
Inner i = new Inner( ) ;i.display( ) ;S.o.p ( i.y ) ;
Inner class objects must be createdthrough Outer class functionInner class can access Outer class fields & methods
One More Access
class Outer
public class Sample
public staticvoid main ( String args[ ] )
Outer o = new Outer( ) ;
Inner fun( )
Inner i = new Inner( ) ;return i ;
interface test
void display( ) ;
class Inner impements test
public void display( )
S.o.p ( "Hi" ) ;
t.display( ) ;test t = o.fun( ) ;
Works
Inner class can be accessed form outside the Outer class
using an interface pointer
Enterprise Solutions Using J2EE / Lecture 50 4
class TreeSetItr implements Iterator
// end of TreeSetItr class
boolean hasNext( )
// logic to check if next node exists in the tree set or not
class TreeSet Implements Iterable
How It WorksIterator iterator( )
// creates object of TreeSetItr// returns its reference
// end of TreeSet class
Object next( )
// go to next node in the tree set// returns next Product object in the tree set as an Object
Iterator e = ts.iterator( ) ;while ( e.hasNext( ) )
S.o.p ( e.next( ) ) ;
Enterprise Solutions Using J2EE / Lecture 51 1
Generics / TemplatesYashavant Kanetkar
Objectives
Ω Need for generalized Collections
Ω What are Generics
Ω How to use Generic Collections
Ω How to create user-defined generic collection
Requirement
Task:Manage a collection of Products
Store Product objects in a
ArrayList
Store Product
objects in a LinkedList
Enterprise Solutions Using J2EE / Lecture 51 2
Product Class
class Product
private int id ;private String name ;
public Product ( int i, String n )
name = n ;id = i ;
public void display( )
S.o.p ( id + " " + name ) ;
Dump Into ArrayListpackage templates ;import java.util.* ;public class Templates1
public static void main ( String[ ] args )
ArrayList ts = new ArrayList( ) ;ts.add ( new Product ( 1, "P1" ) ) ;ts.add ( "hello" ) ;ts.add ( new Product ( 2, "P2" ) ) ;Iterator i = ts.iterator( ) ;while ( i.hasNext( ) )
Product p = ( Product ) i.next( ) ;p.display( ) ;
1 P1ClassCastException: String can't be cast to Product
Heterogeneous - Bad ideaUnless in a inheritance chain
Buggy - Compilation OKSlow - Only objectsUgly -Typecasting
Solutions
Ω Sol. 1 - Create different ArrayList classes for different types
Ω Sol. 2 - Create one Generic ArrayList class for all types
Ω Generics were invented for implementing generic collections
Ω Many other J2SE libraries use them
Ω Generics refers to Generic types & Generic methods
Ω Generics types & methods differ from regular types and methods in that they have type parameters
Code Specialisation Code Sharing
Enterprise Solutions Using J2EE / Lecture 51 3
package templates ;import java.util.* ;public class Templates2
public static void main ( String[ ] args )
ArrayList <Product> pl = new ArrayList <Product> ( ) ;pl.add ( new Product ( 1, "P1" ) ) ;// pl.add ( "hello" ) ;pl.add ( new Product ( 2, "P2" ) ) ;Iterator <Product> i = pl.iterator( ) ;while ( i.hasNext( ) )
Product p = i.next( ) ;p.display( ) ;
Generic ArrayList
- Compilation error- Ensures homogenity- Typesafe collections
- Generic ArrayList. Other Coll. too- Generic types have type parameters- Formal types replaced by actual types
- Compiles without errors- No ClassCastExceptions at runtime
Generics - TipsΩ 3 ways to use generic collection types
Ω Concrete instantiation - with concrete type argumentsArrayList <Product> pl = new ArrayList <Product> ( ) ;
Ω Raw instantiation - without type argumentsArrayList pl = new ArrayList( ) ;
Ω Wildcard instantiation - with wildcard argumentsBeyond scope
Ω Advantages of GenericsΩ Increased expressive powerΩ Improved type safetyΩ Implicit type checks and type conversions where needed
Ω Downside: Ω No primitive types
MyCollection td = new MyCollection( ) ;
td.add ( 5.7f ) ;td.add ( "Hello" ) ;S.o.p ( td.get ( 1 ) ) ;S.o.p ( td.get ( 0 ) ) ;
User-Def. Genericpackage templates ;import java.util.* ;public class Templates3
public static void main ( .. )
MyCollection <Integer> ti = new MyCollection <Integer>( ) ;
ti.add ( 5 ) ;ti.add ( 10 ) ;S.o.p ( ti.get ( 1 ) ) ;S.o.p ( ti.get ( 0 ) ) ;
MyCollection<Product> tp = new MyCollection<Product>( ) ;
tp.add ( new Product ( 1 , "P1" ) ) ;tp.add ( new Product ( 1 , "P2" ) ) ;tp.get ( 1 ).display( ) ;tp.get ( 0 ).display( ) ;
10 5
Type casting not reqd.1 P21 P1
Hello5.7
- Unsafe instantiation- Works without 'type' parameter- Allows 'heterogenous' collections- Bad idea though!
Enterprise Solutions Using J2EE / Lecture 51 4
MyCollectionclass MyCollection<E>
private ArrayList<E> items ;
public MyCollection( )
items = new ArrayList<E>( ) ;public void add ( E obj )
items.add ( obj ) ;public E get ( int i )
return items.get ( i ) ;
- E is Placeholder for any type- E is similar to a type- But not really a type- Restrictions:• Cannot be used in new• Can't be derived from
Product class:- 2-arg Ctor- display( )
Enterprise Solutions Using J2EE / Lecture 52 1
User-defined GenericsYashavant Kanetkar
Objectives
Ω How to create user-defined Collections
Ω How to create user-defined Iterators
Ω How to create a generic printList( ) algorithm
Ω How to create a Function Template
User-Defined Iteratorpackage templates ;import java.util.* ;public class Templates4
public static void main ( String[ ] args ) throws Exception
TCollection<Product> pl = new TCollection<Product> ( ) ;pl.add ( new Product ( 1, "P1" ) ) ;pl.add ( new Product ( 2, "P2" ) ) ;pl.add ( new Product ( 3, "P3" ) ) ;pl.add ( new Product ( 4, "P4" ) ) ;pl.add ( new Product ( 5, "P5" ) ) ;pl.add ( new Product ( 5, "P6" ) ) ;for ( Product p : pl )
p.display( ) ;
1 P12 P23 P34 P45 P55 P6
Product class:- 2-arg Ctor- display( )
Iterator<Product> i = pl.iterator( ) ;
while ( i.hasNext( ) )
Product p = i.next( ) ;p.display( ) ;
Enterprise Solutions Using J2EE / Lecture 52 2
class TCollection<E> implements Iterable<E>
private ArrayList<E> items ;public TCollection( )
items = new ArrayList<E>( ) ;public void add ( E obj )
items.add ( obj ) ;public E get ( int i )
return items.get ( i ) ;public Iterator<E> iterator( )
return new TIterator ( this ) ;
Iterable Collec
Inner Classclass TIterator implements Iterator<E>
Iterator<E> itr ;public TIterator ( TCollection<E> c )
itr = c.items.iterator( ) ;public boolean hasNext( )
return itr.hasNext( ) ;public E next( )
return itr.next( ) ;public void remove( )
itr.remove( ) ;
Generic printList( ) Algorithmpackage templates ;import java.util.* ;public class Templates5
public static void main ( String[ ] args )
Vector<Integer> v = new Vector<Integer>( ) ;v.add ( 1 ) ; v.add ( 4 ) ;
ArrayList<Integer> al = new ArrayList<Integer>( ) ;al.add ( 2 ) ; al.add ( 6 ) ;
printIntList ( v ) ;printIntList ( al ) ;printList ( v ) ;printList ( al ) ;
1 42 6 1 4 2 6
Goal:Common printList( ) for all List<T> compatible classes
Can TCollection<T> use printList( ) ?Yes, if it implements java.util.List<T> interface
Enterprise Solutions Using J2EE / Lecture 52 3
public static void printIntList ( List<Integer> tl )
for ( int a : tl )System.out.print ( a + " " ) ;
S.o.p( ) ;
public static<T> void printList ( List<T> tl )
for ( T a : tl )System.out.print ( a + " " ) ;
S.o.p( ) ;
Generic
More Generic
package templates ;import java.util.* ;public class Templates6
public static void main ( String [ ] args )
int a = 4 ; int b = 5 ;S.o.p ( "max = " + max ( a, b ) ) ;S.o.p ( "max = " + max ( 'z', 'y' ) ) ;S.o.p ( "max = " +
max ( new Product ( 1, "de" ), new Product ( 2, "bc" ) ) ) ;ArrayList<Integer> il = new ArrayList<Integer> ( ) ;il.add ( 10 ) ; il.add ( 20 ) ; il.add ( 30 ) ; il.add ( 20 ) ;S.o.p ( duplicate ( il ) ) ;ArrayList<Product> pl1 = new ArrayList<Product> ( ) ;pl1.add ( new Product ( 1, "P1" ) ) ;pl1.add ( new Product ( 2, "P2" ) ) ;pl1.add ( new Product ( 1, "P1" ) ) ;S.o.p ( duplicate ( pl1 ) ) ;
Function Templates
max = 5max = zmax = <1 , de >
public static <T extends Comparable> T max ( T a, T b ) if ( a.compareTo ( b ) < 0 )
return b ;return a ;
public static <T> boolean duplicate ( List<T> coll )
int count ;for ( T i1 : coll )
count = 0 ;for ( T i2 : coll )
if ( i1.equals ( i2 ) )count ++ ;
if ( count > 1 )
return true ;return false ;
Such a T thatimplements Comparable
Object contains equals( )It compares referencesWe want to compare valuesHence override equals( ) in T
Enterprise Solutions Using J2EE / Lecture 52 4
Product Class Revisitedclass Product implements Comparable
private int id ;private String name ;public Product ( int id, String name )
name = name ;id = id ;
public void display( )
S.o.p ( id + " " + name ) ;public int compareTo ( Object o )
return name.compareTo ( ( ( Product ) o ).name ) ;
Program Continuedpublic boolean equals ( Object obj )
Product p2 = ( Product ) obj ;return name.equals ( p2.name ) ;
public int hashCode( )
int hash = 5 ;hash = 11 * hash + id ;hash = 11 * hash + ( name != null ? name.hashCode( ) : 0 ) ;return hash ;
Necessary once we override equals( )Computes HashcodeSufficiently sparse Empty in NetBeans 5.5Provided by NetBeans 6.0Asks which fields to use to compute hashcode
Enterprise Solutions Using J2EE / Lecture 53 1
Networking Today Yashavant Kanetkar
Objectives
What an App needs to achieve network communicationNetwork programming modelHow to get HTTP headersHow to download a file using HTTPHow to download a file using FTP
Network Communication
Port NumberMachine Name Protocol
Gets converted to IP Address
To distinguish bet.communicating Apps
How to send requestHow to receive response
- 198.168.100.2- General to specific- 32-bit addresses- Network, Host- Class A, B, C
- Std. apps use std. port nos.- Different apps, different port nos.- 20, 21 – FTP 25 – SMTP- 110 – POP 80 – HTTP- No relation with serial, parallel ports
Enterprise Solutions Using J2EE / Lecture 53 2
Network Programming Model
What we get to do?
Email C. Outlook, Eudora C. Email S. MS Exchange
POP/SMTP
Web C. IE, Firefox Web S. IIS, Apache
HTTP
FTP C. CuteFTP FTP S. Configured IIS
FTP
Client Server
How HTTP Works
Session
HTTP Response
Return Host IPReturn Host IP
Browser / App. Server
ISP DNS
Connection Req. Search DNS
HTTP Request
GET - Get a file from URLPOST - For sending dataOther - OPTIONS, HEAD, PUT, DELETE
Web Page – HTML + JavaScriptActiveX controlJava AppletAny requested file
Sample Header
Address : http://quest.ksetindia.com/null : [HTTP/1.1 200 OK]Date : [Sun, 28 Oct 2007 04:14:54 GMT]Transfer-Encoding : [chunked]Expires : [Thu, 19 Nov 1981 08:52:00 GMT]Set-Cookie : [osCsid=f5r28r4nvhl7qlecai71esmq93; path=/; domain=quest.ksetindia.com]Connection : [close]Content-Type : [text/html; charset=UTF-8]Server : [Apache/2.2.3 (Fedora)]X-Powered-By : [PHP/5.1.6]Cache-Control : [no-store, no-cache, must-revalidate, post-check=0, pre-check=0]
Response broken into chunks
200 OK - Request succeeded301 Moved Permanently 302 Moved Temporarily 404 Not Found500 Server Error
Server will close the connection following this response
Controls how proxies may cache this object
Key : Values(s) Pairs
Enterprise Solutions Using J2EE / Lecture 53 3
HTTP Headerspackage networking ;import java.io.* ;import java.net.* ;import java.text.MessageFormat ;import java.util.* ;public class PrintHeaders
public static void main ( String[ ] args ) throws Exception
printHeaders ( "http://quest.ksetindia.com/index.php" ) ;printHeaders ( "http://microsoft.com/windows" ) ;printHeaders ( "http://quest.ksetindia.com/dl/myfile.zip" ) ;
Resource – File, Directory, Query URLs - HTTP, FTP, File, HTTPs..Uniform Resource Locator – Protocol://Location:portnumber/path/file
static void printHeaders ( String addr ) throws Exception
S.o.p ( MessageFormat.format ( "Address : 0", addr ) ) ;URL u = new URL ( addr ) ;HttpURLConnection conn ;conn = ( HttpURLConnection ) u.openConnection( ) ;if ( conn.getResponseCode( ) == HttpURLConnection.HTTP_OK)
Map<String, List<String>>headers = conn.getHeaderFields( );for ( String h : headers.keySet( ) )
S.o.p ( h + " : " + headers.get ( h ) ) ;conn.disconnect( ) ;
HTTPURLConnection - Derived from URLConnectionRepresents a comm. link between the app & HTTP URLUsing conn we can R/W to the resource referenced by URL
HTTP/1.0 200 OK HTTP/1.0 401 Unauthorized
Opens connectionMakes GET request
File Download
Client
HTTP Server
quest.ksetindia.com/dl/myfile.zip
FTP Server
quest.ksetindia.com/pub/myftp.zip
HTTP Request
FTP Request
Our App. Server
Enterprise Solutions Using J2EE / Lecture 53 4
HTTP & FTP Downloadpackage networking ;import java.util.* ;import java.io.* ;import java.net.* ;public class HttpDownload
static final int BUF_SIZE = 100 ;public static void main ( String[ ] args ) throws Exception
URL u ;u = new URL ( "http://quest.ksetindia.com/dl/myfile.zip" ) ;HttpURLConnection conn ;conn = ( HttpURLConnection ) u.openConnection( ) ;if ( conn.getResponseCode( )==HttpURLConnection.HTTP_OK)
downloadFile ( conn.getInputStream( ), "myfile.zip" ) ;u = new URL ( "ftp://quest.ksetindia.com/pub/myftp.zip" ) ;downloadFile ( u.openStream( ), "myftp.zip" ) ;
Opens connection, Returns InputStream for rdg.
local filename
donwloadFile( ) static void downloadFile ( InputStream ins, String name )
throws Exception
S.o.p ( "Downloading: " + name ) ; BufferedInputStream fis = new BufferedInputStream ( ins ) ;FileOutputStream fos = new FileOutputStream ( name ) ;byte[ ] data = new byte[ BUF_SIZE ] ;int len ;while ( ( len = fis.read ( data, 0, data.length ) ) != -1 )
fos.write ( data, 0, len ) ;
fis.close( ) ;fos.close( ) ;S.o.p ( "Download completed: " + name ) ;
Enterprise Solutions Using J2EE / Lecture 54 1
Networking & SecurityYashavant Kanetkar
Objectives
HTTP and FTP DownloadWhat is MD5Where is it usedWhat are its benefitsHow to use is programmatically
File Download
Client
HTTP Server
quest.ksetindia.com/dl/myfile.zip
FTP Server
quest.ksetindia.com/pub/myftp.zip
HTTP Request
FTP Request
Our App. Server
Enterprise Solutions Using J2EE / Lecture 54 2
HTTP & FTP Downloadpackage networking ;import java.util.* ;import java.io.* ;import java.net.* ;public class HttpDownload
static final int BUF_SIZE = 100 ;public static void main ( String[ ] args ) throws Exception
URL u ;u = new URL ( "http://quest.ksetindia.com/dl/myfile.zip" ) ;HttpURLConnection conn ;conn = ( HttpURLConnection ) u.openConnection( ) ;if ( conn.getResponseCode( )==HttpURLConnection.HTTP_OK)
downloadFile ( conn.getInputStream( ), "myfile.zip" ) ;u = new URL ( "ftp://quest.ksetindia.com/pub/myftp.zip" ) ;downloadFile ( u.openStream( ), "myftp.zip" ) ;
Opens connection, Returns InputStream for rdg.
local filename
donwloadFile( ) static void downloadFile ( InputStream ins, String name )
throws Exception
S.o.p ( "Downloading: " + name ) ; BufferedInputStream fis = new BufferedInputStream ( ins ) ;FileOutputStream fos = new FileOutputStream ( name ) ;byte[ ] data = new byte[ BUF_SIZE ] ;int len ;while ( ( len = fis.read ( data, 0, data.length ) ) != -1 )
fos.write ( data, 0, len ) ;
fis.close( ) ;fos.close( ) ;S.o.p ( "Download completed: " + name ) ;
MD5 ChecksumStands for Message-Digest algorithm 5Designed by Ronald Rivest in 1991Converts variable length content to a 128-bit valueOne way hash functionUsed in a wide variety of security applications:
Check integrity of filesStore passwords
MD5 hash is expressed as a 32-character hex numberA small change in the content gives a different 32-char hex no.
Enterprise Solutions Using J2EE / Lecture 54 3
MD5 Checksum Logicmain( )
httpVerifyMD5( ) ftpVerifyMD5( )
downloadAnyFile( )
verifyChecksum( )
getChecksum( )
downloadHTTPFile( )
downloadAnyFile( )
Program
package networking ;import java.util.* ;import java.io.* ;import java.net.* ;import java.security.* ;public class VerifyMD5
static final int BUF_SIZE = 100 ;public static void main ( String[ ] args ) throws Exception
httpVerifyMD5( ) ;ftpVerifyMD5( ) ;
static void ftpVerifyMD5( ) throws Exception
URL u = new URL ( "ftp://quest.ksetindia.com/pub/myftp.zip" ) ;downloadAnyFile ( u.openStream( ), u.toString( ) ) ;u = new URL ( "ftp://quest.ksetindia.com/pub/md5sum.txt" ) ;downloadAnyFile ( u.openStream( ), u.toString( ) ) ;verifyChecksum ( "myftp.zip" ) ;
HTTP Download And Verifystatic void httpVerifyMD5( ) throws Exception
downloadHTTPFile ( "http://quest.ksetindia.com/dl/myfile.zip" ) ;downloadHTTPFile ( "http://quest.ksetindia.com/dl/md5sum.txt" );verifyChecksum ( "myfile.zip" ) ;
Enterprise Solutions Using J2EE / Lecture 54 4
downloadHTTPFile( )static void downloadHTTPFile ( String addr ) throws Exception
URL u = new URL ( addr ) ;HttpURLConnection conn ;conn = ( HttpURLConnection ) u.openConnection( ) ;if ( conn.getResponseCode( ) == HttpURLConnection.HTTP_OK )
downloadAnyFile ( conn.getInputStream( ), u.getFile( ) ) ;
downloadAnyFile( )static void downloadAnyFile ( InputStream ins, String name )
throws Exception
S.o.p ( "Downloading " + name ) ;String[ ] parts = name.split ( "/" ) ;name = parts [ parts.length – 1 ] ;BufferedInputStream fis = new BufferedInputStream ( ins ) ;FileOutputStream fos = new FileOutputStream ( name ) ;byte[ ] data = new byte[ BUF_SIZE ] ;int len ;while ( ( len = fis.read ( data, 0, data.length ) ) != -1 )
fos.write ( data, 0, len ) ;fis.close( ) ;fos.close( ) ;
VerifyChecksum( )
static void verifyChecksum ( String origName ) throws Exception
BufferedReader br ;br = new BufferedReader ( new FileReader ( "md5sum.txt" ) ) ;String origSum = br.readLine( ) ;br.close( ) ;String mySum = getChecksum ( origName ) ;if ( origSum.equals ( mySum ) )
S.o.p ( String.format ( "Checksum %1$s is correct", mySum ) ) ;
Enterprise Solutions Using J2EE / Lecture 54 5
public static String getChecksum ( String name ) throws Exception
File srcF = new File ( name ) ;DigestInputStream dis = null ;try
MessageDigest m = MessageDigest.getInstance ( "MD5" ) ;dis = new DigestInputStream( new FileInputStream (srcF), m ) ;while ( dis.read( ) != -1 )
;byte[ ] md = m.digest( ) ;StringBuilder sb = new StringBuilder( ) ;for ( byte b : md )
sb.append ( String.format ( "%1$x", b ) ) ;return sb.toString( ) ;
DigestInputStream
FileInputStream
getCheckSum( )
- Read a byte- Update the MD
Resultfinally
if ( dis != null )dis.close( ) ;
Downloading /dl/myfile.zipDownloading /dl/md5sum.txtChecksum 1342cf2d386a84ca8b5a55a3c0bf5fa5 is correctDownloading ftp://quest.ksetindia.com/pub/myftp.zipDownloading ftp://quest.ksetindia.com/pub/md5sum.txtChecksum 1342cf2d386a84ca8b5a55a3c0bf5fa5 is correct
Result
Enterprise Solutions Using J2EE / Lecture 55 1
Network SerializationYashavant Kanetkar
Objectives
What is network serialization
How to achieve it programmatically
What is multithreading
When can it be used
How to use it in network serialization
Client Server
Requirement
1C Prog.500.012:45:40
1C Prog.500.012:45:42
1C Prog.500.012:45:44
1C Prog.750.012:45:42
0011 0010 1001 .. Deserialization
1111 0010 1001 .. Serialization
Enterprise Solutions Using J2EE / Lecture 55 2
Product Classpackage networking ;import java.util.* ;import java.io.* ;class Product implements Serializable
private int id ; private String Name ;private float price ; transient private Date creationTime ;public Product( )
creationTime = new Date( ) ;System.out.println (" >>Product.constructor1<<" ) ;
public Product ( int num, String name, float p)
creationTime = new Date( ) ;id = num ; Name = name ; price = p ;System.out.println ( " >>Product.constructor2<<" ) ;
public float getPrice( )
return price ;public void setPrice ( float price )
this.price = price ; public String toString( )
return "[ " + String.format ( "%1$tT", creationTime ) + ", " + id + ", " + Name + ", " + price + " ]" ;
private void readObject ( ObjectInputStream in )
throws IOException, ClassNotFoundException
in.defaultReadObject( ) ;this.creationTime = new Date( ) ;
Product Class Cond.
%1 - Postion$t - Print timeT - Only time
Network Serverpackage networking ;import java.net.* ;import java.io.* ;
public class SerializationServer
static public final int portNumber = 10000 ;public SerializationServer( ) throws Exception
ServerSocket lSock = new ServerSocket ( portNumber ) ;Socket cSock = lSock.accept( ) ;ObjectInputStream is = null ;ObjectOutputStream os = null ;try
is = new ObjectInputStream ( cSock.getInputStream( ) ) ;Thread.sleep ( 2000 ) ;Product p = ( Product ) is.readObject( ) ;
Simulates N/Wdelay
ObjectInputStream
InputStream
Listens for a conn. to be madeto this socket & accepts it
Blocking. Creates comm. sckt.
Socket - Bidirectional communication channelEach Sckt has I/O streams to send/rec. dataUse I stream to read data sent by remote m/cUse O stream to send data to remote m/c
Enterprise Solutions Using J2EE / Lecture 55 3
Server Continued
S.o.p ( "Server Received : " + p ) ;p.setPrice ( p.getPrice( ) * 1.5f ) ;os = new ObjectOutputStream ( cSock.getOutputStream( ) ) ;os.writeObject ( p ) ;
finally
os.close( ) ;is.close( ) ;cSock.close( ) ;lSock.close( ) ;
ObjectOutputStream
OutputStream
Network Clientpackage networking ;import java.net.* ;import java.io.* ;
public class SerializationClient
static public final int portNumber = 10000 ;public SerializationClient( ) throws Exception
Socket cSock = null ;ObjectOutputStream os = null ;ObjectInputStream is = null ;Product p ;try
cSock = new Socket ( "localhost", portNumber ) ;os = new ObjectOutputStream ( cSock.getOutputStream( ) ) ;
ObjectOutputStream
OutputStream
Client Continuedp = new Product ( 1, "C Prog.", 500.0f ) ;S.o.p ( "Client Sent: " + p ) ;os.writeObject ( p ) ;is = new ObjectInputStream ( cSock.getInputStream( ) ) ;Thread.sleep ( 2000 ) ;p = ( Product ) is.readObject( ) ;System.out.println ( "Server Sent: " + p ) ;
finally
if ( cSock != null )cSock.close( ) ;
if ( os != null )os.close( ) ;
Enterprise Solutions Using J2EE / Lecture 55 4
Multiple Units Of Execution
Thread is a unit of executionApps can contain more than one unit (at least one)Once created a thread starts getting time slicesTime slice allocated = Thread QuantumScheduling is done on a per thread basisImproves application's responsivenessSimplify program organization Copying in thread1
Playing AVI file in thread2
Scroll whileDownloading
Check whileTyping
package networking ;import java.io.* ;public class NetSerialTester
public static void main ( String[ ] args ) throws Exception
Thread serverT ;serverT = new Thread ( new ServerRunner( ) ) ;serverT.start( ) ;Thread.sleep ( 400 ) ;Thread clientT ;clientT = new Thread ( new ClientRunner( ) ) ;clientT.start( ) ;clientT.join( ) ;serverT.join( ) ;
Multithreaded Driver Program
Wait for server thread to bindIn real life S and C run on diff. m/cs
Main T waits for client & server T to terminate
ServerRunner
class ServerRunner implements Runnable
public void run( )
try
new SerializationServer( ) ;catch ( Exception ex )
System.err.println ( ex.getMessage( ) ) ;
Enterprise Solutions Using J2EE / Lecture 55 5
ClientRunner
class ClientRunner implements Runnable
public void run( )
try
new SerializationClient( ) ;catch ( Exception ex )
System.err.println ( ex.getMessage( ) ) ;
Enterprise Solutions Using J2EE / Lecture 56 1
Zipping / UnzippingYashavant Kanetkar
Objectives
What is zipping & unzipping
Program to
Zip files
List entries in zipped file
Unzip files
ZIP Popular data compression and archival format
A ZIP file contains one or more compressed files
The format was originally designed by Phil Katz for PKZIP
ZIP files generally use the file extensions ".zip" or ".ZIP"
ZIP format compresses every file separately
This allows individual files to be retrieved
Enterprise Solutions Using J2EE / Lecture 56 2
RequirementCurrent Directory
/build/dist/nbproject/src/test
buildcartdecencmanifest.MF
s.zip
zipAll( )
showZipEntries( )
/build/dist/nbproject/src/test
buildcartdecenc
if t MF
unzipAll( )
In temp Dir
Programpackage zipunzip ;import java.io.* ;import java.util.* ;import java.util.zip.* ;public class ZipUnzip
static final int BUF_SIZE = 100 ;public static void main ( String[ ] args ) throws Exception
ZipOutputStream zos ;zos = new ZipOutputStream ( new FileOutputStream( "s.zip" ));zipAll ( new File ( "." ), zos ) ;zos.close( ) ;showZipEntries ( "s.zip" ) ;File tmpdir = new File ( "temp" ) ;if ( !tmpdir.exists( ) )
tmpdir.mkdir( ) ;unzipAll ( "s.zip", new File(".").getAbsolutePath( ) + "/temp/" ) ;
zipAll( )public static void zipAll ( File f, ZipOutputStream zos )
throws IOException
File[ ] list = f.listFiles( ) ;for ( File ch : list )
if ( !ch.isDirectory( ) )addZipEntry ( zos,
ch.getParent( ) + File.separator + ch.getName( ) ) ;
for ( File ch : list )
if ( ch.isDirectory( ) )zipAll ( ch, zos ) ;
Enterprise Solutions Using J2EE / Lecture 56 3
addZipEntry( )
static void addZipEntry ( ZipOutputStream zos, String n )throws IOException
BufferedInputStream fis ;fis = new BufferedInputStream ( new FileInputStream ( n ) ) ;ZipEntry ze = new ZipEntry ( n.replace ( "\\", "/" ) ) ;S.o.p ( ze.getName( ) ) ;zos.putNextEntry ( ze ) ;int count ;byte[ ] data = new byte[ BUF_SIZE ] ;while ( ( count = fis.read ( data, 0, BUF_SIZE ) ) != -1 )
zos.write ( data, 0, count ) ;
- Begins writing a new ZIP file entry- Positions stream to start of entry data
showZipEntries( )
private static void showZipEntries ( String name ) throws Exception
ZipFile zf = new ZipFile ( name ) ;Enumeration <ZipEntry> e ;for ( e = ( Enumeration<ZipEntry> ) zf.entries( ) ;
e.hasMoreElements( ) ; )
ZipEntry ze = e.nextElement( ) ;if ( !ze.isDirectory( ) )
S.o.p ( String.format ( "%1$s %2$d ( %3$d )",ze.getName( ), ze.getCompressedSize( ), ze.getSize( ) ) ) ;
Returns an enumeration of the ZIP file entries
unzipAll( )private static void unzipAll ( String src, String dest )
throws Exception
ZipInputStream zis ;zis = new ZipInputStream ( new FileInputStream ( src ) ) ;ZipEntry e ;while ( ( e = zis.getNextEntry( ) ) != null )
File f = new File ( e.getName( ) ) ;if ( e.isDirectory( ) )
if ( !f.exists( ) )f.mkdirs( ) ;
else
int len ;long size = 0, max = e.getSize( ) ;File parent = new File ( dest + "/" + f.getParent( ) ) ;
Enterprise Solutions Using J2EE / Lecture 56 4
if ( !parent.exists( ) )parent.mkdirs( ) ;
FileOutputStream fos ;fos = new FileOutputStream ( dest + "/" + f.getName( ) ) ;byte[ ] data = new byte[ BUF_SIZE ] ;while ( size <= max )
len = zis.read ( data, 0, BUF_SIZE ) ;if ( len == -1 )
break ;fos.write ( data, 0, len ) ;size += len ;
fos.close( ) ;
Enterprise Solutions Using J2EE / Lecture 57 1
Multi-threading &Synchronization
Yashavant [email protected]
Objectives
What is multithreadingHow to get properties of current threadHow to launch multiple threadsPros and cons of different launching methodsNeed for synchronizationHow to achieve it programmatically
t.setName ( "mythread" ) ;S.o.p ( "After name change: " + t ) ;String s = t.getName( ) ;S.o.p ( "Thread name: " + s ) ;
package mainthread ;public class MainThread
public static void main ( String args[ ] )
Thread t = Thread.currentThread( ) ;
main, 5, mainnameprioritygroup
mythread, 5, main
S.o.p ( "Current thread: " + t ) ;
mythread
Current Thread
Reference to current thread
Enterprise Solutions Using J2EE / Lecture 57 2
class Ex extends Thread
package sample ;public class Sample
public static void main ( String[ ] args )
for ( int i = 0 ; i < 10 ; i ++ ) S.o.p ( "Main thread" ) ;
Ex t = new Ex( ) ;t.start( ) ;
public void run( )
for ( int i = 0 ; i < 10 ; i++ ) S.o.p ( "New thread" ) ;
Launching A Thread
Main threadNew threadNew threadMain threadNew thread:::
Output
Base class Ctor( )Registers thread
with JVMThread's start( ) is called.Signals thread scheduler
New threadbegins execution hereExecution begins only
when the T is scheduled
Multiple Threads
class Ex extends Thread
public class Sample
public static void main ( .. ) throws Exception
for ( int i = 0 ; i < 10 ; i ++ ) S.o.p ( "Main" ) ;
Ex t1 = new Ex( ) ;t1.start( ) ;t1.setName ( "First" ) ;Ex t2 = new Ex( ) ;t2.start ( ) ;t2.setName ("Second" ) ;Ex t3 = new Ex( ) ;t3.start( ) ;t3.setName ( "Third" ) ;
public void run( )
Thread t ; t =Thread.currentThread( ) ;String s = t.getName( ) ;int i ;for ( i = 0 ; i < 10 ; i++ )
S.o.p ( s ) ;
FirstSecondSecondSecondThirdThirdMain:::
t1.join( ) ;t2.join( ) ;t3.join( ) ;
Wait for thisthread to die
class Ex implements Runnable
public class Sample
public static void main ( String[ ] args )
Thread t = new Thread ( new Ex ( "One" ) ) ;
public void run ( )
int i ;for ( i = 0 ; i < 10 ; i++ )
S.o.p ( str ) ;
String str ;Ex ( String s )
str = s ;
for ( int i = 0 ; i < 10 ; i ++ ) S.o.p ( "Main thread" ) ;
t.start( ) ;
One More Way
Enterprise Solutions Using J2EE / Lecture 57 3
Multiple Thread Using Runnablepublic class Sample
public static void main ( String[ ] args )
for ( int i = 0 ; i < 10 ; i ++ ) S.o.p ( "Main thread" ) ;
Ex t1 = new Thread ( new Ex ( "First" ) ) ;t1.start( ) ;Ex t2 = new Thread ( new Ex ( "Second" ) ) ;t2.start ( ) ;Ex t3 = new Thread ( new Ex ( "Third" ) ) ;t3.start( ) ;
Ex class remains same
Multithreading TipsΩ 2 Methods to launch threads
class that extends Threadclass that implements Runnable
Ω In both cases a thread object must be createdobject ex gets known to Thread
Ω start( ) is a Thread member functionIt registers ex object with scheduler
Ω run( ) must be within our classIt is called by scheduler
Ω extends Thread - Can't use in Multiple Inher. situationΩ extends Thread - Thread related funcs. can be overriden
Requirement
Main Thread
Thread 1 Thread 2
dowork( )
dowork1( ) ;dowork2( ) ;
Enterprise Solutions Using J2EE / Lecture 57 4
Programpackage synchtest ;public class SyncTest
public static void main ( String[ ] args ) throws Exception
Work w = new Work( ) ;Thread t1 = new Thread ( new ThreadRunner ( w ) ) ;Thread t2 = new Thread ( new ThreadRunner ( w ) ) ;t1.start( ) ;t2.start( ) ;t1.join( ) ;t2.join( ) ;
Work Classclass Work
int count = 0 ;public void doWork( ) throws Exception
S.o.p ( String.format ( "(%1$s) ", count ) +Thread.currentThread( ).getName( ) + " : doWork" ) ;
doWork1( ) ; doWork2( ) ;private void doWork1( ) throws Exception
S.o.p ( String.format ( "(%1$s) ", count ) +Thread.currentThread( ).getName( ) + " : doWork1" ) ;
Thread.sleep ( 200 ) ;private void doWork2( ) throws Exception
S.o.p ( String.format ( "(%1$s) ", count ) +Thread.currentThread( ).getName( ) + " : doWork2" ) ;
count ++ ;Thread.sleep ( 100 ) ;
ThreadRunner
class ThreadRunner implements Runnable private Work obj ;public ThreadRunner ( Work o )
obj = o ;public void run( )
for ( int i = 0 ; i < 2 ; i++ )
try
obj.doWork( ) ;catch ( Exception ex )
System.err.println ( ex.getMessage( ) ) ;return ;
(0) Thread-0 : doWork(0) Thread-0 : doWork(0) Thread-1 : doWork(0) Thread-1 : doWork1(0) Thread-0 : doWork2(1) Thread-1 : doWork2(2) Thread-1 : doWork(2) Thread-1 : doWork1(2) Thread-0 : doWork(2) Thread-0 : doWork1(2) Thread-1 : doWork2(3) Thread-0 : doWork2
Enterprise Solutions Using J2EE / Lecture 57 5
Solutionsynchronized public void doWork( ) throws Exception
S.o.p ( String.format ( "(%1$s) ", count ) +Thread.currentThread( ).getName( ) + " : doWork" ) ;
doWork1( ) ;doWork2( ) ;
(0) Thread-0 : doWork(0) Thread-0 : doWork1(0) Thread-0 : doWork2(1) Thread-0 : doWork(1) Thread-0 : doWork1(1) Thread-0 : doWork2(2) Thread-1 : doWork(2) Thread-1 : doWork1(2) Thread-1 : doWork2(3) Thread-1 : doWork(3) Thread-1 : doWork1(3) Thread-1 : doWork2
Enterprise Solutions Using J2EE / Lecture 58 1
Using Web ServicesYashavant Kanetkar
Objectives
Where are web servicesWhat is WSDLAccessing web services in NetBeansUsing web services programmaticallyCrux of Web Services
Create New Project
Enterprise Solutions Using J2EE / Lecture 58 2
Where Is The Web Service?
Names of Functions
WSDL
Enterprise Solutions Using J2EE / Lecture 58 3
Add Web Service ClientR
Add WSDL URLhttp://quest.ksetindia.com/CurrencyService/CurrencyService.asmx?WSDL
Java API for XML Web Services
Enterprise Solutions Using J2EE / Lecture 58 4
Automatically Generated Classes
Add Code
javax.xml.ws.Service
CurrencyService
CurrencyServiceSoap - Interface
Call methods on remote system
1 US Dollar = 39.325 Indian Rupees
1. Get Conversion Rate
public float getRate ( String from, String to )
Enterprise Solutions Using J2EE / Lecture 58 5
2. Countries And Currencies
Output…America (United States) Dollar USD Britain (United Kingdom) Pound GBP Canada Dollar CAD England (United Kingdom) Pound GBP Hong Kong Dollar HKD Hungary Forint HUF India Rupee INR Indonesia Rupiah IDR Iran Rial IRR Iraq Dinar IQD Italy Euro EUR Japan Yen JPY... ... ...... ... ...
Other Methods…
rate = sa.getRateByCountry ( "Australia", "India" ) ;S.o.p ( "1 Australian Dollar = " + rate + " Indian Rupees" ) ;
String curr = sa.getCurrency ( "Hungary" ) ;S.o.p ( "Currency of Hungary is " + curr ) ;
1 Australian Dollar = 36.6099 Indian Rupees
Currency of Hungary is HUF
Enterprise Solutions Using J2EE / Lecture 58 6
What Are Web Services
HTTP / HTTPS for data transferXML format for universal acceptanceSOAP – Simple Object Access Protocol
Message envelopeMaps Java types to XML and vice versa
JAX-WS – Java API for XML Web ServicesJAX-RPC – replaces JAX-WS. Is compatible
Enterprise Solutions Using J2EE / Lecture 59 1
Using XMLYashavant Kanetkar
Objectives
♦ Different data usage scenarios♦ What is XML♦ How to create XML document, DTD, SAX handler classes♦ How to parse a XML file using SAX handler classes
Data Usage Scenarios
Cas
e I
App101000111010110011
Oracle Ind. SeqApp 101000111010110011
Cas
e II ftpSolaris App Web Server Web Client
Res
Req
Cas
e III
Backup Agent2Backup Agent1
Backup Agent4Backup Agent3Backup
Manager
Cas
e IV
Java App
.NET App COM App
Enterprise Solutions Using J2EE / Lecture 59 2
Moral
♦ Need for easy way to describe & exchange data♦ Need for easy way to make function calls in Distributed apps♦ All needs satisfied using XML - Extended Markup Lang.♦ Contains user defined tags (HTML – Std. tags)♦ Sample: <books>
<book><title> VC++ COM and Beyond </title><pages> 460 </pages>
</book><book>
<title> Effective COM </title><pages> 510 </pages>
</book></books>
Tag
XML Reader - Steps Involved
♦ Create new Java application ♦ Project name – Contacts♦ Package - contacts♦ Main Class - XmlContacts
♦ Create new XML file – Contacts.xml♦ Generate DTD file – Contacts.dtd♦ Add its reference in Contacts.xml♦ Generate SAX document handler class♦ Add Contact class♦ Modify SAX handler class♦ Invoke SAX parser and print contacts
Create Contacts.xml
R
Enterprise Solutions Using J2EE / Lecture 59 3
Give Filename
Select XML Document Type
Result
Enterprise Solutions Using J2EE / Lecture 59 4
Modify Contacts.xml
Create DTD – Contacts.dtd
R
Copy DTD Reference
Enterprise Solutions Using J2EE / Lecture 59 5
Paste & Modify
Invoke SAX Document Handler Wizard
R
Step 1 – API Version
Enterprise Solutions Using J2EE / Lecture 59 6
Step 2 – Element Mappings
Step 3 – Data Converters
Step 4 – Output Filenames
Enterprise Solutions Using J2EE / Lecture 59 7
Create Contact class
package contacts ;public class Contact
private String name ; private String telephone ;public Contact( ) public String getName( )
return name ;public void setName ( String n )
this.name = n ;
public String getTel( )
return telephone ;public void setTel ( String t )
telephone = t ;public String toString( )
return "< " + name + ", "+ telephone + " >" ;
Modify ContactsHandlerImpl
package contacts ;import java.util.ArrayList ;import org.xml.sax.* ;public class ContactsHandlerImpl implements ContactsHandlerArrayList<Contact> list ;Contact current = null ;public void start_Contacts ( final Attributes meta) throws SAXException
list = new ArrayList<Contact>( ) ;public void start_Contact ( final Attributes meta ) throws SAXException
current = new Contact( ) ;
Modification Continuedpublic void handle_Name ( final String data, final Attributes meta)
throws SAXException
current.setName ( data ) ;public void handle_Telephone ( final String data, final Attributes meta )
throws SAXException
current.setTel ( data ) ;public void end_Contact( ) throws SAXException
list.add ( current ) ;public void end_Contacts( ) throws SAXException
Enterprise Solutions Using J2EE / Lecture 59 8
Modification Continued
public ArrayList<Contact> getList( )
return list ;protected void finalize( ) throws Throwable
XML Readerpackage contacts ;import java.io.FileReader ;import org.xml.sax.InputSource ;public class XmlContacts
public static void main ( String[ ] args ) throws Exception
ContactsHandlerImpl handler ;ContactsParser p ;handler = new ContactsHandlerImpl( ) ;p = new ContactsParser ( handler, null ) ;p.parse ( new InputSource (
new FileReader ("src/contacts/Contacts.xml" ) ) ) ;for ( Contact c : handler.getList ( ) )
System.out.println ( c ) ;
Enterprise Solutions Using J2EE / Lecture 60 1
Annotations & ReflectionYashavant Kanetkar
Objectives
♦ What are annotations♦ Different scenarios in which it can be used ♦ What is reflection♦ What does it facilitate♦ Writing a Test harness using Annotations & Reflection
Annotations
♦ More mature comments♦ They provide data about a program that is not part of the program itself♦ Annotations can be applied to classes, fields, methods, package♦ 3 uses of annotations:
During CompilationTo detect ErrorsTo suppress warnings
During DeploymentTo generate codeTo create XML files
During ExecutionTo test the program
Enterprise Solutions Using J2EE / Lecture 60 2
Error Detection
class base
public void fun ( String s, int i )
System.out.println ( s + i ) ;
class der extends base
@override void fun ( String ss )
Once marked, Error
Annotation
Suppress Warningpackage sample ;
public class Sample
public static void main ( String[ ] args ) throws Exception
Ex e = new Ex( ) ; e.fun( ) ;
class Ex
@Deprecatedpublic void fun( )
System.out.println ( "Hello" ) ;
Once marked, Warning
Annotation
@SuppressWarnings ( value = "deprecation" )
To suppress Warning
Annotation With Multiple Elements
@Retention ( RetentionPolicy.RUNTIME )@Target ( ElementType.METHOD, ElementType.CLASS )@interface Author
String Company( ) default "KSET Pvt Ltd" ;String Coder( ) ; String Reviewer( ) ;String[ ] Testers( ) ;int VersionNumber default 1.0 ;
Has multiple elements
Annotation - Author
Some have default values
Avlbl at runitme SOURCE, CLASS Won't work for a Field
@Author ( Coder = "Rahul", Reviewer = "Ranjit", Testers = "A", "B" )class Cricket
Usage
Enterprise Solutions Using J2EE / Lecture 60 3
Reflection
Get Information Use Information
Create objectModify objectCall methods
Object Class
Fields
InterfaceConstants
CtorsMethods
Superclass
MethodsClass Modifiers
All this at Runtime!
Using @ At Runtimepackage annotationsreflection ;import java.lang.annotation.* ;import java.lang.reflect.* ;
@Retention ( RetentionPolicy.RUNTIME )@Target ( ElementType.METHOD )@interface TestMethod
class ClassUnderTest
@TestMethod public static void testcase1( )
S.o.p ( "testcase1" ) ;@TestMethod public static void testcase2( )
S.o.p ( "testcase2" ) ;throw new RuntimeException ( "testcase2" ) ;
Program Continued
public static void testcase3( )
S.o.p ( "testcase3" ) ;
Enterprise Solutions Using J2EE / Lecture 60 4
Test The Class
public class TestHarness
public static void main ( String[ ] args ) throws Exception
int passed = 0, failed = 0 ;String className = "annotationsreflection.ClassUnderTest" ;for ( Method m : Class.forName ( className ).getMethods( ) )
if ( m.isAnnotationPresent ( TestMethod.class ) )
try
m.invoke ( null ) ; passed++ ;
- For each class a Class object is maintained by JRE- It contains information about the class
Get Class obj
Returns array of Method objects
Call to static method
Program Continued
catch ( Throwable ex )
S.o.p ( "Test %s failed: %s %n", m, ex.getCause( ) ) ;failed++ ;
S.o.p ( "Passed: %d, Failed %d%n", passed, failed ) ;
testcase1testcase2Test public static void annotationsreflection.ClassUnderTest.testcase2() failed: java.lang.RuntimeException: testcase2 Passed: 1, Failed 1
Output