Software Design Java Tutorial Software Design Java Tutorial
© SERG
Data Types
• Basic types:
– byte, boolean, char, short, int, long, float, double.
– New types cannot be created in Java. Must create
a Java class.
• Java arrays are supported as classes. E.g.,
• int [] i = new int [9]
• size of an array
i. lengt h
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Scalar Data Types In Java
• Standard Java data types:
– byt e
1 byte –
boolean 1 byte
– char
2 byte Unicode –
shor t 2 byte
– int
4 byte –
long 8 byte
– f loat
4 byte –
double 8 byte
dat a t ype var iable_name; int x;
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Java is Strongly Typed
• Java is a strongly typed language.
• Strong typing reduces many common
programming errors.
• Seems inconvenient to CC++
programmers.
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Java is Strongly Typed Cont’d
• Assignments must be made to compatible
data types.
• To contrast, in C:
– No difference between
int ,
char , and “boolean”
– Implicit type casts automatic type promotion
between many types.
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Variables
• Variables may be tagged as constants
f inal
keyword. •
Variables may be initialized at creation time
– f inal
variables must be initialized at creation time
• Objects are variables in Java and must be
dynamically allocated with the
new
keyword.
– E.g.,
a = new ClassA;
• Objects are freed by assigning them to
null, or when
they go out of scope automatic garbage collection.
– E.g.,
a = null;
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Variables Cont’d
int n = 1; char ch = ‘A’;
St r ing s = “Hello”; Long L = new Long100000;
boolean done = f alse; f inal double pi = 3. 14159265358979323846;
Employee j oe = new Employee; char [] a = new char[3];
Vect or v = new Vect or;
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Pointers References Variables
• Java does not support pointers.
• All variables are passed by value except
objects.
• Java classes either:
– Reference an object new keyword
– Alias an object assign to another object
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Expressions
• Java supports many ways to construct
expressions in precedence order:
– ++,--
Auto incrementdecrement –
+,- Unary plusminus
– , Multiplicationdivision
– Modulus
– +,-
Additionsubtraction
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Examples of Expressions
int x, y, z;
x = 0; x++;
y = x + 10; y = y 5;
z = 9 5;
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Assignment Operators
• Assignment may be simple
– x = y
• Or fancy with the following operators:
– =, =
– =
– +=, -=
– = bitwise AND
– |= bitwise OR
– = bitwise exclusive OR
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Examples of
Assignment Operators
int i = 5;
i += 10; i = 15
i = 12; i = 3
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Conditional Logic
• Conditional logic in Java is performed with the
if
statement.
• Unlike C++ a logic expression does not
evaluate to 0 FALSE and non-0 TRUE, it evaluates to either
t r ue
or
f alse
•
t r ue
,
f alse
are values of the
boolean
data type.
• Building compound conditional statements
– And, || Or, Not, , , ==, =, =, =, etc.
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Example of Conditional Logic
int i = 8; if i = 0 i 10
Syst em. out . print lni + “ is bet ween 0 and 9”; else
Syst em. out . print lni + “ is larger t han 9 or less t han 0”;
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Code Blocks
• Java, like many other languages, allows
compound code blocks to be constructed from simple statements.
• Simply enclose the block of statements
between braces. E.g.,
{ St at ement 1;
St at ement 2; St at ement 3;
}
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Looping Constructs
• Java supports three looping constructs:
– while
– do. . . while
– f or
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Examples of Looping Constructs
f or int i = 0; i 10; i++ {
Syst em. out . print lni; }
int i = 0; whilei 10
{
Syst em. out . print lni++; print s i bef ore
} applying i++
int i = 0; do
{
Syst em. out . print lni++; } whilei 10
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Java Exception Handling
• An exception is an object that defines an unusual
or erroneous situation.
• An exception is thrown by a program or a runtime
environment and can be caught and handled appropriately.
• Java supports user-defined and predefined
exceptions:
– ArithmeticException
– ArrayIndexOutOfBoundsException
– FileNotFoundException
– InstantiationException
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Java Exception Handling Cont’d
• Exception handling allows a programmer to
divide a program into a normal execution flow and an exception execution flow.
• Separation is a good idea especially since
80 of execution is in 20 of the code normal flow.
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Java Exception Handling Cont’d
• If an exception is not handled the program
will terminate abnormally and produce a message.
public class DivideBy0 { public st at ic void main St r ing[ ] ar gs {
Syst em.out .pr int ln10 0; }
}
J ava.lang.Ar it hmet icExcept ion: by zer o at DivdeBy0.mainDivdeBy0:3
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Try and Catch statements
• If an exception is thrown in statement-list1,
control is transferred to the appropriate with same exception class catch handler.
• After executing the statements in the catch clause,
control transfers to the statement after the entire try statement.
t r y { st at ement -list 1
} cat ch except ion-class1 var iable1 { st at ement -list 2
} cat ch except ion-class2 var iable2 { st at ement -list 3
} cat ch ….
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Exception Propagation
• If an exception is not caught and handled
where it occurs, it propagates to the calling method.
Software Design Java Tutorial Software Design Java Tutorial
© SERG
class Demo { st at ic public void main St r ing[] ar gs {
Except ion_Scope demo = new Except ion_Scope; Syst em.out .pr int ln“Pr ogr am beginning”;
demo.L1 ; Syst em.out .pr int ln“Pr ogr am ending”;
} }
class Except ion_Scope { public void L3 {
Syst em.out .pr int ln“Level3 beginning”; Syst em.out .pr int ln10 0;
Syst em.out .pr int ln“Level3 ending”;
} public void L2 {
Syst em.out .pr int ln“Level2 beginning”; L3 ;
Syst em.out .pr int ln“Level2 ending”;
} public void L1 {
Syst em.out .pr int ln“Level1 beginning”; t r y { L2 ;
} cat ch Ar it hmet icExcept ion pr oblem {
Syst em.out .pr int lnpr oblem.get Message ; pr oblem.pr int St ackTr ace ;
} Syst em.out .pr int ln“Level1 ending”;
} }
OUTPUT: OUTPUT:
Program beginning Level1 beginning
Level2 beginning Level3 beginning
by zero Java.lang.ArithmeticException: by zero
at Exception_Scope.L3Demo.java:18 at Exception_Scope.L2Demo.java:24
at Exception_Scope.L1Demo.java:31 at Exception_Demo.mainDemo.java:7
Level1 ending Program ending
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Throwing an Exception
impor t j ava.io.I OExcept ion;
public class Demo { public st at ic void main St r ing[ ] ar gs t hr ows Doh {
Doh pr oblem = new Doh “Doh”; t hr ow pr oblem;
Syst em.out .pr int ln“Dead code”;
} }
class Doh ext ends I OExcept ion { Doh St r ing message {
super message; }
}
• The exception is thrown but not caught.
OUTPUT: OUTPUT:
Doh: Doh at Demo.mainDemo.java:4
Software Design Java Tutorial Software Design Java Tutorial
© SERG
Finally clause
• A try statement may have a finally clause.
• The finally clause defines a section of code
that is executed regardless of how the try block in executed.
t r y { st at ement -list 1
} cat ch except ion-class1 var iable1 { st at ement -list 2
} cat ch …
} f inally { st at ement -list 3
}
Software Design Java Tutorial Software Design Java Tutorial
© SERG
IO
• Java supports a rich set of IO libraries:
– Network
– File
– Screen Terminal, Windows, Xterm
– Screen Layout
– Printer
Software Design Java Tutorial Software Design Java Tutorial
© SERG
IO Cont’d
• For this course we only need to write to or
read from the terminal screen or file.
• Use:
– Syst em. out . pr int ln
– Syst em. out . pr int
• May use ‘+’ to concatenate
int i, j ; i = 1;
j = 7; Syst em. out . print ln“i = “ + i + “ j = “ + j ;
Software Design Java Tutorial Software Design Java Tutorial
© SERG
IO Example with Reading and
Writing from or to the Screen
import j ava. io. ;
public class X { public st at ic void mainSt ring args[]
{
t r y{ Buf f er edReader dis = new Buf f er edReader
new I nput St reamReader Syst em. in; Syst em. out . pr int lnEnt er x ;
St r ing s = dis. r eadLine; double x= Double. valueOf s. t r im. doubleValue;
t rim r emoves leading t r ailing whit espace and ASCI I cont r ol char s. Syst em. out . pr int lnx = + x;
} cat ch Except ion e { Syst em. out . pr int lnERROR : + e ;
e. print St ackTr aceSyst em. out ;
} }
Software Design Java Tutorial Software Design Java Tutorial
© SERG
IO Example with Reading and
Writing from or to the File
import j ava. io. ; import j ava. ut il. ;
Program t hat reads f rom a f ile wit h space delimit ed name- pairs and wr it es t o anot her f ile t he same name- pair s delimit ed by a t ab.
class P {
public st at ic void mainSt ring [] args {
Buf f eredReader reader_d; int linecount = 0;
Vect or moduleN ames = new Vect or ;
t r y {
r eader _d = new Buf f er edReader new FileReader ar gs[0];
cont inued on next page
Software Design Java Tutorial Software Design Java Tutorial
© SERG
IO Example with Reading and
Writing from or to the File Cont’d
… cont inued f r om pr evious page.
while t r ue { St r ing line = r eader _d. r eadLine;
if line == null {
break; }
St r ingTokenizer t ok = new St r ingTokenizer line, ; St r ing module1 = t ok. next Token;
St r ing module2 = t ok. next Token; moduleN ames. addElement module1 + \ t + module2;
linecount ++; } end while
Software Design Java Tutorial Software Design Java Tutorial
© SERG
IO Example with Reading and
Writing from or to the File Cont’d
… cont inued f r om pr evious page.
cat ch Except ion e { e. pr int St ackTrace;
Syst em. exit 1;
}
Buf f er edW r it er wr it er _d;
t r y {
wr it er _d = new Buf f er edW r it er new FileW r it er ar gs[0] + . t ab;
Software Design Java Tutorial Software Design Java Tutorial
© SERG
IO Example with Reading and
Writing from or to the File Cont’d
f or int i = 0; i moduleN ames. size; i++ { St r ing modules = St ring moduleN ames. element At i;
wr it er _d. wr it emodules, 0, modules. lengt h- 1; wr it er _d. newLine;
} end f or wr it er _d. close;
} end t r y cat ch Except ion e {
e. pr int St ackTrace; Syst em. exit 1;