• No results found

Quick Introduction to Java

N/A
N/A
Protected

Academic year: 2021

Share "Quick Introduction to Java"

Copied!
19
0
0

Loading.... (view fulltext now)

Full text

(1)

Quick Introduction to Java

Dr. Chris Bourke

Department of Computer Science & Engineering

University of Nebraska—Lincoln

Lincoln, NE 68588, USA

Email: [email protected]

2015/10/30 20:02:28

Abstract

These are lecture notes used in CSCE 155 and CSCE 156 (Computer Science I &

II) at the University of Nebraska—Lincoln. They represent a short introduction to the Java programming language for students who already have a strong foundation in at least one high-level programming language.

Contents

1 Overview 3

1.1 History. . . 3 1.2 Key Aspects . . . 3 1.3 Hello World Demo . . . 4

2 Variables 5

2.1 Primitives . . . 5 2.2 Assignments & Literals . . . 6 2.3 Declaration . . . 7

3 Operators 8

4 Strings 8

5 Arrays 9

(2)

6 Conditionals 10

7 Loops 11

8 Input & Output 12

8.1 Command Line Arguments . . . 12

8.2 Standard I/O . . . 13

8.3 File Output . . . 14

9 Searching & Sorting 15 10 Classes 16 11 Exceptions 18

Code Samples

1 Hello World Java Program . . . 5

2 Demonstration of Java Wrapper Classes . . . 6

3 Different Bases in Java . . . 7

4 Casting in Java . . . 7

5 Strings in Java . . . 9

6 Arrays in Java. . . 10

7 Conditionals in Java . . . 10

8 Loops in Java . . . 11

9 Java Command Line Arguments . . . 13

10 Java Buffered Input . . . 13

11 Java Scanner . . . 14

12 Java File Output . . . 14

13 Searching & Sorting. . . 15

14 Bank Account class in Java . . . 17

15 Exceptions in Java . . . 19

(3)

1 Overview

1.1 History

• Developed by James Gosling, Sun Microsystems (1995)

• Designed with 5 basic principles – Simple, Object-oriented, familiar – Robust and secure

– Architecture-neutral and portable – High performance

– Interpreted, threaded and dynamic

• Version History – 1.0 1996

– 1.1 1997 introduced JDBC, inner classes, reflection – 1.2 1998 Collections framework

– 1.3 2000 JNDI, HotSpot JVM – 1.4 2002 Library improvements

– 1.5 2004 Generics introduced, enhanced-for loop (foreach loop), concurrency util- ities

– SE6 2006 JVM improvements (synch, compiler, garbage collection), Update 26 (June 7, 2011)

– 1.7 July 2011

• 2009–2010: Oracle purchases Sun

• Summer 2012: Oracle loses lawsuit to Google (APIs, interfaces cannot be copyrighted)

1.2 Key Aspects

• C-style syntax: semicolons, bracketed code blocks, identifiers

• Objected-oriented: everything is a class or belongs to a class

• No memory management – Built-in garbage collection

– When no valid references to an object exist, it is eligible for garbage collection

(4)

– JVM uses sophisticated algorithms to determine when it is optimal to perform garbage collection

– Little or no control on when or how this occurs

• Portable

– Write once, compile once, run anywhere

– Compiled code is run within a Java Virtual Machine

1.3 Hello World Demo

• Packages

– Packages allow you to organize code into a tree-like structure – Period delimits packages-subpackages

– Naming convention: all lower case, underscores; should go from general to specific – Actual code is stored in a directory tree corresponding to the package names

• Class declarations

– Java: everything is a class or belongs to a class

– Code must be in a file with the same name as the class, HelloWorld.java – Naming convention: UpperCamelCase

• Comments follow C-style comments

– //single line comments

– /* multi line comments */

– Javadoc style comments

• Main method declaration

• Standard output (System.out.println)

• JDK Libraries

– http://download.oracle.com/javase/6/docs/api/

– java.lang, java.util, java.io,java.sql, java.net,java.math,java.security – Collections: List, ArrayList, Set, HashSet, Map, HashMap

