Vous êtes sur la page 1sur 64

Objective 1, Creating Arrays

Write code that declares, constructs and initializes arrays of any base type using any of the permitted forms, both for declaration and for initialization.

Arrays
Arrays in Java are similar in syntax to arrays in other languages such as C/C++ and isual !asic. "o#ever, Java removes the feature of C/C++ #hereby you can bypass the $% style accessing of elements and get under the hood using pointers. &his capability in C/C++ , although po#erful, ma'es it easy to #rite buggy soft#are. !ecause Java does not support this direct manipulation of pointers, this source of bugs is removed. An array is a type of ob(ect that contains values called elements. &his gives you a convenient bag or holder for a group of values that can be moved around a program, and allo#s you to access and change values as you need them. &o give a trivial example you could create an array of )trings, each one containing the names of members in a sports team. &he array can be passed into methods that need to access the names of each team member. *f a ne# member (oins the team, one of the old names can be modified to become that of the ne# member. &his is much more convenient than having an arbitrary number of individual variables such as player+, player,, player- etc .nli'e variables #hich are accessed by a name, elements are accessed by numbers starting from zero. !ecause of this you can /#al'/ through an array, accessing each element in turn. Arrays are very much li'e ob(ects, they are created #ith the new 'ey#ord, and have the methods of the great grandparent 0b(ect class. Arrays may store primitives or references to ob(ects. 1very element of an array must be of the same type &he type of the elements of an array is decided #hen the array is declared. *f you need a #ay of storing a group of elements of different types, you can use the collection classes #hich are a ne# feature in the Java, exam, and are discussed in section +2. 3ou can store an array of ob(ect references, #hich you can access, extract and use li'e any other ob(ect reference.

Declaration without allocation


&he declaration of an array does not allocate any storage, it (ust announces the intention of creating an array. A significant difference to the #ay C/C++ declares an array is that no size is specified #ith the identifier. &hus the follo#ing #ill cause a compile time error
int num[5];

&he size of an array is given #hen it is actually created #ith the new operator thus
int num[];

num = new int[5];

3ou can thin' of the use of the #ord new as similar to the use of the #ord new #hen initialising a reference to an instance of a class. &he name num in the examples is effectively saying that num can hold a reference to any size array of int values.

Simultaneous declaration and creation


&his can be compressed into one line as
int num[] = new int[5];

Also the s4uare brac'ets can be placed either after the data type or after the name of the array. &hus both of the follo#ing are legal
int[] num; int num[];

3ou can read these as either An integer array named num An integer type in an array called num. 3ou might also regard it as enough choice to cause confusion

Java vs C/C++ arrays

Java arrays now how big they are, and the language !rovides !rotection "rom accidentally wal ing o"" the end o" them#

&his is particularly handy if you are from a isual !asic bac'ground and are not used to constantly counting from 2. *t also helps to avoid one of the more insidious bugs in C/C+ + programs #here you #al' off the end of an array and are pointing to some arbitrary area of memory. &hus the follo#ing #ill cause a run time error, ArrayIndexOutOfBoundsException
int[] num= new int[5]; for(int i =0; i<6; i++){ num[i]=i*2;

&he standard idiom for #al'ing through a Java array is to use the length member of the array thus
int[] num= new int[5]; for(int i =0; i<num.length; i++){ num[i]=i*2; }

Arrays now their own si$e


Just in case you s'ipped the C/C++ comparison, arrays in Java al#ays 'no# ho# big they are, and this is represented in the length field. &hus you can dynamically populate an array #ith the follo#ing code
int my rr y[]=new int[!0]; for(int "=0; "<my rr y.length;"++){ my rr y["]="; }

5ote that arrays have a length field not a length() method. When you start to use Strings you #ill use the string, length method, as in s.length678 With an array the length is a field 6or property7 not a method.

Java vs %isual &asic Arrays


Arrays in Java al#ays start from zero. isual !asic arrays may start from + if the Option base statement is used. &here is no Java e4uivalent of the isual !asic redim preserve command #hereby you change the size of an array #ithout deleting the contents. 3ou can of course create a ne# array #ith a ne# size and copy the current elements to that array. An array declaration can have multiple sets of s4uare brac'ets. Java does not formally support multi dimensional arrays, ho#ever it does support arrays of arrays, also 'no#n as nested arrays. &he important difference bet#een multi dimensional arrays, as in C/C++ and nested arrays, is that each array does not have to be of the same length. *f you thin' of an array as a matrix, the matrix does not have to be a rectangle. According to the Java 9anguage )pecification

6http://(ava.sun.com/docs/boo's/(ls/html/+2.doc.html;,<=2>7 !he number of brac"et pairs indicates the depth of array nesting# *n other languages this #ould correspond to the dimensions of an array. &hus you could set up the s4uares on a map #ith an array of , dimensions thus
int i[][];

&he first dimension could be ? and second 3 coordinates.

Combined declaration and initiali$ation


*nstead of looping through an array to perform initialisation, an array can be created and initialised all in one statement. &his is particularly suitable for small arrays. &he follo#ing #ill create an array of integers and populate it #ith the numbers 2 through @
int #[]=new int[] {0$!$2$%$&};

5ote that at no point do you need to specify the number of elements in the array. 3ou might get exam 4uestions that as' if the follo#ing is correct.
int #=new int[5] {0$!$2$%$&} ''(rong$ will not )om*ile+

3ou can populate and create arrays simultaneously #ith any data type, thus you can create an array of strings thus
,tring -[]=new ,tring[] {./ero.$.0ne.$.1wo.$.1hree.$.2our.};

&he elements of an array can be addressed (ust as you #ould in C/C++ thus
,tring -[]=new ,tring[] {./ero.$.0ne.$.1wo.$.1hree.$.2our.}; ,y-tem.out.*rintln(-[0]);

&his #ill output the string Aero.

De"ault values o" arrays


.nli'e other variables that act differently bet#een class level creation and local method level creation, Java arrays are al#ays set to default values.

'he elements o" arrays are always set to de"ault values wherever the array is created

&hus an array of integers #ill all be set to zero, an array of boolean values #ill al#ays be set to false. &hus the follo#ing code #ill compile #ithout error and at runtime #ill output 2.
*u3li) )l -- 4rr y5nit{ *u3li) -t ti) 6oi7 m in(,tring int[] i = new int[!0]; ,y-tem.out.*rintln( i[0]); } } rg6[]){

!y contrast #ith primitive variables, the follo#ing code #ill thro# a compile time error #ith a message something li'e Bvariable i might not have been initializedC
u3li) )l -- 8rim5nit{ *u3li) -t ti) 6oi7 m in(,tring int i; ,y-tem.out.*rintln(i); } } rg6[]){

(uestions

(uestion 1)
"o# can you reDsize an array in a single statement #hilst 'eeping the original contentsE +7 .se the set)ize method of the Array class ,7 .se .til.set)ize6int i5e#)ize7 -7 use the size67 operator @7 5one of the above

(uestion *)
3ou #ant to find out the value of the last element of an array. 3ou #rite the follo#ing code. What #ill happen #hen you compile and run itE
*u3li) )l -- 9y4r{

*u3li) -t ti) 6oi7 m in(,tring rg6[]){ int[] i = new int[5]; ,y-tem.out.*rintln(i[5]); } }

+7 Compilation and output of 2 ,7 Compilation and output of null -7 Compilation and runtime 1xception @7 Compile time error

(uestion +)
3ou #ant to loop through an array and stop #hen you come to the last element. !eing a good Java programmer, and forgetting everything you ever 'ne# about C/C++ you 'no# that arrays contain information about their size. Which of the follo#ing can you useE
!)my 2)my %)my &)my rr rr rr rr y.length(); y.length; y.-i:e y.-i:e();

(uestion ,)
3our boss is so pleased that you have #ritten "elloWorld he she has given you a raise. )he no# puts you on an assignment to create a game of &ic&ac&oe 6or noughts and crosses as it #as #hen * #ere a #ee boy7. 3ou decide you need a multi dimensioned array to do this. Which of the follo#ing #ill do the (obE
!) int i =new int[%][%];

2) int[] i =new int[%][%]; %) int[][] i =new int[%][%]; &) int i[%][%]=new int[][];

(uestion -)
3ou #ant to find a more elegant #ay to populate your array than looping through #ith a for statement. Which of the follo#ing #ill do thisE
!) my4rr y{ [!]=.0ne.; [2]=.1wo.; [%]=.1hree.; en7 with

2),tring -[5]=new ,tring[] {./ero.$.0ne.$.1wo.$.1hree.$.2our.}; %),tring -[]=new ,tring[] {./ero.$.0ne.$.1wo.$.1hree.$.2our.}; &),tring -[]=new ,tring[]={./ero.$.0ne.$.1wo.$.1hree.$.2our.};

(uestion .)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
*u3li) )l -- 4r7e){ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 4r7e) 7 = new 4r7e)(); 7. metho7(); } *u3li) 6oi7 metho7(){ int i ![]= {!$2$%}; int[] i 2 = {!$2$%}; int i %[] = new int[] {!$2$%}; ,y-tem.out.*rint(i %.length); } }

+7 Compile time error, ia- is not created correctly ,7 Compile time error, arrays do not have a length field -7 Compilation but no output @7 Compilation and output of -

Answers

Answer 1)
@7 5one of the above 3ou cannot /resize/ and array. 3ou need to create a ne# temporary array of a different size and populate it #ith the contents of the original. Java provides resizable containers #ith classes such as ector or one of the members of the collection classes.

Answer *)
-7 Compilation and runtime 1xception 3ou #ill get a runtime error as you attempt to #al' off the end of the array. !ecause arrays are indexed from 2 the final element #ill be i$@%, not i$>%

Answer +)

,7 myarray.length8

Answer ,)
%) int[][] i=new int[%][%];

Answer -)
%),tring -[]=new ,tring[] {./ero.$.0ne.$.1wo.$.1hree.$.2our.};

Answer .
@7 Compilation and output of All of the array declarations are correct, if you find that unli'ely, try compiling the code yourself

Objective *, Declaring classes and variables


Feclare classes, inner classes, methods, instance variables static, variables and automatic 6method local7 variables, ma'ing appropriate use of all permitted modifiers 6such as public final static abstract and so forth7. )tate the significance of each of these modifiers both singly and in combination and state the effect of pac'age relationships on declared items 4ualified by these modifiers.

Comment on the objective