(5)

Code Sample 1: Hello World Java Program

 

1 p a c k a g e unl . cse ; // p a c k a g e d e c l a r a t i o n 2

3 // i m p o r t s w o u l d go h e r e 4

5 /* *

6 * A b a s i c h e l l o w o r l d p r o g r a m in J a v a 7 */

8 p u b l i c c l a s s H e l l o W o r l d { 9

10 // s t a t i c m a i n m e t h o d

11 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s []) { 12 S y s t e m . out . p r i n t l n (" H e l l o W o r l d ! ") ;

13 }

14

15 } 

• Command line demo – Editing

– Compiling: javac HelloWorld.java – Produces a.classfile (Java Bytecode) – Running: java HelloWorld

• IDE (Eclipse) demo

– Create a project, package, class – Compiling: automatic; running

2 Variables

2.1 Primitives

• A primitive is a type that is built-in to a language

• Java defines 8 primitives (see Table 1)

• Java does define default values for variables: zero for numeric types, falseforboolean types

• Wrapper classes provide an object-equivalent version for each primitive type

(6)

Type Details Wrapper Class byte 8-bit signed 2s complement integer Byte

short 16-bit signed 2s complement integer Short int 32-bit signed 2s complement integer Integer long 64-bit signed 2s complement integer Long float 32-bit IEEE 754 floating point number Float

double 64-bit floating point number Double

boolean may be set totrue orfalse Boolean

char 16-bit unicode character Character Table 1: Primitive types in Java

• Wrapper classes have many utility functions for conversion, parsing, etc.

• Instances can be null, may need to make null pointer checks

• Instances of such classes are immutable: once created, they cannot be changed; only new instances can be created

Code Sample 2: Demonstration of Java Wrapper Classes

 

1 // c o n v e r t a s t r i n g to an i n t e g e r : 2 String s = " 1 2 3 4 "

3 int a = I n t e g e r . p a r s e I n t ( s ) ;

4 String a_bin = I n t eg e r . t o S t r i n g (a , 2) ;

5 System . out . p r i nt l n ( a + " in b i n a r y is " + a _ b i n ) ; 6 I n t eg e r b ;

7 a += b ; // w o u l d r e s u l t in a N u l l P o i n t e r E x c e p t i o n

 

2.2 Assignments & Literals

• The standard assignment operator, =

• Standard numerical literals integers, floats (f), longs (l); scientific notation supported, 4.2e1 or4.2E1

• Different bases supported (see Code Sample 3)

• Character literals delimited by single quotes, char a = ’C’ or unicode (hex) escape:

char a = ’\u4FFA’

• String literals delimited by double quotes, String s = "hello";

• Standard escape sequences

(7)

Sequence Meaning

\b backspace

\t tab

\n line feed

\f form feed

\r carriage return

\" double quote

\’ single quote

\\ backslash

Code Sample 3: Different Bases in Java

 

1 int n ;

2 n = 0 b 0 0 1 0 _ 1 0 1 0 ; // binary , J a v a 7 o n l y 3 n = 052; // octal , l e a d i n g z e r o

4 n = 42; // d e c i m a l 5 n = 0 x2A ; // hex

 

2.3 Declaration

• Java is strongly typed ; every variable must be declared to have a particular type and will always be that type (aka statically typed )

• Identifier rules:

– Identifiers can include characters A-Z, a-z, 0-9, _, $ but cannot begin with a digit

– Identifiers are case sensitive

– Naming convention: lowerCamelCase

– Naming convention: CAPS_FOR_STATIC_CONSTANTS

– Cannot be a reserved word (seehttp://download.oracle.com/javase/tutorial/

java/nutsandbolts/_keywords.html)

• Scoping rules: variables are only valid within the block in which they are declared

• Casting: java does not allow implicit type casting when downcasting, does allow ex- plicit; see Code Sample 4

Code Sample 4: Casting in Java

 

1 Double x = 10; // c o m p i l e e r r o r 2 d o u b l e y = 10; // o k a y (!)

(8)

3 I n t eg e r z = 10.0; // c o m p i l e e r r o r 4 int a = 1 0 . 0 ; // c o m p i l e e r r o r

5 // e x p l i c i t t y p e c a s t i n g is r e q u i r e d : 6 int a = 10;

7 d o u b l e b = 1 0 . 5 ;

8 d o u b l e x = a + b ; // o k a y

9 int c = a + b ; // c o m p i l e e r r o r

10 int d = (int) ( a + b ) ; // e x p l i c i t c a s t ok , t r u n c a t i o n o c c u r s

 

3 Operators

• Unary operators: increment/decrement, ++, --

• Arithmetic: * / + - %

• Relational

– <, <=, >, >=

– Equality: ==, !=: careful when used with objects: reference comparison

• Logical: !, &&, || (can only be applied to boolean expressions or variables, not inte- gers!)

4 Strings

• Strings are a class provided as standard by the language

• Immutable; mutable version: StringBuilder

• Concatenation operator: +

• Comparison

– Using == is a reference operator, not a content comparison – Strings are naturally ordered (lexicographically) by the language – Meaning: they implement theComparable interface

– They have a method: a.compareTo(b) which returns:

∗ 0 ifa,b have the same content

∗ < 0 if aprecedes b(acomes before b)

∗ > 0 if asucceeds b(bcomes before a)

(9)

a b Result foo bar positive bar baz negative

foo foo zero

aaa aaaa negative

Table 2: Examples results of a.compareTo(b)

• Various other member and static methods exist:

– public char charAt(int)- returns the character at the specified position

– public String substring(int, int) - returns the substring between the indices (inclusive/exclusive)

– public String replaceAll(String, String) - replaces all matches to the (first) regular expression with the second

– More: http://docs.oracle.com/javase/6/docs/api/java/lang/String.html

Code Sample 5: Strings in Java

 

1 String s1 = " H e l l o " + " " + " W o r l d ! "; 2 System . out . p r i nt l n ( s1 ) ;

3

4 S t r i n g B u i l d e r sb = new S t r i n g B u i l d e r () ; 5 sb . append (" G o o d b y e ") ;

6 sb . append (" ") . a p p e n d (" W o r l d ! ") ; 7 String s2 = sb . t o S t r i n g () ;

8 System . out . p r i nt l n ( s2 ) ; 9