* find it a little disturbing that the ob(ective uses the #ords and so forth # * suspect this means you should also be a#are of, native transient synchronized volatile

/hat is a class0

0ne rather dry definition of a class describes it as /an aggregation of methods and data/. *t is possibly more instructive to vie# the concept in the light of the thin'ing on programming that came before classes. &he main programming concept before Classes and 0b(ect 0rientation #as that of structured programming. &he idea of structured programming is that the programmer brea's do#n a complex problem into small chun's of code 'no#n variously as functions or subroutines. &his fits into the idea that a good #ay to deal #ith a large complex problem is by brea'ing it up into a se4uence of smaller more manageable problems. Although structured programming has great benefits in terms of managing complexity it does not lead itself easily to reDuse code. Grogrammers found themselves constantly /reD inventing/ the #heel. *n an attempt to ta'e ideas from the #orld of physical ob(ect thin'ers on programming came up #ith the ob(ect of 0b(ect 0rientation 6sometimes called 007. &a'e the example of a computer manufacturer coming up #ith a ne# model of GC. *f computer manufacturers used a similar process to much of the #orld of programming, this #ould involve starting setting teams to design a ne# CG. chip, a ne# video chip and maybe another team to design, layout and create a motherboard. *n reality this doesnHt happen. !ecause of the standardisation of interfaces in computer components, manufacturers contact the component suppliers and negotiate the specifications of the machine they are going to create. 5ote the significance of the standardisation of the interfaces of the components.

Com!aring C++/%& classes with Java


!ecause Java #as designed to be easy for C++ programmers to learn there are many similarities bet#een the #ay the t#o languages deal #ith classes. !oth C++ and Java have inheritance, polymorphism, and data hiding using visibility modifiers. )ome of the #ays in #hich they differ are to do #ith ma'ing Java an easier language to learn and use. &he C++ language implements multiple inheritance and thus a class can have more than one parent 6or base7 class. Java allo#s only single inheritance and thus can only ever have a single parent. &o overcome this limitation Java has a feature called interfaces. &he language designers decided that interfaces #ould give some of the benefits of multiple inheritance #ithout the dra#bac's. All Java classes are descendants of the great ancestor class called Ob$ect. 0b(ects in isual !asic are some#hat of a bolt on afterthought to the language. isual !asic is sometimes called an 0b(ect !ased language rather than 0b(ect 0riented. *t is almost as if the language designers decided that classes are cool and #ith ! version @ decided that they #ould create a ne# type of module, call it a class and use the dot notation to ma'e it more li'e C++. &he crucial element missing from the ! concept of class is that of inheritance. With !> Iicrosoft delivered the concept of interfaces #hich acts similarly to the Java concept of an interface. )ome of the main similarities bet#een ! classes and Java classes is the use of references and the 'ey#ord new #ord.

'he role o" classes in Java


Classes are the heart of Java, all Java code occurs #ithin a class. &here is no concept of free standing code and even the most simple "elloWorld application involves the creation of a class. &o indicate that a class is a descendent of another class the extends 'ey#ord is used. *f the extends 'ey#ord is not used the class #ill be a descended of the base class 0b(ect, #hich gives it some basic functionality including the ability to print out its name and some of the capability re4uired in threads.

'he sim!lest o" class


&he minimum re4uirements to define a class are the 'ey#ord class, the class name and the opening and closing braces. &hus
)l -- )l --n me {}

is a syntactically correct, if not particularly useful class 6surprisingly * have found myself defining classes li'e this, #hen creating examples to illustrate inheritance7. 5ormally a class #ill also include an access specifier before the 'ey#ord class and of course, a body bet#een the braces. &hus this is a more sensible template for a class.
*u3li) )l -- )l --n me{ '';l -- 3o7y goe- here }

Creating a sim!le HelloWorld class


"ere is a simple "elloWorld program that #ill output the string /hello #orld/ to the console.
*u3li) )l -- <ello(orl7{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ ,y-tem.out.*rintln(.<ello worl7.); } }''=n7 )l -- 7efinition

&he 'ey#ord public is a visibility modifier that indicates this class should be visible to any other class. 0nly one outer class per file can be declared public. *nner classes #ill be covered else#here. *f you declare more than one class in a file to be public, a compile time error #ill occur. 5ote that Java is case sensitive in every respect. &he file that contains this class must be called "elloWorld.Java. 0f course this is some#hat of an

anomaly on Iicrosoft platforms that preserve, yet ignore the case of letters in a file name. &he 'ey#ord class indicates that a class is about to be defined and %ello&orld is the name of that class. &he curly braces indicate the start of the class. 5ote that the closing brace that ends the class definition does not involve any closing semi colon. &he comment
''=n7 )l -- 7efinition

uses the style of single line comments that is available in C/C++. Java also understands the multiDline /J J/ form of comments.

Creating an instance o" a class


&he %ello&orld application as described above is handy to illustrate the most basic of applications that you can create, but it misses out on one of the most crucial elements of using classes, the use of the 'ey #ord new Which indicates the creation of a ne# instance of a class. *n the %ello&orld application this #as not necessary as the only method that #as called #as System#out#println, #hich is a static method and does not re4uire the creation of a class using the ne# 'ey#ord. )tatic methods can only access static variables, of #hich only one instance can exist per class. &he %ello&orld application can be slightly modified to illustrate the creation of a ne# instance of a class.
*u3li) )l -- <ello(orl72{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ <ello(orl72 hw = new <ello(orl72(); hw. metho7(); }

*u3li) 6oi7 metho7(){ ,y-tem.out.*rintln(.<ello worl7.); } }

&his code creates a ne# instance of itself #ith the line


<ello(orl72 hw = new <ello(orl72();

&his syntax of creating a ne# instance of a class is basic to the use of classes. 5ote ho# the name of the class appears t#ice. &he first time indicates the data type of the reference

to the class. &his need not be the same as the actual type of the class as indicated after the use of the new 'ey#ord. &he name of this instance of the class is hw. &his is simply a name chosen for a variable. &here is a naming convention that an instance of a class starts #ith a lo#er case letter, #hereas the definition of a class starts #ith an upper case letter. &he empty parenthesis for the name of the class %ello&orld() indicate that the class is being created #ithout any parameters to its constructor. *f you #ere creating an instance of a class that #as initialized #ith a value or a string such as the label of a button the parenthesis #ould contain one or more initializing values.

Creating 1ethods
As illustrated in the last example %ello&orld', a method in Java is similar to a function in C/C++ and a function or sub in isual !asic. &he method called amethod in that example is the method called amethod in this example is declared as public &o indicate it can be accessed from any#here. *t has a return type of void indicating no value #ill be returned. And it has empty parenthesis, indicating that it ta'es no parameters. &he same method might have been defined in these alternative #ays
*ri6 te 6oi7 metho7(,tring -) *ri6 te 6oi7 metho7(int i$ ,tring -) *rote)te7 6oi7 metho7(int i)

&hese examples are to illustrate some other typical signatures of methods. &he use of the 'ey#ords private and protected #ill be covered else#here. &he difference bet#een Java methods and methods in a non 00 language such as C is that the methods belong to a class. &his means they are called using the dot notation indicating the instance of the class that the code belongs to. 6)tatic methods are an exception to this but donHt #orry about that at the moment7. &hus in "elloWorld, amethod #as called thus
<ello(orl7 hw = new <ello(orl7(); hw. metho7();

*f other instances of the %ello&orld class had been created the method could have been called from each instance of the class. 1ach instance of the class #ould have access to its

o#n variables. &hus the follo#ing #ould involve calling the amethod code from different instances of the class.
<ello(orl7 hw = new <ello(orl7(); <ello(orl7 hw2 = new <ello(orl7(); hw. metho7(); hw2. metho7();

&he t#o instances of the class hw and hw' might have access to different variables.

Automatic local variables


Automatic variables are method variables. &hey come into scope #hen the method code starts to execute and cease to exist once the method goes out of scope. As they are only visible #ithin the method they are typically useful for temporary manipulation of data. *f you #ant a value to persist bet#een calls to a method then a variable needs to be created at class level. An automatic variable #ill /shado#/ a class level variable. &hus the follo#ing code #ill print out KK and not +2.
*u3li) )l -- ,h 7{ *u3li) int i,h 7=!0; *u3li) -t ti) 6oi7 m in(,tring rg6[]){ ,h 7 - = new ,h 7(); -. metho7(); }''=n7 of m in *u3li) 6oi7 metho7(){ int i,h 7=>>; ,y-tem.out.*rintln(i,h 7); }''=n7 of metho7 }

1odi"iers and enca!sulation

'he visibility modi"iers are !art o" the enca!sulation mechanism "or Java# 2nca!sulation allows se!aration o" the inter"ace "rom the im!lementation o" methods#

&he visibility modifiers are a 'ey part of the encapsulation mechanism for (ava. 1ncapsulation allo#s separation of the interface from the implementation of methods. &he benefit of this is that the details of the code inside a class can be changed #ithout it

affecting other ob(ects that use it. &his is a 'ey concept of the 0b(ect 0riented paradaigm 6had to use that #ord some#here eventually7. 1ncapsulation generally ta'es form of methods to retrieve and update the values of private class variables. &hese methods are 'no#n as a accessor and mutator methods. &he accessor 6or get7 method retrieves the value and the mutator changes 6or sets7 the value. &he naming convention for these methods are set(oo to change a variable and get(oo to obtain the contents of a variable. An aside note: the use of get and set in the naming of these methods is more significant than (ust programmer convenience and is an important part of the Javabeans system. Javabeans are not covered in the programmer exam ho#ever. &a'e the example #here you had a variable used to store the age of a student. 3ou might store it simply #ith a public integer variable int iAge) later #hen your application is delivered you find that some of your students have a recorded age of more than ,22 years and some have an age of less than zero. 3ou are as'ed to put in code to chec' for these error conditions. )o #herever your programs change the age value, you #rite if statements that chec' for the range.
if(i4ge ? @0){ ''7o -omething } if (i4ge <%){ ''7o -omething }

*n the process of doing this you miss some code that used the iAge variable and you get called bac' because you have a +K year old student #ho is on your records has being +K2 years old. &he 0b(ect 0riented approach to this problem using encapsulation, is to create methods that access a private field containing the age value, #ith names li'e setAge and getAge. &he setAge method might ta'e an integer paramete and update the private value for Age and the getAge method #ould ta'e no parameter but return the value from the private age field.
*u3li) 6oi7 -et4ge(int i,tu7ent4ge){ i4ge = i,tu7ent4ge; } *u3li) int get4ge(){ return i4ge; }

At first this seems a little pointless as the code seems to be a long #ay around something that could be done #ith simple variable manipulation. "o#ever #hen they come bac' to you #ith the re4uirement to do more and more validation on the iAge field you can do it all in these methods #ithout affecting existing code that uses this information. !y this approach the implementation of code, 6the actual lines of program code7, can be changed #hilst the #ay it loo's to the outside #orld 6the interface7 remains the same.

3rivate
Grivate variables are only visible from #ithin the same class as they are created.in. &his means they are 50& visible #ithin sub classes. &his allo#s a variable to be insulated from being modified by any methods except those in the current class. As described in modifiers and encapsulation, this is useful in separating the interface from the implementation.
)l -- A -e{ *ri6 te int i=n)=!0; *u3li) 6oi7 -et=n)(int i=n)B l){ if(i=n)B l < !000){ i=n)=i=n)B l; }el-e ,y-tem.out.*rintln(.=n) 6 lue mu-t 3e le-- th n !000.); ''0r 8erh *- thow n eC)e*tion }''=n7 if } *u3li) )l -- =n){ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ A -e 3 = new A -e(); 3.-et=n)(!00!); }''=n7 of m in }

3ublic
&he public modifier can be applied to a variable 6field7 or a class. *t is the first modifier you are li'ely to come across in learning Java. *f you recall the code for the %ello&orld.Java program the class #as declared as
*u3li) )l -- <ello(orl7

&his is because the Java irtual Iachine only loo's in a class declared as public for the magic main startup method
*u3li) -t ti) 6oi7 m in(,tring rg6[])

A public class has global scope, and an instance can be created from any#here #ithin or outside of a program. 0nly one non inner class in any file can be defined #ith the public

'ey#ord. *f you define more than one non inner class in a file #ith the 'ey#ord public the compiler #ill generate an error. .sing the public modifier #ith a variable ma'es it available from any#here. *t is used as follo#s,
*u3li) int myint =!0;

*f you #ant to create a variable that can be modified from any#here you can declare it as public. 3ou can then access it using the dot notation similar to that used #hen calling a method.
)l -- A -e { *u3li) int iDo=n)=@@; } *u3li) )l -- Do=n){ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ A -e 3 = new A -e(); 3.iDo=n)=2; ,y-tem.out.*rintln(3.iDo=n)); }''=n7 of m in }

5ote that this is not the generally suggested #ay as it allo#s no separation bet#een the interface and implementation of code. *f you decided to change the data type of i*oEnc+ you #ould have to change the implementation of every part of the external code that modifies it.

3rotected
&he protected modifier is a slight oddity. A protected variable is visible #ithin a class, and in sub classes, the same pac'age but not else#here. &he 4ualification that it is visible from the same pac'age can give more visibility than you might suspect. Any class in the same directory is considered to be in the default pac'age, and thus protected classes #ill be visible. &his means that a protected variable is more visible than a variable defined #ith no access modifier. A variable defined #ith no access modifier is said to have default visibility. Fefault visibility means a variable can be seen #ithin the class, and from else#here #ithin the same pac'age, but not from subDclasses that are not in the same pac'age.

Static
Static is not directly a visibility modifier, although in practice it does have this effect. &he modifier static can be applied to an inner class, a method and a variable. .tility code is often 'ept in static methods, thus the Iath class class has an entire set of utility methods

such as random, sin, and round, and the primitive #rapper classes *nteger, Fouble etc have static methods for manipulating the primitives they #rap, such as returning the matching int value from the string /,/. Iar'ing a variable as static indicates that only one copy #ill exist per class. &his is in contrast #ith normal items #here for instance #ith an integer variable a copy belongs to each instance of a class. *in the follo#ing example of a non static int three instances of the int iIy al #ill exist and each instance can contain a different value.
)l -- 9y;l --{ *u3li) int i9yB l=0; } *u3li) )l -- Don,t t{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 9y;l -- m! = new 9y;l --(); m!.i9yB l=!; 9y;l -- m2 = new 9y;l --(); m2.i9yB l=2; 9y;l -- m% = new 9y;l --(); m%.i9yB l=>>; ''1hi- will out*ut ! - e )h in-t n)e of the )l -''h - it- own )o*y of the 6 lue i9yB l ,y-tem.out.*rintln(m!.i9yB l); }''=n7 of m in }

&he follo#ing example sho#s #hat happens #hen you have multiple instances of a class containing a static integer.
)l -- 9y;l --{ *u3li) -t ti) }''=n7 of 9y;l -int i9yB l=0;

*u3li) )l -- ,t t{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 9y;l -- m! = new 9y;l --(); m!.i9yB l=0; 9y;l -- m2 = new 9y;l --(); m2.i9yB l=!; 9y;l -- m% = new 9y;l --(); m2.i9yB l=>>; ''Ae) u-e i9yB l i- -t ti)$ there i- only one '')o*y of it no m tter how m ny in-t n)e''of the )l -- re )re te7 '1hi- )o7e will ''out*ut 6 lue of >> ,y-tem.out.*rintln(m!.i9yB l); }''=n7 of m in }

!ear in mind that you cannot access non static variables from #ithin a static method. &hus the follo#ing #ill cause a compile time error
*u3li) )l -- ,t{ int i; *u3li) -t ti) 6oi7 m in(,tring rg6[]){ i = i + 2;''(ill ) u-e )om*ile time error } }

A static method cannot be overriden to be non static in a child class


A static method cannot be overriden to be non static in a child class. Also a non static 6normal7 method cannot be overriden to be static in a child class. &here is no similar rule #ith reference to overloading. &he follo#ing code #ill cause an error as it attempts to override the class amethod to be nonDstatic.
)l -- A -e{ *u3li) -t ti) 6oi7 } } metho7(){

*u3li) )l -- Erimley eCten7- A -e{ *u3li) 6oi7 metho7(){}''; u-e}

)om*ile time error

&he *!I Ji'es compiler produces the follo#ing error


2oun7 ! -em nti) error )om*iling .Erimley." 6 .F 6. *u3li) 6oi7 metho7(){} <GGGGGGG? *** =rrorF 1he in-t n)e metho7 .6oi7 metho7();. metho7();.

) nnot o6erri7e the -t ti) metho7 .6oi7 7e)l re7 in ty*e .A -e.

Static methods cannot be overriden in a child class but they can be hidden#

*n one of my moc' exams * have a 4uestion that as's if static methods can be overriden. &he ans#er given is that static methods cannot be overriden, but that lead to a considerable number of emails from people giving examples #here it appears that static methods have been overriden. &he process of overriding involves more than simply replacing a method in a child class, it involves the runtime resolution of #hat method to call according to its reference type. "ere is an example of some code that appears to sho# overriding of static methods
)l -- A -e{ *u3li) -t ti) 6oi7 -t metho7(){ ,y-tem.out.*rintln(.A -e.); } } *u3li) )l -- 5t-06er eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 5t-06er -o = new 5t-06er(); -o.-t metho7(); } *u3li) -t ti) 6oi7 -t metho7(){ ,y-tem.out.*rintln(. metho7 in ,t 06er.); } } 1hi- )o7e will )om*ile n7 out*ut . metho7 in ,t 06er.

4ative
&he native modifier is used only for methods and indicates that the body of the code is #ritten in a language other than Java such as C or C++. 5ative methods are often #ritten for platform specific purposes such as accessing some item of hard#are that the Java irtual Iachine is not a#are of. Another reason is #here greater performance is re4uired. A native method ends #ith a semicolon rather than a code bloc'. &hus the follo#ing #ould call an external routine, #ritten perhaps in C++
*u3li) n ti6e 6oi7 f -t) l)();

Abstract
*t is easy to overloo' the abstract modifier and miss out on some of its implications. *t is the sort of modifier that the examiners li'e to as' tric'y 4uestions about. &he abstract modifier can be applied to classes and methods. When applied to a method it indicates that it #ill have no body 6ie no curly brace part7 and the code can only be run #hen implemented in a child class. "o#ever there are some restrictions on #hen and #here you can have abstract methods and rules on classes that contain them. A class must be declared as abstract if it has one or more abstract methods or if it inherits abstract methods for #hich it does not provide an implementation. &he other circumstance #hen a class must be declared abstract is if it implements an interface but does not provide implementations for every method of the interface. &his is a fairly unusual circumstance ho#ever.

5" a class has any abstract methods it must be declared abstract itsel"#
Fo not be distracted into thin'ing that an abstract class cannot have non abstract methods. Any class that descends from an abstract class must implement the abstract methods of the base class or declare them as abstract itself. &hese rules tend to beg the 4uestion #hy #ould you #ant to create abstract methodsE Abstract methods are mainly of benefit to class designers. &hey offer a class designer a #ay to create a prototype for methods that ought to be implemented, but the actual implementation is left to people #ho use the classes later on. "ere is an example of an abstract a class #ith an abstract method. Again note that the class itself is declared abstract, other#ise a compile time error #ould have occurred. &he follo#ing class is abstract and #ill compile correctly and print out the string
*u3li) 3-tr )t )l -- 3-tr{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ ,y-tem.out.*rintln(.hello in the } *u3li) 3-tr )t int metho7(); }

3-tr )t.);

6inal

&he final modifier can be applied to classes, methods and variables. *t has similar meanings related to inheritance that ma'e it fairly easy to remember. A final class may never be subclassed. Another #ay to thin' of this is that a final class cannot be a parent class. Any methods in a final class are automatically final. &his can be useful if you do not #ant other programmers to /mess #ith your code/. Another benefit is that of efficiency as the compiler has less #or' to do #ith a final method. &his is covered #ell in olume + of Core Java. &he final modifier indicates that a method cannot be overridden. &hus if you create a method in a sub class #ith exactly the same signature you #ill get a compile time error. &he follo#ing code illustrates the use of the final modifier #ith a class. &his code #ill print out the string /amethod/
fin l )l -- A -e{ *u3li) 6oi7 metho7(){ ,y-tem.out.*rintln(. metho7.); } } *u3li) )l -- 2in{ *u3li) -t ti) 6oi7 m in(,tring A -e 3 = new A -e(); 3. metho7(); } } rg6[]){

A final variable cannot have itHs value changed and must be set at creation time. &his is similar to the idea of a constant in other languages.

Synchroni$ed
&he synchroni,ed 'ey#ord is used to prevent more than one thread from accessing a bloc' of code at a time. )ee section < on threads to understand more on ho# this #or's.

'ransient
&he transient 'ey#ord is one of the less fre4uently used modifiers. *t indicates that a variable should not be #ritten out #hen a class is serialized.