10 if( s1 . c o m p a r e T o ( s2 ) > 0) {

11 S y s t e m . out . p r i n t l n (" G o o d b y e W o r l d ! c o m e s s e c o n d ") ; 12 e l s e if( s1 . c o m p a r e T o ( s2 ) < 0) {

13 S y s t e m . out . p r i n t l n (" H e l l o W o r l d ! c o m e s s e c o n d ") ; 14 } e l s e {

15 S y s t e m . out . p r i n t l n (" T h e y are e q u a l s o m e h o w ") ; 16 }

17

18 // r e p l a c e all w h i t e s p a c e w i t h u n d e r s c o r e s : 19 String s3 = s1 . r e p l a c e A l l (" \ s ", " _ ") ;

 

5 Arrays

• All arrays are statically typed

(10)

• Implicit size declaration:

String myStrings[] = {"Hello", "world", "how", "are", "you"};

• Dynamic declaration using the new operator:

String myStrings[] = new String[10];

int myIds[] = new String[20];

• Arrays are zero-indexed and contiguous; size is kept track through a.lengthproperty:

• Multidimensional arrays supported

• Dynamic Collections alternative: ArrayList

Code Sample 6: Arrays in Java

 

1 int m y I d s [] = new int[ 1 0 ] ; 2 myIds [0] = 10;

3 System . out . p r i nt l n (" m y I d s is an a r r a y of s i z e " + m y I d s . l e n g t h + " , and the f i r s t e l e m e n t is " + m y I d s [ 0 ] ) ; 4

5 int m y M a t r i x [ ] [ ] = new int[ 5 ] [ 5 ] ;

6 m y M a t r i x [0][4] = 10; // f i r s t row , l a s t c o l u m n 7

8 ArrayList < Integer > myList = new A r r a y L i s t < Integer >() ; 9 myList . add (10) ;

10 myList . add (20) ; 11 myList . add (30) ;

12 System . out . p r i nt l n (" m y L i s t is an a r r a y l i s t of s i z e " +

m y L i s t . s i z e () + " , and the f i r s t e l e m e n t is " + m y L i s t . get (0) ) ;

 

6 Conditionals

• All the basic if-statements are supported

• Switch statements supported for integers

• Switch statements supported for Strings as of Java 7

Code Sample 7: Conditionals in Java

 

1 if( a > b ) {

2 S y s t e m . out . p r i n t l n (" foo ") ; 3 }

(11)

4

5 if( a > b ) {

6 S y s t e m . out . p r i n t l n (" foo ") ; 7 } e l s e {

8 S y s t e m . out . p r i n t l n (" bar ") ; 9 }

10

11 if( a > b ) {

12 S y s t e m . out . p r i n t l n (" foo ") ; 13 } e l s e if ( a == b ) {

14 S y s t e m . out . p r i n t l n (" bar ") ; 15 } e l s e {

16 S y s t e m . out . p r i n t l n (" baz ") ; 17 }

18

19 int m o n t h = . . . ; 20 s w i t c h( m o n t h ) { 21 c a s e 1:

22 S y s t e m . out . p r i n t l n (" J a n u a r y ") ; 23 b r e a k;

24 c a s e 2:

25 S y s t e m . out . p r i n t l n (" F e b r u a r y ") ; 26 b r e a k;

27 c a s e 3:

28 S y s t e m . out . p r i n t l n (" M a r c h ") ; 29 b r e a k;

30 d e f a u l t:

31 S y s t e m . out . p r i n t l n (" S m a r c h ") ; 32 b r e a k;

33 } 

7 Loops

• Basic loops supported: for, while, do-while

• Enhanced for-loop for collections (arrays or any class that implements the Iterable interface)

Code Sample 8: Loops in Java

 

1 for(int i =0; i < 1 0 ; i ++) {

2 S y s t e m . out . p r i n t l n (" i = " + i ) ; 3 }

4

(12)

5 int j = 0;

6 w h i l e( j < 10) {

7 S y s t e m . out . p r i n t l n (" j = " + j ) ;

8 j ++;

9 } 10

11 j = 0;

12 do {

13 S y s t e m . out . p r i n t l n (" j = " + j ) ; 14 j ++;

15 } w h i l e( j <10) ; 16

17 String m y S t r i n g s [] = {" h e l l o ", " w o r l d ", " foo ", " bar ", " baz "};

18 for( S t r i n g s : m y S t r i n g s ) { 19 S y s t e m . out . p r i n t l n ( s ) ; 20 }

21

22 // o l d e r i d i o m for I t e r a b l e c o l l e c t i o n s : 23 w h i l e( c . h a s N e x t () ) {

24 S y s t e m . out . p r i n t l n ( c . n e x t () ) ;

25 } 

8 Input & Output

8.1 Command Line Arguments

Most programs do not involve a user interface or even involve human interaction. Instead, programs executed from the command line can be configured by specifying command line arguments which are passed to the program when invoking it. For example:

~>./programName argument1 argument2

When a Java class is executed through the JVM via the command line, arguments can be passed to the class in a similar manner:

~>java JavaClass arg1 arg2 arg3 Note:

• Arguments are accessible in the main method through the args array:

public static void main(String args[])

• In most languages, the first argument is the name of the executable file. However, for Java, the first argument is not the class

• In the example above, arg[0] would hold the string arg1, etc.

(13)

Code Sample 9: Java Command Line Arguments

 

1 /* *

2 * T h i s p r o g r a m d e m o n s t r a t e s c o m m a n d l i n e a r g u m e n t u s a g e 3 * by p r i n t i n g out all the a r g u m e n t s p a s s e d to it w h e n

i n v o k e d . 4 */