%olatile
3ou probably #ill not get a 4uestion on the volatile 'ey#ord. &he #orst you #ill get it is recognising that it actually is a Java 'ey#ord. According to !arry !oone it tells the compiler a variable may change asynchronously due to threads

Accept that it is part of the language and then get on #orrying about something else

7sing modi"iers in combination


&he visibility modifiers cannot be used in combination, thus a variable cannot be both private and public, public and protected or protected and private. 3ou can of course have combinations of the visibility modifiers and the modifiers mentioned in my so forth list native transient synchronized volatile &hus you can have a public static native method.

/here modi"iers can be used

1odi"ier public private protected abstract final transient native

1ethod yes yes yes yes yes no yes

%ariable yes yes yes no yes yes no

class yes yes 6nested7 yes6nested7 yes yes no no

volatile

no

yes

no

(uestions

(uestion 1)
What #ill happen #hen you attempt to compile and run this codeE
3-tr )t )l -- A -e{ 3-tr )t *u3li) 6oi7 myfun)(); *u3li) 6oi7 nother(){ ,y-tem.out.*rintln(.4nother metho7.); }

*u3li) )l -- 43- eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring 43= new 43-(); . metho7(); }

rg6[]){

*u3li) 6oi7 myfun)(){ ,y-tem.out.*rintln(.9y fun).); } *u3li) 6oi7 metho7(){ myfun)(); }

+7 &he code #ill compile and run, printing out the #ords /Iy Lunc/ ,7 &he compiler #ill complain that the !ase class has non abstract methods -7 &he code #ill compile but complain at run time that the !ase class has non abstract methods @7 &he compiler #ill complain that the method myfunc in the base class has no body, nobody at all to looove it

(uestion *)
What #ill happen #hen you attempt to compile and run this codeE
*u3li) )l -- 9y9 in{ *u3li) -t ti) 6oi7 m in(,tring rg6){ ,y-tem.out.*rintln(.<ello )ruel worl7.); } }

+7 &he compiler #ill complain that main is a reserved #ord and cannot be used for a class ,7 &he code #ill compile and #hen run #ill print out /"ello cruel #orld/ -7 &he code #ill compile but #ill complain at run time that no constructor is defined @7 &he code #ill compile but #ill complain at run time that main is not correctly defined

(uestion +)
Which of the follo#ing are Java modifiersE +7 public ,7 private -7 friendly @7 transient

(uestion ,)
What #ill happen #hen you attempt to compile and run this codeE
)l -- A -e{ 3-tr )t *u3li) 6oi7 myfun)(); *u3li) 6oi7 nother(){ ,y-tem.out.*rintln(.4nother metho7.); } } *u3li) )l -- 43- eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring 43= new 43-(); . metho7(); } rg6[]){

*u3li) 6oi7 myfun)(){ ,y-tem.out.*rintln(.9y fun).);

} *u3li) 6oi7 myfun)(); } }

metho7(){

+7 &he code #ill compile and run, printing out the #ords /Iy Lunc/ ,7 &he compiler #ill complain that the !ase class is not declared as abstract. -7 &he code #ill compile but complain at run time that the !ase class has non abstract methods @7 &he compiler #ill complain that the method myfunc in the base class has no body, nobody at all to looove it

(uestion -)
Why might you define a method as nativeE +7 &o get to access hard#are that Java does not 'no# about ,7 &o define a ne# data type such as an unsigned integer -7 &o #rite optimised code for performance in a language such as C/C++ @7 &o overcome the limitation of the private scope of a method

(uestion .)
What #ill happen #hen you attempt to compile and run this codeE
)l -- A -e{ *u3li) fin l 6oi7 metho7(){ ,y-tem.out.*rintln(. metho7.); } } *u3li) )l -- 2in eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring A -e 3 = new A -e(); 3. metho7(); } } rg6[]){

+7 Compile time error indicating that a class #ith any final methods must be declared final itself ,7 Compile time error indicating that you cannot inherit from a class #ith final methods

-7 Mun time error indicating that !ase is not defined as final @7 )uccess in compilation and output of /amethod/ at run time.

(uestion 8)
What #ill happen #hen you attempt to compile and run this codeE
*u3li) )l -- 9o7{ *u3li) -t ti) 6oi7 m in(,tring } } rg6[]){ metho7();

*u3li) -t ti) n ti6e 6oi7

+7 1rror at compilation: native method cannot be static ,7 1rror at compilation native method must return value -7 Compilation but error at run time unless you have made code containing native amethod available @7 Compilation and execution #ithout error

(uestion 9)
What #ill happen #hen you attempt to compile and run this codeE
*ri6 te )l -- A -e{} *u3li) )l -- Bi-{ tr n-ient int iB l; *u3li) -t ti) 6oi7 m in(,tring ele*h nt[]){ }

+7 Compile time error: !ase cannot be private ,7 Compile time error indicating that an integer cannot be transient -7 Compile time error transient not a data type @7 Compile time error malformed main method

(uestion :)
What happens #hen you attempt to compile and run these t#o files in the same directoryE
''2ile 8!." 6 * )# ge 9y8 )# ge; )l -- 8!{ 6oi7 f n)ymetho7(){ ,y-tem.out.*rintln(.(h t } } ''2ile 82." 6 *u3li) )l -- 82 eCten7- 8!{ f n)ymetho7(); }

f n)y metho7.);

+7 !oth compile and G, outputs /What a fancy method/ #hen run ,7 5either #ill compile -7 !oth compile but G, has an error at run time @7 G+ compiles cleanly but G, has an error at compile time

(uestion 1;)
Which of the follo#ing are legal declarationsE +7 public protected amethod6int i7 ,7 public void amethod6int i7 -7 public void amethod6void7 @7 void public amethod6int i7

Answers

Answer 1)
+7 &he code #ill compile and run, printing out the #ords /Iy Lunc/ An abstract class can have non abstract methods, but any class that extends it must implement all of the abstract methods.

Answer *)
@7 &he code #ill compile but #ill complain at run time that main is not correctly defined &he signature of main has a parameter of )tring rather than string array

Answer +)
+7 public ,7 private @7 transient Although some texts use the #ord friendly #hen referring to visibility it is not a Java reserved #ord. 5ote that the exam #ill almost certainly contain 4uestions that as' you to identify Java 'ey#ords from a list

Answer ,)
,7 &he compiler #ill complain that the !ase class is not declared as abstract. &he actual error message using my JFN +.+ compiler #as
43-." 6 F!F )l -- A -e mu-t 3e 7e)l re7 5t 7oe- not 7efine 6oi7 myfun) () from )l -- A -e. )l -- A -e{ H ! error 3-tr )t.

Answer -)
+7 &o get to access hard#are that Java does not 'no# about -7 &o #rite optimised code for performance in a language such as C/C++ Although the creation of /Gure Java/ code is highly desirable, particularly to allo# for platform independence, it should not be a religion, and there are times #hen native code is re4uired.

Answer .)

@7 )uccess in compilation and output of /amethod/ at run time. &his code calls the version of amethod in the !ase class. *f you #ere to attempt to implement an overridden version of amethod in Lin you #ould get a compile time error.

Answer 8)
@7 Compilation and execution #ithout error &here is no call to the native method and so no error occurs at run time

Answer 9)
+7 Compile time error: !ase cannot be private A top level class such as base cannot be declared to be private.

Answer :)
@7 G+ compiles cleanly but G, has an error at compile time 1ven though G, is in the same directory as G+, because G+ #as declared #ith the pac'age statement it is not visible from G,

Answer 1;)
,7 public void amethod6int i7 *f you thought that option - #as legal #ith a parameter argument of void you may have to empty some of the C/C++ out of your head. 0ption @7 is not legal because method return type must come immediately before the method name.

Objective +, 'he de"ault constructor


Lor a given class, determine if a default constructor #ill be created and if so state the prototype of that constructor.

4ote on this objective


!his is a neat small ob$ective that concentrates on an easily overloo"ed aspect of the -ava language

/hat is a constructor0
3ou need to understand the concept of a constructor to understand this ob(ective. !riefly, it is special type of method that runs automatically #hen an class is instantiated. Constructors are often used to initialise values in the class. Constructors have the same name as the class and no return value. 3ou may get 4uestions in the exam that have methods #ith the same name as the class but a return type, such as int or string. !e careful and ensure that any method you assume is a constructor does not have a return type.

5" a method has the same name as the class it is in, but also has a return ty!e it is not a constructor#

"ere is an example of a class #ith a constructor that prints out the string /Oreetings from Cro#le/ #hen an instance of the class is created.
*u3li) )l -- ;rowle{ *u3li) -t ti) 6oi7 m in(,tring ;rowle ) = new ;rowle(); } rg6[]){

;rowle(){ ,y-tem.out.*rintln(.Ereeting- from ;rowle.); }

/hen does Java su!!ly the de"ault constructor0


*f you do not specifically define any constructors, the compiler inserts an invisible zero parameter constructor /behind the scenes/. 0ften this is of only theoretical importance, but the important 4ualification is that you only get a default zero parameter constructor if you do not create any of your o#n.

5" you create constructors o" your own, Java does not su!!ly the de"ault $ero !arameter constructor

As soon as you create any constructors of your o#n you loose the default no parameter constructor. *f you then try to create an instance of the class #ithout passing any parameters 6i.e. invo'ing the class #ith a zero parameter constructor7, you #ill get an error. &hus as soon as you create any constructors for a class you need to create a zero parameter constructor. &his is one of the reasons that code generators li'e !orland/*nprise J!uilder create a zero parameter constructor #hen they generate a class s'eleton. &he follo#ing example illustrates code that #ill not compile. When the compiler chec's to create the instance of the !ase class called c it inserts a call to the zero parameter constructor. !ecause Base has an integer constructor the zero parameter constructor is not available and a compile time error occurs. &his can be fixed by creating a /do nothing/ zero parameter constructor in the class Base.
''( rningF will not )om*ile. )l -- A -e{ A -e(int i){ ,y-tem.out.*rintln(.-ingle int )on-tru)tor.); } } *u3li) )l -- ;on- { *u3li) -t ti) 6oi7 m in(,tring A -e ) = new A -e(); } } rg6[]){

''1hi- will )om*ile )l -- A -e{ A -e(int i){ ,y-tem.out.*rintln(.-ingle int )on-tru)tor.); } A -e(){} } *u3li) )l -- ;on- { *u3li) -t ti) 6oi7 m in(,tring A -e ) = new A -e(); } } rg6[]){

'he !rototy!e o" the de"ault constructor


&he ob(ective as's you to be a#are of the prototype of the default constructor. 5aturally it must have no parameters. &he most obvious default is to have no scope specifier, but you could define the constructor as public or protected. .onstructors cannot be native+ abstract+ static+ synchroni,ed or final#

&hat piece of information #as derived directly from a compiler error message. *t seems that the 4uality of the error messages is improving #ith the ne# releases of Java. * have heard that the ne# *!I Java compilers have good error reporting. 3ou might be #ell advised to have more than one version of the Java compiler available to chec' your code and hunt do#n errors.

(uestions

(uestion 1)
Oiven the follo#ing class definition
)l -- A -e{ A -e(int i){} } )l -- Ief;on eCten7- A -e{ Ief;on(int i){ ''JJ } }

Which of the follo#ing lines #ould be legal individually if added at the line mar'ed //??E +7 super678 ,7 this678 -7 this6KK78 @7super6KK78

(uestion *)
Oiven the follo#ing class
*u3li) )l -- ;rowle{ *u3li) -t ti) 6oi7 m in(,tring ;rowle ) = new ;rowle(); } ;rowle(){ rg6[]){

,y-tem.out.*rintln(.Ereeting- from ;rowle.); } } (h t i- the 7 t ty*e returne7 3y the )on-tru)torK

+7 null ,7 integer -7 )tring @7 no datatype is returned

(uestion +)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
*u3li) )l -- ;rowle{ *u3li) -t ti) 6oi7 m in(,tring ;rowle ) = new ;rowle(); } rg6[]){

6oi7 ;rowle(){ ,y-tem.out.*rintln(.Ereeting- from ;rowle.); } }

+7 Compilation and output of the string /Oreetings from Cro#le/ ,7 Compile time error, constructors may not have a return type -7 Compilation and output of string /void/ @7 Compilation and no output at runtime

(uestion ,)
What #ill happen #hen you attempt to compile and run the follo#ing classE
)l -- A -e{ A -e(int i){ ,y-tem.out.*rintln(.A -e.); }

} )l -- ,e6ern eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ ,e6ern - = new ,e6ern(); }

6oi7 ,e6ern(){ ,y-tem.out.*rintln(.,e6ern.); }

+7 Compilation and output of the string /)evern/ at runtime ,7 Compile time error -7 Compilation and no output at runtime @7 Compilation and output of the string /!ase/

(uestion -)
Which of the follo#ing statements are trueE +7 &he default constructor has a return type of void ,7 &he default constructor ta'es a parameter of void -7 &he default constructor ta'es no parameters @7 &he default constructor is not created if the class has any constructors of its o#n.

Answers

Answer to (uestion 1)
@7 super6KK78 !ecause the class !ase has a constructor defined the compiler #ill not insert the default zero argument constructor. &herefore calls to super() #ill cause an error. A call to this() is an attempt to call a non existent zero argument constructor in the current class. &he call to this(//) causes a circular reference and #ill cause a compile time error.

Answer to (uestion *)
@7 no datatype is returned *t should be fairly obvious that no datatype is returned as by definition constructors do not have datatypes.

Answer to (uestion +)

@7 Compilation and no output at runtime !ecause the method Cro#le has a return type it is not a constructor. &herefore the class #ill compile and at runtime the method Cro#le is not called.

Answer to (uestion ,)
,7 Compile time error An error occurs #hen the class )evern attempts to call the zero parameter constructor in the class Base

Answer to (uestion -)
-7 &he default constructor ta'es no parameters @7 &he default constructor is not created if the class has any constructors of its o#n. 0ption + is fairly obviously #rong as constructors never have a return type. 0ption , is very dubious as #ell as Java does not offer void as a type for a method or constructor.

Objective ,, Overloading and overriding


)tate the legal return types for any method given the declarations of all related methods in this or parent classes.

4ote on this objective


!his seems to be a rather obscurely phrased ob$ective# It appears to be as"ing you to understand the difference between overloading and overriding# &o appreciate this ob(ective you need a basic understanding of overloading and overriding of methods. &his is covered in )ection P: 0verloading 0verriding Muntime &ype and 0b(ect 0rientation

1ethods in the same class


!y related methods * assume that the ob(ective means a method #ith the same name. *f t#o or more methods in the same class have the same name, the method is said to be overloaded. 3ou can have t#o methods in a class #ith the same name but they must have different parameter types and order. *t is the parameter order and types that distinguish bet#een any t#o versions of

overloaded method. &he return type does not contribute to#ards distinguishing bet#een methods. &he follo#ing code #ill generate an error at compile time, the compiler sees amethod as an attempt to define the same method t#ice. *t causes an error that #ill say something li'e
metho7 re7efine7 with 7ifferent return ty*eF 6oi7 w - int metho7(int) )l -- , me{ *u3li) -t ti) 6oi7 m in(,tring 06er o = new 06er(); int iA -e=0; o. metho7(iA -e); } metho7(int)

rg6[]){

''1he-e two ) u-e )om*ile time error *u3li) 6oi7 metho7(int i06er){ ,y-tem.out.*rintln(.06er. metho7.); } *u3li) int metho7(int i06er){ ,y-tem.out.*rintln(.06er int return metho7.); return 0; } }

'he return data ty!e does not contribute towards distinguishing between one method and another#

1ethods in a sub class


3ou can overload a method in a sub class. All that it re4uires is that the ne# version has a different parameter order and type. &he parameter names are not ta'en into account or the return type. *f you are going to override a method, ie completely replace its functionality in a sub class, the overriding version of the method must have exactly the same signature as the version in the base class it is replacing. &his includes the return type. *f you create a method in a sub class #ith the same name and signature but a different return type you #ill get the same error message as in the previous example. i.e.

metho7 w - int

re7efine7 with 7ifferent return ty*eF 6oi7 metho7(int)

metho7(int)

&he compiler sees it as a faulty attempt to overload the method rather than override it.)tatic methods cannot be overriden *f you consider overriding the simple replacement of a method ina child class it is easy to believe at static methods can be overriden. *ndeed * have had many emails from people that include code that appears to illustrate ho# static methods can be overriden. "o#ever this does not ta'e into account the more subtle aspect of overriding #hich is the runtime resolution of #hich version a method #ill be called. &he follo#ing code appears to illustrate ho# static methods can be overriden.
)l -- A -e{ -t ti) 6oi7 metho7(){ ,y-tem.out.*rintln(.A -e. metho7.); } } *u3li) )l -- ;r 6engi3 eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring rg[]){ ;r 6engi3 )g = new ;r 6engi3(); )g. metho7(); } -t ti) 6oi7 metho7(){ ,y-tem.out.*rintln(.;r 6engi3. metho7.); } }

*f you compile and run this code you #ill find it outputs the text Cravengib.amethod, #hich appears to be a nice illustration of overriding. "o#ever there is more to overriding than simple replacement of one method by another in a child class. &here is also the issue of runtime resolution of methods based on the class type of the reference. and this can be illustrated by ma'ing the type of the reference 6the part on the left hand side of the instance initialisation7 to the type of the class that is being instantiated. *n the previous example, because the method called amethod is associated #ith the class, and not #ith any particular instance of the class it does not matter #hat the type of class being created it, (ust the type of the reference.. &hus if you change the line before the callng of amethod to read !ase cgQ ne# Cravengib67 3ou #ill find that #hen you run the program you get an output of !ase.amethod

&he reference cg is a reference 6or pointer7 of type !ase to an instance in memory of the class Cravengib. When a call is made to a static method, the J I does not chec' to see #hat the type is that is being pointed to i,t (ust calls the one instance of the method that is associated #ith the !ase class. !y contrast #hen a method is overriden the J I chec's the type of the class that is being pointed to by the reference and calls the method associated #ith that type. &o complete the illustration, if you change both versions of amethod to be non static, 'eep the creation of the class to !ase cgQ ne# Cravengib67 compile and run the code, and you #ill find that amethod has been overriden and the output #ill be Cravengib.amethod

(uestions

(uestion 1)
Oiven the follo#ing class definition
*u3li) )l -- L*ton{ *u3li) -t ti) 6oi7 m in(,tring } *u3li) 6oi7 ''<ere rg6[]){

metho7(int i){}

Which of the follo#ing #ould be legal to place after the comment //"ere E +7 public int amethod6int z7RS ,7 public int amethod6int i,int (7Rreturn KK8S -7 protected void amethod6long l7R S @7 private void anothermethod67RS

(uestion *)

Oiven the follo#ing class definition


)l -- A -e{ *u3li) 6oi7 metho7(){ ,y-tem.out.*rintln(.A -e.); } } *u3li) )l -- < y eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring < y h = new < y(); h. metho7(); } } rg6[]){

Which of the follo#ing methods in class "ay #ould compile and cause the program to print out the string /"ay/ +7 public int amethod67R )ystem.out.println6/"ay/78S ,7 public void amethod6long l7R )ystem.out.println6/"ay/78S -7 public void amethod67R )ystem.out.println6/"ay/78S @7 public void amethod6void7R )ystem.out.println6/"ay/78S

(uestion +)
Oiven the follo#ing class definition
*u3li) )l -- ,hru3<ill{ *u3li) 6oi7 foreg te(,tring -D me){} ''<ere } (hi)h of the following metho7- )oul7 3e leg lly *l )e7 imme7i tely fter the )omment ''<ere

+7 public int foregate6)tring s5ame7RS ,7 public void foregate6)tring!uffer s5ame7RS -7 public void foreOate6)tring s5ame7RS @7 private void foregate6)tring s&ype7RS Answers

Answer to (uestion 1)
,7 public int amethod6int i, int (7 Rreturn KK8S -7 protected void amethod 6long l7RS @7 private void anothermethod67RS

0ption + #ill not compile on t#o counts. 0ne is the obvious one that it claims to return an integer. &he other is that it is effectively an attempt to redefine a method #ithin the same class. &he change of name of the parameter from i to z has no effect and a method cannot be overridden #ithin the same class.

Answer to (uestion *)
-7 public void amethod67R )ystem.out.println6/"ay/78S 0ption - represents an overriding of the method in the base class, so any zero parameter calls #ill invo'e this version. 0ption + #ill return an error indicating you are attempting to redefine a method #ith a different return type. Although option , #ill compile the call to amethod67 invo'e the !ase class method and the string /!ase/ #ill be output. 0ption @ #as designed to catch out those #ith a head full of C/C++, there is no such thing as a void method parameter in Java.