5 p u b l i c c l a s s C o m m a n d L i n e A r g u m e n t D e m o { 6 p u b l i c s t a t i c v o i d m a i n ( S t r i n g a r g s []) { 7 if( a r g s . l e n g t h == 0) {

8 S y s t e m . out . p r i n t l n (" No c o m m a n d l i n e a r g u m e n t s p r o v i d e d "

) ;

9 } e l s e {

10 for(int i =0; i < a r g s . l e n g t h ; i ++) {

11 S y s t e m . out . p r i n t l n (" a r g s [ " + i + " ] = " + a r g s [ i ]) ;

12 }

13 }

14 }

15 } 

8.2 Standard I/O

• Standard Output: System.out (methods: print, println, printf)

• Printf-style formatting: String.format orSystem.out.printf

• Object-oriented formatting: java.util.Formatter class

• Several classes exist BufferedReader, BufferedWriter, InputStream, OutputStream

• Better alternative: Scanner

Code Sample 10: Java Buffered Input

 

1 try {

2 S t r i n g l i n e = n u l l;

3 // c r e a t e a B u f f e r e d R e a d e r f r o m a F i l e R e a d e r

4 B u f f e r e d R e a d e r br = new B u f f e r e d R e a d e r (new F i l e R e a d e r ("

i n p u t . txt ") ) ;

5 // r e a d the f i r s t l i n e 6 l i n e = br . r e a d L i n e () ;

7 // w h i l e the l i n e r e a d is not n u l l ( end of f i l e ) 8 w h i l e( l i n e != n u l l) {

9 // p r o c e s s the l i n e

10 S y s t e m . out . p r i n t l n ( l i n e ) ; 11 // r e a d the n e x t l i n e

(14)

12 l i n e = br . r e a d L i n e () ;

13 }

14 } c a t c h( E x c e p t i o n e ) {

15 ...

16 } 

Code Sample 11: Java Scanner

 

1 // r e a d f r o m the s t a n d a r d i n p u t : 2 S c a nn e r s = new S c a n n e r ( S y s t e m . in ) ;

3 System . out . p r i nt l n (" E n t e r an i n t e g e r : ") ; 4 int n = s . n e x t I n t () ;

5

6 // r e a d f r o m a f i l e

7 S c a nn e r s = new S c a n n e r (new F i l e (" i n p u t . txt ") ) ; 8 int x = s . n e x t I n t () ;

9 d o u b l e y = s . n e x t D o u b l e () ; 10 String s = s . next () ;

11 String line = s . n e x t L i n e () ; 12 w h i l e( s . h a s N e x t () ) {

13 l i n e = s . n e x t L i n e () ; 14 }

15

16 // by default , S c a n n e r t o k e n i z e s on w h i t e s p a c e , 17 // you can r e s e t t h i s to any r e g u l a r e x p r e s s i o n : 18 s . u s e D e l i m i t e r (" , ") ;

 

8.3 File Output

• Buffered text output: BufferedWriter and FileWriter

• Binary output: FileOutputStream

• Non-buffered text output: PrintWriter

Code Sample 12: Java File Output

 

1 // B u f f e r e d t e x t o u t p u t :

2 File f = new F i l e (" o u t f i l e . txt ") ;

3 B u f f e r e d W r i t e r bw = new B u f f e r e d W r i t e r (new F i l e W r i t e r ( f ) ) ; 4 // can w r i t e s t r i n g or c h a r a c t e r d a t a

5 bw . write (" H e l l o W o r l d \ n ") ; 6

7 // B i n a r y d a t a o u t p u t : 8 b y t e b A r r a y [] = . . . ;

(15)

9 File f = new F i l e (" o u t f i l e . bin ") ;

10 F i l e O u t p u t S t r e a m fos = new F i l e O u t p u t S t r e a m ( f ) ; 11 fos . write ( bArray ) ;

12

13 // Non - b u f f e r e d t e x t o u t p u t ( easier , but f a i l s s i l e n t l y ) : 14 File f = new F i l e (" o u t f i l e 0 2 . txt ") ;

15 P r i n t W r i t e r pw = new P r i n t W r i t e r ( f ) ; 16 pw . print (" H e l l o ") ;

17 pw . print (10) ; 18 pw . print (3.14) ; 19 // or :

20 pw . printf (" % s , % d , %.4 f \ n ", " H e l l o ", 10 , 3 . 1 4 ) ;

 

9 Searching & Sorting

• The Arraysclass provides two sort methods for arrays – Arrays.sort(...)

– Arrays.sort(T a[], Comparator<? super T> c)

• The Collectionsclass provides two sort methods for lists – Collections.sort(List<T> list)

– Collections.sort(List<T> list, Comparator<? super T> c)

• First version is for anything that is naturally ordered : any class that implements the Comparable interface

• Second version is for any type, but you must provide a Comparatorfor it

• Searching: binarySearch methods, collections have contains, indexOf methods

Code Sample 13: Searching & Sorting

 

1 int ids [] = . . . ; 2 Arrays . sort ( ids ) ; 3

4 Comparator < Student > c = new C o m p a r a t o r < Student >() { 5 p u b l i c int c o m p a r e ( S t u d e n t s1 , S t u d e n t s2 ) {

6 if( s1 . g e t G P A () > s2 . g e t G P A () ) {

7 r e t u r n -1;

8 } e l s e if ( s1 . g e t G P A () < s2 . g e t G P A () ) {

9 r e t u r n 1;

10 } e l s e {

(16)

11 r e t u r n 0;

12 }

13 }

14 };

15

16 S t u de n t roster [] = ...;

17 Arrays . sort ( roster , c ) ; 18

19 ArrayList < Student > roster = new A r r a y L i s t < Student >() ; 20 C o l l e c t i o n s . sort ( roster , c ) ;

 

10 Classes

Object-oriented programming involves the interaction of complex, abstract data types (ADTs), often realized in programming languages as classes. Java is a class-based OOP language.

Classes can be viewed as a “blueprint” for creating (called instantiating) instances which provide both state and behavior.

• Declaration

• Member variables: visibility-level type name;

• Visibility keywords (cf. Table 3), accessors/mutators: getters and setters

• Member methods: declared inside a class

• Constructors: same name as the class, no return type, multiple constructors can be defined; default one provided if none are defined

• Instantiation (new keyword invokes a constructor)

• Usage: dot operator

• Other modifiers

– staticcan be used with a method or variable to make it a member of the class instead of instances of the class. Access would then be through the class rather than an instance: BankAccount.foo()

– final can be used with a variable to make it a constant ; attempts to modify a finalvariable are a compiler error

– final can also be used on methods (to make them non-virtual); and classes (to make them non-derivable)

(17)

Code Sample 14: Bank Account class in Java

 

1 p u b l i c c l a s s B a n k A c c o u n t { 2

3 p u b l i c s t a t i c f i n a l S t r i n g B A N K _ N A M E = " F i r s t I n t e r n a t i o n a l B a n k Co . ";

4

5 p r i v a t e int b a n k A c c o u n t I d ; 6 p r i v a t e S t r i n g l a b e l;

7 p r i v a t e d o u b l e b a l a n c e ; 8 p r i v a t e d o u b l e apr ; 9

10 p u b l i c B a n k A c c o u n t (int b a n k A c c o u n t I d , S t r i n g label, d o u b l e balance , d o u b l e apr ) {

11 t h i s. b a n k A c c o u n t I d = b a n k A c c o u n t I d ; 12 t h i s.l a b e l = l a b e l;

13 t h i s. b a l a n c e = b a l a n c e ; 14 t h i s. apr = apr ;

15 }

16

17 p u b l i c B a n k A c c o u n t (int b a n k A c c o u n t I d , S t r i n g l a b e l) { 18 t h i s( b a n k A c c o u n t I d , label, 0.0 , 0 . 0 ) ;

19 }

20

21 p u b l i c int g e t B a n k A c c o u n t I d () { 22 r e t u r n t h i s. id ;

23 }

24

25 p u b l i c v o i d s e t B a l a n c e (d o u b l e b a l a n c e ) { 26 t h i s. b a l a n c e = b a l a n c e ;

27 }

28

29 // m o r e g e t t e r s and s e t t e r s as d e s i r e d h e r e 30

31 p u b l i c v o i d d e p o s i t (d o u b l e d e p o s i t ) { 32 t h i s. b a l a n c e += d e p o s i t ;

33 }

34

35 p u b l i c d o u b l e g e t M o n t h l y I n t e r e s t E a r n e d () { 36 r e t u r n t h i s. b a l a n c e * t h i s. apr / 1 2 . 0 ;

37 }

38

39 p r i v a t e d o u b l e g e t A P Y () {

40 r e t u r n M a t h . exp (t h i s. apr ) - 1;

41 }

42

(18)

43 @ O v e r r i d e

44 p u b l i c S t r i n g t o S t r i n g () {

45 r e t u r n t h i s.l a b e l + " ( " + t h i s. b a n k A c c o u n t I d + " ) $ " + t h i s. b a l a n c e ;

46 }

47 } 48 49 ...

50

51 B a n k A c c o u n t a = new B a n k A c c o u n t (1234 , " C h e c k i n g ") ; 52 a . s e t B a l a n c e ( 1 0 0 0 . 0 ) ;

53 a . d e p o s i t ( 1 0 0 . 0 ) ;

54 a . d e p o s i t ( a . g e t M o n t h l y I n t e r e s t E a r n e d () ) ; 55 System . out . p r i nt l n ( a ) ;

56

57 System . out . p r i nt l n (" B a n k N a m e : " + B a n k A c c o u n t . B A N K _ N A M E ) ;

 

Keyword Class Package Subclass(es) World

public Y Y Y Y

protected Y Y Y N

public Y Y N N

private Y N N N

Table 3: Visibility Keywords and Access Levels

11 Exceptions

• Run-time errors occur when something goes wrong and your program cannot handle it (or by design shouldn’t)

• We may be able to recover from some errors by handling them

• AnExceptionis an error that is not usual, but could be anticipated (FileNotFoundException )

• Exceptions can be thrown or caught and handled

• Handling can be done in a try-catch-finally block

• Many predefined standard exceptions

• Uncaught exceptions will bubble up until caught or it kills the JVM process

(19)

Code Sample 15: Exceptions in Java

 

1 String s = ...;

2 int n ; 3 try {

4 // p o t e n t i a l l y u n s a f e c o d e : 5 n = I n t e g e r . p a r s e I n t ( s ) ;

6 } c a t c h( N u m b e r F o r m a t E x c e p t i o n nfe ) {

7 S y s t e m . out . p r i n t l n (" S t r i n g d o e s not c o n t a i n a v a l i d n u m e r i c r e p r e s e n t a t i o n ") ;

8 } c a t c h( N u l l P o i n t e r E x c e p t i o n npe ) {

9 S y s t e m . out . p r i n t l n (" S t r i n g is n u l l ! ") ; 10 } c a t c h( E x c e p t i o n e ) {

11 S y s t e m . out . p r i n t l n (" S o m e o t h e r e x c e p t i o n o c c u r r e d , s t a c k t r a c k f o l l o w s ... ") ;

12 e . p r i n t S t a c k T r a c e () ; 13 } f i n a l l y {

14 // t h i s c o d e b l o c k w i l l be e x e c u t e d w h e t h e r or not an e x c e p t i o n is t h r o w n

15 // c o u l d be u s e d to c l e a n up any o u t s t a n d i n g r e s o u r c e s 16 }

17

18 // t h r o w i n g : 19 if( n == 0) {

20 t h r o w new R u n t i m e E x c e p t i o n (" c a n n o t d i v i d e by z e r o ! ") ;

21 } 

References

Related documents