Answer to (uestion +)
,7 public void foregate6)tring!uffer s5ame7RS -7 public void foreOate6)tring s5ame7RS 0ption + is an attempt to redefine a method t#ice, the fact that it has an int return type does not contribute to distinguish it from the existing foregate method. Changing the name of a method parameter as in option @, does not distinguish it from the existing method. 5ote that in option , foreOate has a capital O in it.

Chapter 2) Flow control and exception Handling

Objective 1, 'he i" and switch statements


Write code using if and switch statements and identify legal argument types for these statements.

5"/else statements
If0else constructs in Java are (ust as you might expect from other languages. switch0case statements have a fe# peculiarities. &he syntax for the if0else statement is
if(3oole n )on7ition){ ''the 3oole n w - true -o 7o thi}el-e { ''7o -omething el-e

Java does not have a /then/ 'ey#ord li'e the one in isual !asic. &he curly braces are a general indicator in Java of a compound statement that allo#s you to execute multiple lines of code as a result of some test. &his is 'no#n as a bloc" of code. &he else portion is al#ays optional. 3ou can chain multiple if/else statements as follo#s 6though after a couple you might #ant to consider the case construct instead7.
int i=!; if(i==!){ ''-ome )o7e } el-e if (i==2){ ''-ome )o7e } el-e{ ''-ome )o7e }

0ne idiosyncrasy of the Java if statement is that it must ta'e a boolean value. 3ou cannot use the C/C++ convention of any non zero value to represent true and 2 for false. &hus in Java the follo#ing #ill simply not compile
int # =G!; if(#){''(ill not )om*ile+ ,y-tem.out.*rintln(.7o -omething.); }

because you must explicitly ma'e the test of ' return a boolean value, as in the follo#ing example
if(# == G!){ ,y-tem.out.*rintln(.7o -omething.); '';om*ile- 0M+ }

As in C/C++ you can miss out the curly brac'ets thus


3oole n #=true; if(#) ,y-tem.out.*rintln(.7o -omething.);

&his is sometimes considered bad style, because if you modify the code later to include additional statements they #ill be outside of the conditional bloc'. &hus

if(#)

,y-tem.out.*rintln(.7o -omething.); ,y-tem.out.*rintln(. l-o 7o thi-.);

&he second output #ill al#ays execute.

Switch statements
Geter van der 9indens opinion of the s#itch statement is summed up #hen he says

<death to the switch statement<


&hus this is a sub(ect you should pay extra attention to. &he argument to a s#itch statement must be a byte+ char+ short or int. 3ou might get an exam 4uestion that uses a float or long as the argument to a switch statement.. A fairly common 4uestion seems to be about the use of the brea" statement in the process of falling through a switch statement. "ere is an example of this type of 4uestion.
int #=!0; -wit)h(#){ ) -e !0F ) -e 20F } ,y-tem.out.*rintln(.ten.); ,y-tem.out.*rintln(.twenty.);

Common sense #ould indicate that after executing the instructions follo#ing a case statement, and having come across another case statement the compiler #ould then finish falling through the switch statement. "o#ever, for reasons best 'no#n to the designers of the language case statements only stop falling through #hen they come across a brea" statement. As a result, in the above example both the strings ten and t#enty #ill be sent to the output. Another little peculiarity that can come up on 4uestions is the placing of the default statement.

'he de"ault clause does not need to come at the end o" a case statement

&he conventional place for the default statement is at the end of of case options. &hus normally code #ill be #ritten as follo#s
int #=!0; -wit)h(#){ ) -e !0F ) -e 20F 7ef ultF }

,y-tem.out.*rintln(.ten.); 3re #; ,y-tem.out.*rintln(.twenty.); 3re #; ,y-tem.out.*rintln(.1hi- i- the 7ef ult out*ut.);

&his approach mirrors the #ay most people thin'. 0nce you have tried the other possibilities, you perform the default output. "o#ever, it is syntactically correct, if not advisable, to code a s#itch statement #ith the default at the top
int #=!0; -wit)h(#){ 7ef ultF ''8ut the 7ef ult t the 3ottom$ not here ,y-tem.out.*rintln(.1hi- i- the 7ef ult out*ut.); 3re #; ) -e !0F ,y-tem.out.*rintln(.ten.); 3re #; ) -e 20F ,y-tem.out.*rintln(.twenty.); 3re #; }

=egal arguments "or if and switch statements


As mentioned previously an if statement can only ta'e a boolean type and a switch can only ta'e a byte, char+ short or int#

'he ternary 0 o!erator


)ome programmers claim that the ternary operator is useful. * do not consider it so. *t is not specifically mentioned in the ob(ectives so please let me 'no# if it does come up in the exam.

Other "low control statements


Although the published ob(ectives only mention the if0else and case statements the exam may also cover the do0while and the while loop.

2>ercises# 2>ercise 1
Create a file #ith a public class called *f1lse. Create a method called go that ta'es the args )tring array from the main method. *n that method create an if/else bloc' that loo's at the first element of the array and uses the )tring e4uals method to determine the output. *f it contains BtrueC print out Bo'C and if false output B5ot 0'C, if it contains a string other than true or false print out B*nvalid command parameterC. .se a single se4uence of if/else if/else statements.

2>ercise *
Iodify the *f1lse class so that an if statement chec's to see if the )tring array passed to the go method has a length of zero using the array length field. *f the length is zero output the string B5o parameter suppliedC. Glace the existing if/else if/else bloc' #ithin the else bloc' of this test, so it acts as in the original version.

Suggested Solution to 2>ercise 1


*u3li) )l -- 5f=l-e{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 5f=l-e ie = new 5f=l-e(); ie.go( rg6); } *u3li) 6oi7 go(,tring[] - ){ ,tring - = - [0]; if(-.eNu l-(.true.)){ ,y-tem.out.*rintln(.0M.); }el-e if(-.eNu l-(.f l-e.)){ ,y-tem.out.*rintln(.Dot 0M.); }el-e{ ,y-tem.out.*rintln(.5n6 li7 )omm n7 * r meter.); } } }

Suggested Solution to 2>ercise *


*u3li) )l -- 5f=l-e{ *u3li) -t ti) 6oi7 m in(,tring 5f=l-e ie = new 5f=l-e(); ie.go( rg6); } rg6[]){

*u3li) 6oi7 go(,tring[] - ){ if(- .length ==0){ ,y-tem.out.*rintln(.Do * r meter -u**lie7.); }el-e{ ,tring - = - [0]; if(-.eNu l-(.true.)){ ,y-tem.out.*rintln(.0M.); }el-e if(-.eNu l-(.f l-e.)){ ,y-tem.out.*rintln(.Dot 0M.); }el-e{ ,y-tem.out.*rintln(.5n6 li7 )omm n7 * r meter.); } } } }

(uestions

(uestion 1)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
*u3li) )l -- 9y5f{ 3oole n 3; *u3li) -t ti) 6oi7 m in(,tring 9y5f mi = new 9y5f(); } 9y5f(){

rg6[]){

} }

if(3){ ,y-tem.out.*rintln(.1he 6 lue of 3 w - true.); } el-e{ ,y-tem.out.*rintln(.1he 6 lue of 3 w - f l-e.); }

+7 Compile time error variable b #as not initialised ,7 Compile time error the parameter to the if operator must evaluate to a boolean -7 Compile time error, cannot simultaneously create and assign value for boolean value @7 Compilation and run #ith output of false

(uestion *)
What #ill happen #hen you attempt to compile and run this codeE
*u3li) )l -- 9y5f{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 9y5f mi = new 9y5f(); } 9y5f(){ 3oole n 3 = f l-e; if(3=f l-e){ ,y-tem.out.*rintln(.1he 6 lue of 3 i-.+3); } } }

+7 Mun time error, a boolean cannot be appended using the + operator ,7 Compile time error the parameter to the if operator must evaluate to a boolean -7 Compile time error, cannot simultaneously create and assign value for boolean value @7 Compilation and run #ith no output

(uestion +)
What #ill happen #hen you attempt to compile and run this codeE
*u3li) )l -- 9y,wit)h{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 9y,wit)h m-= new 9y,wit)h(); m-. metho7(); } *u3li) 6oi7 metho7(){ )h r #=!0; -wit)h(#){ 7ef ultF ,y-tem.out.*rintln(.1hi- i- the 7ef ult out*ut.); 3re #; ) -e !0F ,y-tem.out.*rintln(.ten.); 3re #; ) -e 20F ,y-tem.out.*rintln(.twenty.); 3re #; } } }

+7 5one of these options ,7 Compile time error target of s#itch must be an integral type -7 Compile and run #ith output /&his is the default output/ @7 Compile and run #ith output /ten/

(uestion ,)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
*u3li) )l -- 9y,wit)h{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ 9y,wit)h m-= new 9y,wit)h(); m-. metho7(); } *u3li) 6oi7 metho7(){ int #=!0; -wit)h(#){ 7ef ultF ''8ut the 7ef ult t the 3ottom$ not here ,y-tem.out.*rintln(.1hi- i- the 7ef ult out*ut.); 3re #; ) -e !0F ,y-tem.out.*rintln(.ten.); ) -e 20F ,y-tem.out.*rintln(.twenty.); 3re #; } } }

+7 5one of these options ,7 Compile time error target of s#itch must be an integral type -7 Compile and run #ith output /&his is the default output/ @7 Compile and run #ith output /ten/

(uestion -)
Which of the follo#ing could be used as the parameter for a s#itch statementE +7 byte bQ+8 ,7 int iQ+8 -7 boolean bQfalse8 @7 char cQHcH8 Answers

Answer 1)
@7 Compilation and run #ith output of false !ecause the boolean b #as created at the class level it did not need to be explicitly initialised and instead too' the default value of a boolean #hich is false. An if statement must evaluate to a boolean value and thus b meets this criterion.

Answer *)
@7 Compilation and run #ith no output !ecause b is a boolean there #as no error caused by the if statement. *f b #as of any other data type an error #ould have occurred as you attempted to perform an assignment instead of a comparison. &he expression
if(3=f l-e)

#ould normally represent a programmer error. 0ften the programmer #ould have meant to say
if (3==f l-e)

*f the type of b had been anything but boolean a compile time error #ould have resulted. &he re4uirement for the if expression is that it return a boolean and because
(3=f l-e )

does return a boolean it is acceptable 6if useless7.

Answer +)
@7 Compile and run #ith output /ten/

Answer ,)
+7 5one of these options !ecause of the lac' of a brea' statement after the
3re # !0;

statement the actual output #ill be /ten/ follo#ed by /t#enty/

Answer -)
+7 byte bQ+8 ,7 int iQ+8 @7 char cQHcH8 A s#itch statement can ta'e a parameter of byte, char, short or int.

Objective *, loo!ing, brea and continue


Write code using all forms of loops including labeled and unlabeled use of brea' and continue and state the values ta'en by loop counter variables during and after loop execution.

'he for statement


&he most common method of looping is to use the for statement.3ou can get an idea of the value of the for statement in that many other languages have a very similar construct. Lor example C/C++ and perl have a for construct. Iany programmers use the for construct for most looping re4uirements as it is compact, self contained, easy to understand and hard to mess up. 9i'e C++ and unli'e C, the variable that controls the looping can be created and initialised from #ithin the for statement. &hus
*u3li) )l -- 9yOoo*{ *u3li) -t ti) 6oi7 m in(,tring 9yOoo* ml = new 9yOoo*(); ml. metho7(); } rg6[]){

*u3li) 6oi7 metho7(){ for(int M=0;M<5l;M++){ ,y-tem.out.*rintln(.0uter .+M); for(int O=0;O<5;O++) {,y-tem.out.*rintln(.5nner .+O);} } }

&his code #ill loop > times around the inner loop for every time around the outer loop. &hus the output #ill read
0uter 5nner 5nner 5nner 5nner inner 0uter 5nner 5nner 0; 0 ! 2 % & !; 0 2

etc etc &he for statement is the e4uivalent of a for0next loop in isual !asic. 3ou may consider the syntax to be
for(initi li: tion; )on7ition l eC*re--ion;in)rement)

&he conditional expression must be a boolean test in a similar #ay to an if statement. *n the code example above the for statement #as follo#ed by a code bloc' mar'ed by curly braces. *n the same #ay that an if statement does not demand a bloc' you can have a for statement that simply drives the follo#ing line thus
for(int i=0;i<5;i++) ,y-tem.out.*rintln(i);

5ote that in neither versions do you terminate the for line #ith a semi colon. *f you do, the for loop #ill (ust spin around until the condition is met and then the program #ill continue in a /straight line/. 3ou do not have to create the initialisation variable 6in this case7 #ithin the for loop, but if you do it means the variable #ill go out of scope as soon as you exit the loop. &his can be considered an advantage in terms of 'eeping the scope of variables as small as possible. *t is syntactically correct to create an empty for bloc' that #ill loop forever thus
for(;;){ } ,y-tem.out.*rintln(.fore6er.);

*t is more compact ho#ever to use a #hile6true7 construct thus


while(true){ ,y-tem.out.*rintln(.true.); }

'he while loo!s and do loo!s, nothing une>!ected


&he while and do loops perform much as you #ould expect from the e4uivalent in other languages. &hus a while #ill perform zero or more times according to a test and the do #ill perform one or more times. Lor a while loop the syntax is
while()on7ition){ 3o7y0fOoo*; }

&he condition is a boolean test (ust li'e #ith an if statement. Again you cannot use the C/C++ convention of 2 for true or any other value for false )o you might create a while loop as follo#s
while(i<&){ i++; ,y-tem.out.*rintln(.Ooo* 6 lue i- F.i); }

5ote that if the variable i #as @ or more #hen you reached the #hile statement #ould not result in any output. !y contrast a do loop #ill al#ays execute once. &hus #ith the follo#ing code you #ill al#ays get at least one set of output #hatever the value of the variable i on entering the loop.
7o{ ,y-tem.out.*rintln(.6 lue of F .+i); } while (i <&);

Iany programmers try to use the for loop instead of do while loop as it can concentrate the creation initialisation, test and incrementation of a counter all on one line.

'he goto statement, science or religion0


&he designers of Java decided that they agreed #ith programming guru 1dsger Fi('stra #ho #rote a famous article titled /Ooto considered harmful/. !ecause indiscriminate use of goto statements can result in hard to maintain spaghetti code it has fallen out of use and considered bad programming style. &he expression /spaggetti code/ refers to code #here it is hard to tell #here the logic starts and ends. &he goto statement is sometimes 'no#n as an /unconditional (ump/, ie it is possible to #rite code that (umps from one part of a program to another #ithout even performing a test. &here are situations #hen it #ould be useful and to help in those situations Java offers the labeled and unlabeled versions of the brea" and continue 'ey#ords.
*u3li) )l -- Ar{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ Ar 3 = new Ar(); 3. metho7(); } *u3li) 6oi7 metho7(){ for(int i=0;i <%;i ++){ ,y-tem.out.*rintln(.i.+i+.Pn.); outerF''<==8oint of thi- eC m*le if(i?2){ 3re # outer;''<==8oint of thi- eC m*le }''=n7 of if

for(int "=0; " <& QQ i<%; "++){ ,y-tem.out.*rintln(.".+"); }''=n7 of for }''=n7 of for }''en7 of Ar metho7

3ou then have to pic' out #hich combination of letters are output by the code. !y the #ay the code /Tn/ means to output a blan' line.

Jum! to a label
*t is often desirable to (ump from an inner loop to an outer loop according to some condition. 3ou can do this #ith the use of the labeled brea" and continue statement. A label is simply a non 'ey #ord #ith a colon placed after it. !y placing the name of the label after brea" or continue your code #ill (ump to the label. &his is handy for ma'ing part of a loop conditional. 3ou could of course do this #ith an if statement but a brea" statement can be convenient. According to 1lliotte Musty "arold, a distinguished Java author, B&here are only seven uses of continue in the entire Java +.2.+ source code for the (ava pac'ages.C &his means you are unli'ely to get much practice #ith it in your real #orld programming and thus you should place emphasis in learning it #ell for the exam. &he creators of the exam 4uestions seem to love creating convoluted netsted loops #ith brea's and continue statements that you #ould probably never encounter in good 4uality real code.

'he brea statement abandons !rocessing o" the current loo! entirely, the continue statement only abandons the currently !rocessing time around the loo!#

&a'e the follo#ing example


*u3li) )l -- O 3Ooo*{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ O 3Ooo* ml = new O 3Ooo*(); ml. metho7(); } *u3li) 6oi7 metho7(){ outerF for(int i=0;i<2;i++){ for(int "=0;"<%;"++){ if("?!) ''1ry thi- with 3re # in-te 7 of )ontinue )ontinue outer; ,y-tem.out.*rintln(.i .+ i + . " .+"); }

}''=n7 of outer for ,y-tem.out.*rintln(.;ontinuing.); }

&his version gives the follo#ing output


i 0 " 0 i 0 " ! i ! " 0 i ! " ! ;ontinuing

*f you #ere to substitute the continue command #ith brea', the i counter #ould stop at zero as the processing of the outer loop #ould be abandoned instead of simply continuing to the next increment.

(uestions

(uestion 1)
What #ill happen #hen you attempt to compile and run the follo#ing code in a methodE
for(int i=0;i<5;){ ,y-tem.out.*rintln(i); i++; )ontinue; }

+7 Compile time error, malformed for statement ,7 Compile time error continue #ithin for loop -7 runtime error continue statement not reached @7 compile and run #ith output 2 to @

(uestion *)

What #ill happen #hen you attempt to compile and run the follo#ing codeE
*u3li) )l -- O 3Ooo*{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ O 3Ooo* ml = new O 3Ooo*(); ml. metho7(); m inmetho7F ,y-tem.out.*rintln(.;ontinuing.); } *u3li) 6oi7 metho7(){ outerF for(int i=0;i<2;i++){ for(int "=0;"<%;"++){ if("?!) 3re # m inmetho7; ,y-tem.out.*rintln(.i .+ i + . " .+"); } }''=n7 of outer for } }

!) i 0 " 0 i 0 " ! ;ontinuing

,7
i i i i 0 0 ! ! " " " " 0 ! 0 !

;ontinuing %)

Compile time error


&) i 0 " 0 i 0 " ! i ! " 0 i ! " ! i 2 " ! ;ontinuing

(uestion +)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
*u3li) 6oi7 metho7(){ outerF for(int i=0;i<2;i++){ for(int "=0;"<2;"++){ ,y-tem.out.*rintln(.i=.+i + . "= .+"); if(i ?0) 3re # outer; } } ,y-tem.out.*rintln(.;ontinuing with i -et to =.+i); }

+7 Compile time error ,7


i=0 i=0 i=! %) i=0 i=0 i=! i=2 &) "= 0 "= ! "= 0 "= "= "= "= 0 ! 0 0

i=0 "= 0 i=0 "= !

(uestion ,)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
int i=0; while(i?0){ ,y-tem.out.*rintln(.B lue of iF .+i); } 7o{ ,y-tem.out.*rintln(i); } while (i <2);

!) B lue of iF 0 followe7 3y 0 !

,7
0 ! 2

-7
B lue of iF 0 2ollowe7 3y )ontinuou- out*ut of 0

@7 Continuous output of 2

(uestion -)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
*u3li) )l -- 4no6 { *u3li) -t ti) 6oi7 m in(,tring 4no6 n = new 4no6 (); n.go(); } *u3li) 6oi7 go(){ int :=0; for(int i=0;i<!0; i++$:++){ ,y-tem.out.*rintln(:); } for(;;){ ,y-tem.out.*rintln(.go.); } } } rg6[]){

+7 Compile time error, the first for statement is malformed ,7 Compile time error, the second for statement is malformed -7 0utput of 2 to K follo#ed by a single output of /go/ @7 0utput of 2 to K follo#ed by constant output of /go/

(uestion .
What #ill be output by the follo#ing codeE
*u3li) )l -- 9y2or{ *u3li) -t ti) 6oi7 m in(,tring int i; int "; rg6[]){

outerF for (i=!;i <%;i++) innerF for("=!; "<%; "++) { if ("==2) )ontinue outer; ,y-tem.out.*rintln(.B lue for i=. + i + . B lue for "=. +"); } }

+7 ,7 -7 @7

alue for iQ+ value for (Q+ alue for iQ, value for (Q+ alue for iQ, value for (Q, alue for iQ- value for (Q+

Answers

Answer 1)
@7 compile and run #ith output 2 to @ &his is a strange but perfectly legal version of the for statement

Answer *)
-7 Compile time error 3ou cannot arbitrarily (ump to another method, this #ould bring bac' all the evils manifest in the goto statement

Answer +)
+7 Compile time error &his is not really a 4uestion about brea" and continue. &his code #ill not compile because the variable is no longer visible outside the for loop. &hus the final System#out#println statement #ill cause a compile time error.

Answer ,)
+7 Continuous output of 2 &here is no increment of any value and a #hile loop #ill not execute at all if its test is not true the on the first time around

Answer -)
@7 0utput of 2 to K follo#ed by constant output of /go/ &he structure of the first for loop is unusual but perfectly legal.

Answer . )
+7 alue for iQ+ value for (Q+ ,7 alue for iQ, value for (Q+

Objective +, try/catch and overridden methods


Write code that ma'es proper use of exceptions and exception handling clauses 6try catch finally7 and declares methods and overriding methods that thro# exceptions. An exception condition is a #hen a program gets into a state that is not 4uite normal. 1xceptions trapping is sometimes referred to as error trapping. A typical example of an exception is #hen a program attempts to open a file that does not exist or you try to refer to an element of an array that does not exist. &he try and catch statements are part of the exception handling built into Java. 5either C/C++ nor isual !asic have direct e4uivalents to JavaHs built in exceptions. C++ does support exceptions but they are optional, and isual !asic supports On Error01oto error trapping, #hich smac's some#hat of a thro#bac' to an earlier less flexible era of !A)*C programming. Java exceptions are a built in part of the language. Lor example if you are performing */0 you must put in exception handling. 3ou can of course put in null handling that doesnHt do anything. &he follo#ing is a little piece of code * have used #ith !orland/*nprise J!uilder to temporarily halt output to the console and #ait for any 'ey to be pressed.
*u3li) )l -- 1ry{ im*ort " 6 .io.*; *u3li) -t ti) 6oi7 m in(,tring

rg6[]){

1ry t = new 1ry(); t.go(); }''=n7 of m in *u3li) 6oi7 go(){ try{ 5n*ut,tre mRe 7er i-r = new 5n*ut,tre mRe 7er(,y-tem.in); Auffere7Re 7er 3r = new Auffere7Re 7er(i-r); 3r.re 7Oine(); } ) t)h(=C)e*tion e){ '*Dot 7oing nything when eC)e*tion o))ur-*' } ''=n7 of try ,y-tem.out.*rintln(.;ontinuing.); }''=n7 of go }

*n this case nothing is done #hen an error occurs, but the programmer must still ac'no#ledge that an error might occur. *f you remove the try and catch clause the code #ill simply not compile. &he compiler 'no#s that the */0 methods can cause exceptions and demands exception handling code.

Com!aring with %isual &asic and C/C++


&his is a little more rigorous than isual !asic or C/C++ #hich allo#s you to thro# together /4uic' and dirty/ programs that pretend they are in a #orld #here errors do not occur. Memember that the original version of F0) #as called UF0) for Uuic' and Firty F0) by itHs creator and loo' ho# long #e have lived #ith the legacy of that bit of hac'ery. !y the time you have gone to the trouble of putting in a try0catch bloc' and blan' braces you may as #ell put in some real error trac'ing. *tHs not exactly bondage and discipline programming, it (ust persuasively encourages you to /do the right thing/.

Overriding methods that throw e>ce!tions


An overriding method in a subclass may only thro# exceptions declared in the parent class or children of the exceptions declared in the parent class. &his is only true for overriding methods not overloading methods. &hus if a method has exactly the same name and arguments it can only thro# exceptions declared in the parent class, or exceptions that are children of exceptions in the parent declaration. *t can ho#ever thro# fe#er or no exceptions. &hus the follo#ing example #ill not compile
im*ort " 6 .io.*; )l -- A -e{ *u3li) -t ti) 6oi7 }

metho7()throw- 2ileDot2oun7=C)e*tion{}

*u3li) )l -- =C)e*Iemo eCten7- A -e{ ''(ill not )om*ile$ eC)e*tion not in 3 -e 6er-ion of metho7 *u3li) -t ti) 6oi7 metho7()throw- 50=C)e*tion{} }

*f it #ere the method in the parent class that #as thro#ing IOException and the method in the child class that #as thro#ing (ile*ot(oundException this code #ould compile. Again, remember that this only applies to overridden methods, there are no similar rules to overloaded methods. Also an overridden method in a sub class may thro# 1xceptions.

'he throws clause


0ne of the issues created #ith the need to include try/catch bloc's in code that may thro# an exception is that you code can start to appear to more about #hat might happen than about #hat should happen. 3ou can pass exceptions /up the stac'/ by using the thro#s clause as part of the method declaration. &his in effect says /#hen an error occurs this method thro#s this exception and it must be caught by any calling method/. "ere is an example of using the thro#s clause
im*ort " 6 .io.*; *u3li) )l -- 1hrow-{ *u3li) -t ti) 6oi7 m in(,tring 1hrow- t = new 1hrow-(); try{ t. metho7(); }) t)h (50=C)e*tion ioe){} }

rg6[]){

*u3li) 6oi7 metho7() throw- 50=C)e*tion{ 2ile5n*ut,tre m fi- = new 2ile5n*ut,tre m(.1hrow-." 6 .); } }

(uestions

(uestion 1)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
im*ort " 6 .io.*; )l -- A -e{

*u3li) -t ti) 6oi7 }

metho7()throw- 2ileDot2oun7=C)e*tion{}

*u3li) )l -- =C)e*Iemo eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ =C)e*Iemo e = new =C)e*Iemo(); } *u3li) -t ti) 6oi7 metho7(){} *rote)te7 =C)e*Iemo(){ try{ I t 5n*ut,tre m 7in = new I t 5n*ut,tre m(,y-tem.in); ,y-tem.out.*rintln(.8 u-ing.); 7in.re 7;h r(); ,y-tem.out.*rintln(.;ontinuing.); thi-. metho7(); }) t)h(50=C)e*tion ioe) {} }

+7 Compile time error caused by protected constructor ,7 Compile time error caused by amethod not declaring 1xception -7 Muntime error caused by amethod not declaring 1xception @7 Compile and run #ith output of /Gausing/ and /Continuing/ after a 'ey is hit

(uestion *)
What #ill happen #hen you attempt to compile and run the follo#ing codeE
im*ort " 6 .io.*; )l -- A -e{ *u3li) -t ti) 6oi7 }

metho7()throw- 2ileDot2oun7=C)e*tion{}

*u3li) )l -- =C)e*Iemo eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ =C)e*Iemo e = new =C)e*Iemo(); } *u3li) -t ti) 6oi7 metho7(int i)throw- 50=C)e*tion{}

*ri6 te =C)e*Iemo(){ try{

I t 5n*ut,tre m 7in = new I t 5n*ut,tre m(,y-tem.in); ,y-tem.out.*rintln(.8 u-ing.); 7in.re 7;h r(); ,y-tem.out.*rintln(.;ontinuing.); thi-. metho7(); }) t)h(50=C)e*tion ioe) {} }

+7 Compile error caused by private constructor ,7 Compile error caused by amethod declaring 1xception not in base version -7 Muntime error caused by amethod declaring 1xception not in base version @7 Compile and run #ith output of /Gausing/ and /Continuing/ after a 'ey is hit

(uestion +)
What #ill happen #hen you attempt to compile and run this codeE
im*ort " 6 .io.*; )l -- A -e{ *u3li) -t ti) 6oi7 }

metho7()throw- 2ileDot2oun7=C)e*tion{}

*u3li) )l -- =C)e*Iemo eCten7- A -e{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ =C)e*Iemo e = new =C)e*Iemo(); } *u3li) -t ti) 6oi7 metho7(int i)throw- 50=C)e*tion{} *ri6 te 3oole n =C)e*Iemo(){ try{ I t 5n*ut,tre m 7in = new I t 5n*ut,tre m(,y-tem.in); ,y-tem.out.*rintln(.8 u-ing.); 7in.re 7;h r(); ,y-tem.out.*rintln(.;ontinuing.); thi-. metho7(); return true; }) t)h(50=C)e*tion ioe) {} fin lly{ ,y-tem.out.*rintln(.fin lly.); } return f l-e; } }

+7 Compilation and run #ith no output. ,7 Compilation and run #ith output of /Gausing/, /Continuing/ and /finally/ -7 Muntime error caused by amethod declaring 1xception not in base version @7 Compile and run #ith output of /Gausing/ and /Continuing/ after a 'ey is hit

(uestion ,)
Which of the follo#ing re4uire explicit try/catch exception handling by the programmer +7&raversing each member of an array ,7 Attempting to open a file -7 Attempting to open a net#or' soc'et @7 Accessing a method in other class

(uestion -)
What #ill happen #hen you attempt to compile the follo#ing codeE
im*ort " 6 .io.*; )l -- gr n ry{ *u3li) 6oi7 ) n l() throw- 50=C)e*tion{ ,y-tem.out.*rintln(.) n l.); } } *u3li) )l -- mmill eCten7- gr n ry{ *u3li) -t ti) 6oi7 m in(,tring rg6[]){ ,y-tem.out.*rintln(.mmill.); } *u3li) 6oi7 ) n l(int i) throw- =C)e*tion{ ,y-tem.out.*rintln(.mmill.) n l.); } *u3li) 6oi7 ) n l(long i) { ,y-tem.out.*rint(.i.); } }

+7 Compile time error ,7 Muntime errors -7 Compile error, mmill version of canal thro#s 1xception not in granary version @7 Compilation and run #ith output of mmill

Answers

Answer to (uestion 1)

@7 Compile and run #ith output of /Gausing/ and /Continuing/ after a 'ey is hit An overridden method in a sub class must not thro# 1xceptions not thro#n in the base class. *n the case of the method amethod it thro#s no exceptions and #ill thus compile #ithout complaint. &here is no reason that a constructor cannot be protected.

Answer to (uestion *)
@7 Compile and run #ith output of /Gausing/ and /Continuing/ after a 'ey is hit *n this version amethod has been overloaded so there are no restrictions on #hat 1xceptions may or may not be thro#n.

Answer to (uestion +)
+7 Compilation and run #ith no output. 0N, * have #andered off topic here a little. 5ote that the constructor no# has a return value. &his turns it into an ordinary method and thus it does not get called #hen an instance of the class is created.

Answer to (uestion ,)
,7 Attempting to open a file -7 Atempting to open a net#or' soc'et Oenerally spea'ing, all */0 operations re4uire explicit exception handling #ith try/catch bloc's. &he JFN +.@ exams does not explicitly cover */0 but it may be referred to in the context of exception handling.

Answer to (uestion -)
@7 Compilation and run #ith output of mmill &he limitations on #hat exceptions can be thro#n only applies to methods that are overriden, not to methods that are overloaded. !ecause the method canal is overloaded 6ie it ta'es a different parameter type7 in the mmill version there is no compile or runtime problem.

Vous aimerez peut-être aussi