84
CS 5JA Introduction to Java Objects You’ve heard the word “object-oriented” before. In general, it means thinking about a problem in terms of the objects involved. Or, modeling aspects of the world in discrete objects. Specifically, it refers to three particular concepts: encapsulation inheritance ploymorphism

CS 5JA Introduction to Java Objects You’ve heard the word “object-oriented” before. In general, it means thinking about a problem in terms of the objects

  • View
    214

  • Download
    0

Embed Size (px)

Citation preview

CS 5JA Introduction to Java

ObjectsYou’ve heard the word “object-oriented” before. In general, it means

thinking about a problem in terms of the objects involved. Or, modeling aspects of the world in discrete objects.

Specifically, it refers to three particular concepts:

encapsulation

inheritance

ploymorphism

CS 5JA Introduction to Java

EncapsulationEncapsulation means that each object is a kind of “capsule” of data.

You instantiate an object of a specific class.

Your object has data (instance variables).

You access the data through the specific methods defined in the object.

There is no other way to access the data, except through these methods.

The data is “hidden”, private to the object, and it is clearly defined how we can access and change the data.

For example, our Account class had a getBalance and a setBalance method to access and change the data. And the setBalance method wouldn’t let you set the balance to a negative number.

CS 5JA Introduction to Java

InheritanceThe next major idea in Object-Oriented programming is Inheritance.

You use the “extend” keyword in order to signal that the class will automatically include everything in a defined “superclass”.

In our drawing example we took a package from the java library called JPanel and extended it by adding data we cared about (polkadots, a mouselistener, etc). We also overrode the existing method paintComponent so that it painted something interesting and relevant to our task.

Out extended class is also called a “subclass”. E.g., MyDigitalPainting is a subclass of JPanel

In general, deciding how different classes inherit from each other solidifies the organization of your program and defines how data is related to each other. There may be no one right way to decide how to do it, but some ways may simplify your life.

CS 5JA Introduction to Java

InheritanceFor example, by extending JPanel, we could get away with not even thinking about

lots of difficult things, because the superclass already has methods relevant to any subclass: we used getWidth(), getHeight(), addMouseListener(), repaint(), etc. Our subclass automatically can use the data and methods in the superclass.

So, before we used inheritance to take advantage of code that already existed. But it is also helpful to define our own hierarchy of classes.

For example, as a non-techincal example you can think of the basic qualities of a bird:

what data might be important to define when modeling a bird?what actions might be important to define when modeling a bird?

.

CS 5JA Introduction to Java

Inheritancewhat data might be important to define when modeling a bird?size, color, sound of chirp, wingspan, number of feet, speed of flight,

favorite type of things to eat, predator or prey?

what actions might be important to define when modeling a bird?flight, eating, swimming, walking, hopping, singing, migrating, etc

Now if you think of an abstract bird, or your proto-typical bird, you probably think of ... a robin?

most birds are kind of small, have pleasant chirps, live in nests in trees, fly about tree level, are kind of brownish colored, eat worms.

but specifically, there are lots of birds that are completely different: chickens don’t fly, hawks eat mice, eagles soar really high in the air, crows have a super-annoying chirp, peacocks are colorful, etc, etc.

CS 5JA Introduction to Java

InheritanceBut there is enough basic “functionality” in our prototype to make it useful to define

a kind of basic bird which will contain most of the elements for most of the birds...

So we’ll define a base class, which is the superclass for all the other birds. It won’t extend from anything else

public class Bird{

boolean migrates = false;boolean canFly = true;int colorful = false;String favoriteFood = “worms”;String typeOfBird;

public Bird(String typeOfBird){

this.typeOfBird = typeOfBird;}

}

CS 5JA Introduction to Java

InheritanceNow any bird we decide to create automatically has four variables already

pre-defined for it. But we can extend this class so that it changes the variables, or adds different variables to it.

For instance, we might have a class which describes birds that can’t fly:

public class FlightlessBird extends Bird

{

public FlightlessBird(String typeOfBird)

{

super(typeOfBird);

this.canFly = false;

}

}

CS 5JA Introduction to Java

Inheritance

For instance, and we might have a class which describes birds that can fly:

public class FlyingBird extends Bird{

double avgHeight = 20.0;double avgSpeed = 10.0;

public FlyingBird(String typeOfBird, double avgHeight, double avgSpeed){

super(typeOfBird);this.avgHeight = avgHeight; this.avgSpeed = avgSpeed;

}}

CS 5JA Introduction to Java

InheritanceNow we can also have “base” methods we are automatically defined for all

birds, but can also be overwritten by subclasses of bird.

public class Bird

{

...

public void chirp()

{

//play generic bird sound

}

}

CS 5JA Introduction to Java

InheritanceNow we can also have “base” methods we are automatically defined for all

birds, but can also be overwritten by subclasses of bird.

public class FlyingBird

{

...

public void fly()

{

//model generic flight of a regular bird

}

}

CS 5JA Introduction to Java

InheritanceThese birds fly normally, so we won’t override the fly method

public class Nightengale extends FlyingBird{

...public void chirp(){

//play beautiful sounds of a nightengale...}

}public class Crow extends FlyingBird{

...public void chirp(){

//play ugly sounds of a crow...}

}

CS 5JA Introduction to Java

InheritanceThese birds fly normally, so we won’t override the fly method

public class Eagle extends FlyingBird{

...public void chirp(){

//play clip from Colbert Report...}

public void fly(){

//model soaring of bird...}

}

CS 5JA Introduction to Java

Enough birds (for now)What other things might be useful to model with inheritance?

base class: Phonesubclass: CameraPhone, SmartPhone, LandlinePhonewhy we’re using inheritance: all phones share basic functionality, but some phones

have added functionality

base class: Periodicalsubclass: DailyPeriodical, WeeklyPeriodical, BiweeklyPeriodical, MonthlyPeriodicalwhy we’re using in inheritance: all periodicals cost money and are printed on paper.

all of the subclasses have a different billing schedule, and in general the less often a periodical comes the nicer the paper is.

baseClass: Accountsublcass: CheckingAccount, SavingsAccount, CreditCardAccountwhy: all accounts have a balance and a security model, but different accounts have

different functionality: you can overdraw a creditcard, you get interest on a savings account, etc.

CS 5JA Introduction to Java

Your turnGet in groups of two or three or four and Take five minutes or so and think

up some good examples of things that can be described using inheritance. Use either practical examples that you might actually want to code up, or more general examples.

Also, once you have an example of an inheritance model, can you think of an alternative hierarchy that might also work? Why would one work better than another?

For instance, I divided Bird into FlyingBird and FlightlessBird, but it might also have been useful to divide Bird by what they eat: SeedEatingBird, WormEatingBird, MouseEatingBird, FishEatingBird, or whatever.

In other words, defining an inheritance model depends on the particular thing you are trying to do.

CS 5JA Introduction to Java

PolymorphismIn addition to helping us organize data, defining an inheritance model ties

in to a very useful feature of object-oriented programming called polymorphism.

Polymorphism is a fancy word to say that the particular method that is invoked depends on the specific subclass it is.

For example, our Bird base class had a method called chirp(). Which means that ALL subclasses of bird also will definitely have that method as well. They will either use the generic one provided in the base class, or they will override it.

CS 5JA Introduction to Java

Polymorphism

Bird nightingale = new Nightingale(“nightingale”);Bird crow = new Crow(“crow”, 10.0, 5.0);Bird eagle = new Eagle(“eagle”, 200.0, 30.0);

List<Bird> birds = new ArrayList<Bird>();

birds.add( nightingale );birds.add( crow );birds.add( eagle );

for (int i = 0; i < birds.size(); i++){

Bird b = birds.get(i);b.chirp();

}

CS 5JA Introduction to Java

PolymorphismEven though the method name is the same, the actual chirp method is

different for all the birds.

That is even though we have a list of type Bird,

When the code is run, Java is able to look and see that each object is actually a specific type of Bird, subclassed from the base class. So instead of using the basic chirp in Bird, it uses the most specific method available to it instead.

Now if we had a subclass that didn’t define the method chirp, then the most specific chirp() available is the one in the base class, so it would use that one.

CS 5JA Introduction to Java

Polymorphismpublic class Robin extends FlyingBird

{

public Robin(String typeOfBird)

{

super(typeOfBird);

}

//chirp is not defined! so use generic chirp from base class

}

CS 5JA Introduction to Java

Strings

We can make a new substring out of part of an original String:

String longStr = “Blah blah blah important stuff blah blah blah”;String subStr = longStr.substring(15, 29);

We can check to see if two string have the same data:

String str1 = “abc”;String str2 = “abc”;boolean theSame = str1.equals(str2);

String str1 = “abc”;String str2 = “abd”;boolean notTheSame = str1.equals(str2);

CS 5JA Introduction to Java

How to use FontsSince you have a Graphics object available to you, you can set and the

current Font if you need to draw Strings to the screen.

How to set a Font:

Font f = new Font(“Arial”, Font.BOLD, 32);

g.setFont(f);

The first argument is the typeface; the second is a style: either bold, italic, or plain; the third is the font size.

If you want to see what the current Font is, you can simply grab it with :

Font f = g.getFont();

CS 5JA Introduction to Java

Important Message

NO CLASS ON TUESDAY

CS 5JA Introduction to Java

How to use FontsYou can also query the basic attributes of the Font with the FontMetrics

class:

FontMetrics fm = g.getFontMetrics();

With the FontMetrics class you can do such useful things as query the size of a String in that font in the current Graphics context. This is useful for figuring out the size of a letter so that you can determine when it has been clicked.

Rectangle2D bounds = fm.getStringBounds(“Q”, g);

You pass in the String and the current Graphics, and it returns a Rectangle with the width and height of the String.

CS 5JA Introduction to Java

How to use FontsOr if you don’t need to be super specific, you can use :

Rectangle2D r2d = fm.getMaxCharBounds(g);

This will return the size of the largest possible character in that font, usually an O or a Q.

int w = (int) bounds.getWidth();

int h = (int) bounds.getHeight();

So now you have all the necessary information to determine when a particular letter has been selected.

CS 5JA Introduction to Java

How to use FontsOne slightly tricky thing about drawing a String as opposed to any other

type of graphical object is that instead of drawing from the (x, y) coordinate to the right & down, the drawString method draws from the (x,y) position to the right & up.

So now we have the (x, y) pixel coordinate of the letter, and the maximum possible with and height of the letter, so we can look to see if a particular mouse click hits one of our letters.

CS 5JA Introduction to Java

How to use Fonts (see FontTest1.java) Letter letter = letters.get(i);

int letterx = letter.getX();

int lettery = letter.getY();

int letterw = fontw;

int letterh = fonth;

if (

( (x > letterx) && (x < letterx + letterw) )

&&

( (y > lettery - letterh) && (y < lettery ) )

) {

System.out.println("you got a letter!");

}

CS 5JA Introduction to Java

A simple but real OO exampleLast class I talked about inheritance and polymorphism. I used a kind of

generic example of Birds and chirps.

Here’s a simple example that could conceivably be used with the Poetry Generator.

The assignment asks you to encode the parts of speech of particular sentences so that you can mimic the grammatical structure of a poem.

Because you might want to add lots of different types of sentences, and also make it so that other people could easily add other sentences, you might consider making your sentences into Objects. In particular, since creating sentences has more less the same logic for all sentences, it might make sense to put the basic functionality in a superclass, and extend the specific functionality for a sentence into a subclass.

CS 5JA Introduction to Java

A simple but real OO exampleBase class:

Sentence:

common data needed by all Sentences:

ability to get random words from the different word lists

placeholder for common method to create a sentence.

Inherited classes:

special method for deciding on the types of words to get and their order.

special method for getting punctuation, stylistic additions, etc.

CS 5JA Introduction to Java

A simple but real OO examplepublic Sentence

{

public String getRandomWord(List<String> wordList)

{

int index = (int) (Math.random() * wordList.size());

return wordList.get(index);

}

public String createSentence()

{

return “”; //this is just the base class. We can change this so that it has default functionality

}

}

CS 5JA Introduction to Java

A simple but real OO examplepublic EECummingsSentence extends Sentence{

public EECummingsSentence(PoetryGenerator generator){

this.generator = generator;}public String getRandomPunctuationMark(){

//logic to return a & or a ! or a %-- e.e. cummings style}public String createSentence(){

String sentence = “”;sentence += getRandomWord(generator.nounList).toLowerCase();sentence += “ ” + getRandomPunctuationMark();sentence += “ “ + getRandomWord(generator.adjList).toLowerCase();return sentence;

}}

CS 5JA Introduction to Java

A simple but real OO examplepublic EmilyDickinsonSentence extends Sentence{

public EmilyDickinsonSentence(PoetryGenerator generator){

this.generator = generator;}

public String createSentence(){

String sentence = “”;sentence += “The “sentence += getRandomWord(generator.adjList);sentence += “ “ +

getRandomWord(generator.nounList).toUpperCase();sentence += “ “ + getRandomWord(generator.verbList);sentence += “ “ + getRandomWord(generator.adverbList);sentence += “ - - “;return sentence;

}}

CS 5JA Introduction to Java

A simple but real OO exampleList<Sentence> templates = new ArrayList<Sentence>();

templates.add(new EmilyDickinsonSentence(this));

templates.add(new EECummingsSentence(this));

templates.add(new HallmarkCardSentence(this));

String poem = “”;

for (int i = 0; i < templates.size(); i++)

{

Sentence s = templates.get(i);

poem += s.createSentence + “\n”;

}

System.out.println(poem);

CS 5JA Introduction to Java

Strings

Take a close look at the Javadocs. There are some other powerful tools in the String library– mainly the ability to use regular expressions for string matching and substitution.

http://java.sun.com/javase/6/docs/api/java/lang/String.html

You can of course apply a sequence of operations to a String:

String str = “ a b c d e f”;

String newStr = str.trim().toUpperCase().substring(3,6).replace(“ “, “!”);

But this can be a bit confusing... However, if you see code like this you will know how to read it– from left to right.

CS 5JA Introduction to Java

StringsString str = “ a b c d e f”;

String newStr = str.trim().toUpperCase().substring(3,6).replace(“ “, “!”);

step 1: “a b c d e f”

step 2: “A B C D E F”

step 3: “ C D”

step 4: “!C!D”

step 5: assign “!C!D” to newStr.

CS 5JA Introduction to Java

ArrayListLast week we talked about arrays, including multi-dimensional arrays.

We made a note of a problem with arrays: you have to know their size before you work with them.

For example, say we are reading lines of text from a file, and we want to store those lines in an array of Strings. But we don’t know how many lines there are!

We have two choices:

1) We can loop through the list twice, once to count (so we can construct the array properly), and once to actually fill in the array.

2) We can make a super-big array and hope that the file isn’t bigger than we thought and that we don’t waste too much memory.

CS 5JA Introduction to Java

ArrayListAnd actually we have another choice:

3) We can use an ArrayList to store the data.

Here’s how you initialize an ArrayList to hold an arbitrary number of Strings:

List<String> listOfStrings = new ArrayList<String>();

This syntax is a little bit unusual, and it was introduced into Java only a couple of years ago.

The idea is that we have a bunch of different kinds of data structures, all of which are in some way a collection of data. And we have a framework (the Collections framework) for moving data into different data-structures.

CS 5JA Introduction to Java

ArrayListList<String> listOfStrings = new ArrayList<String>();

The first word List is a special kind of data-type called an interface. We’ll talk about this in more detail later. The actual data-type is ArrayList, which is an implementation of the interface. An interface describes important features, but doesn’t actually provide the logic to do anything. The implementation of the interface is a normal class that is required to handle all of the important features.

For example, if we have a list of data, we need to be able to add and remove data to it. All lists of data require these important features. But different types of lists might do it in different ways.

We are using an ArrayList, which is very fast at “random access”, that is optimized for adding to, removing from, or getting or setting at data a particular location. Other lists are faster at iterating through data in order, etc.

CS 5JA Introduction to Java

ArrayListList<String> listOfStrings = new ArrayList<String>();

The pointy braces explicitly defines the type of data that the List can hold.

In this case, Strings and Strings only. Trying to add anything else to our listOfStrings will throw an error.

So, to summarize:

We have a List called listOfStrings which can only hold Strings and uses the ArrayList implementation to store and retrieve those Strings.

Let’s look at the available methods in the List interface:

(http://java.sun.com/javase/6/docs/api/java/util/List.html)

CS 5JA Introduction to Java

ArrayListList<String> listOfStrings = new ArrayList<String>();

listOfStrings.add(“some words”);listOfStrings.add(4, “other words”);

listOfStrings.remove(2); //remove String at 2nd index (ie, the 3rd String)listOfStrings.remove(“some words”); //find and remove the first occurance of the

String (“some words”);

listOfStrings.set(3, “yet another string”); //overwrite whatever is at index 3 and replace it with “yet another string”.

String s = listOfStrings.get(2); //return the String that is at the 2nd index. int pos = listOfStrings.indexOf(“some words”); //return index of “some words”)

boolean doesStringExist = listOfStrings.contains(“some words”);

int numStringsInList = listOfStrings.size();

CS 5JA Introduction to Java

ArrayListAs with normal Arrays, the most important things we do with Lists are :

sorting, searching, and storing data.

For arrays, we have a uitlity class called Arrays which has built in sorting and searching methods.

Likewise, for Lists (and other types of data structures in the Collections Framework) we have a utility class called Collections with helpful static methods:

Collections.sort(listOfStrings); //sorts alphabetically

Collections.binarySearch(listOfStrings, “important stuff”); //returns index to “important stuff”

CS 5JA Introduction to Java

ArrayListAdditionally, there is some other cool stuff built in:

Collections.rotate(listOfStrings, -3);

Collections.shuffle(listOfStrings);

Collections.reverse(listOfStrings);

int numTimes = Collections.frquency(listOfStrings, “word”);

int pos = Collections.min(listOfStrings);

int pos = Collections.max(listOfStrings);

CS 5JA Introduction to Java

Next ClassNew homework set will be on-line by this evening or tomorrow at latest.

Will be due next Thursday and involve three or four problems.

Next class:

adding a mouseListener and a keyboardListener to a JFrame

loading from and saving images to a file.

CS 5JA Introduction to Java

MouseListenerIn the last assignment we learned how access the Graphics package to

draw on a component, in our case we used the JPanel.

If we want to use the mouse, we need to make use of a built-in interface called a MouseInputListener. This interface will provide information about the position of the mouse (in relationship to the JPanel) when it is mouse is moved, clicked, pressed, or dragged, and released.

We talked briefly about interfaces last class. Java’s built-in interfaces may have some basic functionality, but you are required to implement certain functionality via specified methods.

In the case of MouseInputListener we need to implement the following 7 methods: mouseClicked, mousePressed, mouseDragged, mouseReleased, mouseMoved, mouseEntered, and mouseExited.

CS 5JA Introduction to Java

MouseListenerEven if you only care about, say, what happens when the user clicks the

mouse, but not what happens when the user moves it, you still need to provide that method. Otherwise the compiler will tell you that there is an error and that you haven’t fulfilled the contract designated by the interface.

For instance, I have never used mouseEntered or mouseExited, and so I just provide empty functions for them like so:

public void mouseEntered(MouseEvent e) {}

public void mouseExited(MouseEvent e) {}

CS 5JA Introduction to Java

MouseListenerHowever if you do care about the functionality, then you can make use of

the MouseEvent it gives you to query the position of the mouse when that event is occurring.

int mx = 0;

int my = 0;

public void mousePressed(MouseEvent me)

{

mx = me.getX();

my = me.getY();

System.out.printf(“mouse pressed at pixel position %d/%d\n”, mx, my);

}

CS 5JA Introduction to Java

MouseListenerLet’s modify our PolkadotTest program so that it only draws polka dots at

the places we specify with the mouse. Since we don’t know in advance how many times the user will press the mouse, we’ll use the ArrayList to store polkadots (instead of a normal array like we used before).

During the paintComponent method we’ll iterate through our list of polkadots and draw them.

[example code]

CS 5JA Introduction to Java

MouseListenerNow what if we mistakenly add a polka dot to the wrong place? Let’s

modify our code so that a user can select a polkadot. If the user selects the polkadot it will be instantly removed from the list, and thus won’t be drawn anymore.

[example code]

CS 5JA Introduction to Java

MouseListenerAs a final example, instead of making the user remove and re-add a

polkadot, we’ll let the user drag it to a new position.

[example code]

CS 5JA Introduction to Java

MouseListenerAs a final final example, let’s make a new program that imitates the pencil

tool from Photoshop. It draws a small black square under the mouse as we press and drag the mouse across the screen.

[example code]

CS 5JA Introduction to Java

KeyListenerJust as there are built-in listeners to get mouse events, there is a built-in

listener to get keyboard events. We also need to tell the compiler that our class implements the interface, and when we instantiate the object we need to add the listener to our new object. We also need to make sure and actually implement all the methods that the interface defines.

CS 5JA Introduction to Java

KeyListener

adding listeners, setting focus

fonts

saving images

switch statement

try/catch with imageIO

difference between interface and extends

this keyword

CS 5JA Introduction to Java

ArraysWe get at the data in the array using the indexing notation:

int checkNumber = myNumbers[0];

int checkNumber = myNumbers[55];

etc...

CS 5JA Introduction to Java

Arrayswhat’s going on in these code snippets?

int[] myIntArray = new int[3];System.out.println(“num = “ + myIntArray[1]);

int[] myIntArray = new int[3];myIntArray[0] = 99;myIntArray[1] = 98;myIntArray[2] = 97;myIntArray[3] = 96;

double[] myDblArray = new double[2];myDblArray[0] = 99.9;myDblArray[1] = -100.0;System.out.println(“num = “ + myIntArray[2]);

CS 5JA Introduction to Java

Arrays

int[] myIntArray = new int[3];

myIntArray[0] = 2;

myIntArray[1] = 0;

myIntArray[2] = 1;

myIntArray[3] = 17;

what does myIntArray[2] equal?

what does myIntArray[myIntArray[0]] equal?

what does myIntArray[myIntArray[0] – myIntArray[2]] equal?

CS 5JA Introduction to Java

ArraysYou can create, initialize, and fill an array all at the same time with this shortcut

syntax:

String[] myStrArray = {“Duck”, “Duck”, “Duck”, “Goose”};

boolean[] myBoolArray= {false, false, false, true};

what is myStrArray[1] contain?

what does x equal?

boolean x = myBoolArray[0];

what does x equal?

boolean x = myBoolArray[4];

what does str equal?

boolean str = myStrArray[3];

CS 5JA Introduction to Java

ArraysString[] grades = {“A”, “A+”, “C”, “F”, “B+”};

How do I change the grade from a C to an A?

CS 5JA Introduction to Java

ArraysString[] grades = {“A”, “A+”, “C”, “F”, “B+”};

How do I change the grade from a C to an A?

grades[2] = “A”;

Or something like:

String newGrade = “A”;

grades[2] = newGrade;

CS 5JA Introduction to Java

ArraysWhat are arrays good for?

An array is a simple data structure. That is, you have a set of data and you give it some structure.

I used the example of a pile of papers that you put into a filing cabinet.

The main things you can do with your filing cabinet:

storing information, sorting information and searching for information

[see example program, ArraysTest.java]

CS 5JA Introduction to Java

ArraysYou can also pass arrays to methods just like other data types: This

sample shows how to use one of the binarySearch methods in the Arrays library.

public Test() {int[] someArray = {2, 4, 1, -4, 5, 6};boolean hasZero = doesListContainAZero(someArray);

}public boolean doesListContainAZero(int[] intArray){

if (Arrays.binarySearch(intArray, 0) > -1){

return true;}return false;

}

CS 5JA Introduction to Java

Pass-by-value vs Pass-by-referenceIn Java, when you pass a variable to a method it either

a) makes a new variable which is a copy of the original value, even if the variable has the same name.

b) passes in the exact same data, even if the variable is given a different name.

The first possibility is called “passing-by-value” and it is what happens for any primitive data types (ints, booleans, doubles, etc).

Every other data type in Java uses “passing-by-reference”. This includes every object and arrays.

CS 5JA Introduction to Java

Pass-by-value vs Pass-by-referenceWhen something is passed-by-reference, it means that any modification to

the data within a method will affect the data outside the method as well.

When something is passed-by-value, it means that any modification to the data within the method has no affect whatsoever on the data outside the method.

public void method1() {

int x = 5;

method2(x);

System.out.println(“x = “ + x); //what is x?

}

public void method2(int x) {

x = 6;

}

CS 5JA Introduction to Java

Pass-by-value vs Pass-by-referenceArrays are passed-by-reference

public void method1() {

int[] arr = {5, 6, 7};

method2(arr);

//what is arr[0]?

System.out.println(“arr[0] = “ + arr[0]);

}

public void method2(int[] aNewArray) //not really new!

{

aNewArray[0] = 1001;

}

CS 5JA Introduction to Java

Pass-by-value vs Pass-by-referencePrimitive values in arrays are still passed-by-value

public void method1() {

int[] arr = {5, 6, 7};

method2(arr[0]); //just an int!

//what is arr[0]?

System.out.println(“arr[0] = “ + arr[0]);

}

public void method2(int aNewInt) //it really is new!

{

aNewInt = 1001;

}

CS 5JA Introduction to Java

Multi-dimensional Arrays

You can also make an array of arrays, also called a Multi-dimensional array.

For instance, to declare a two-dimensional int array, you can do this:

int[][] da = new int[2][];da[0] = new int[] {5,4,3,2,1};da[1] = new int[2];da[1][0] = 100;da[1][1] = 99;

So what’s in da[0]? What’s in da[1]? What value is da[0][2]? What value is da[1][3]? What value is da[1][1]?

What happens if you print d[0] or d[1]?

CS 5JA Introduction to Java

Multi-dimensional ArraysYou can also use the shortcut method for multidimensional arrays:

int da[][] = { {1, 2, 3}, {10, 11, 12} };

[see ArraysTest.java]

You can have as high a dimension as you want...

[see ArraysTest.java]

CS 5JA Introduction to Java

Multi-dimensional ArraysMain issue with arrays...

You have to know their size before you work with them. You can’t arbitrarily add extra data into them without recreating them from scratch.

The more flexible way is to use the List interface... which we’ll talk about another time.

CS 5JA Introduction to Java

Quick note about debugging...If your program doesn’t compile, then you have a syntax error.

The compiler will provide you with a list of errors and line numbers for where each error occurs.

Sometimes it’s a little off. The error might be that you forgot a semi-colon on a line, but the line that shows up as an error is the line below. To the compiler, the error doesn’t really happen until it runs into something it can’t handle, which in this case is when all of sudden there is something unexpected.

System.out.print(“hello”)System.out.print(“again”);

The compiler removes all whitespace (except within quotes) so it sees something like this...

System.out.print(“hello”)System.out.print(“again”); So it finds the error at the capital S at the beginning of line 2.

CS 5JA Introduction to Java

Quick note about debugging...If your program compiles but gives you unexpected results, then you have

a logical error.

You will have no information about why it isn’t doing what you wanted it to!

There are tools called debuggers which you can attach to your program and step through code so you can tell what’s going on at every point.

But usually the simplest solution is to break things into small steps and make sure that each of those steps work.

For instance, you can take a complicated piece of code and break it up into smaller methods, and then write test cases to make sure that the individual methods are doing what they are supposed to.

CS 5JA Introduction to Java

Quick note about debugging...The main thing though to remember is that System.out.println is your

friend.

You can use it to make sure that your code has gotten to a certain place.

You can use it to make sure that you have the right values at particular variables

public void myMethod(int a, int b)

{

System.out.println(“in myMethod, int a = “ + a);

System.out.println(“int b = “ + b);

int c = complicatedFunction(a, b);

System.out.println(“ok, c = “ + c);

}

CS 5JA Introduction to Java

Passing in arguments from the command lineWe’ve talked about the main mathod signature:

public static void main (String args[])

What does the String args[] part do?

It says that the method expects an array of type String. Built in to Java is the ability to pass Strings in from the command line, like so:

java MyProgram str0 str1 str2

In the main method you can access these Strings:

CS 5JA Introduction to Java

Passing in arguments from the command line public static void main (String args[])

{

for (int i = 0; i < args.length; i++)

{

System.out.println(“args[“+i+”] = “ + args[i]);

}

}

You can use these arguments to pass in parameters, filenames, numbers, etc.

But as you can see, by default they are Strings, so you need to convert them to other data types if necessary.

CS 5JA Introduction to Java

Parsing data from a String Commonly, you’ll want to get a number out of a String. If a user passes in

the string “5”, you will want to convert it to an int so that you can do something with it.

There are different ways to do this. Because it is so common, there is a built-in utility method in the Integer class which lets you parse out a number:

int num = Integer.parseInt(“5”);

String numApples = “I have 5 apples”;

int num = Integer.parseInt(numApples);

CS 5JA Introduction to Java

Parsing data from a String For more complex parsing, you can use the Scanner as we have already

done.

String numApples(“I have 10 apples!”);Scanner s = new Scanner(numApples);

while(s.hasNext()){ if(s.hasNextInt()) {

int num = s.nextInt(); }}

If you try to scan for a data type that isn’t there you will get an Exception,in this case a InputMismatchException.

CS 5JA Introduction to Java

Exceptions Exception handling is the term used for dealing with errors. So far, we

have assumed that if there are any errors then they are “fatal”. We either explicitly exit the program immediately, or we let the Java exit the program when it discovers a run-time error.

However there are many cases when we might not want to exit the program when there is an error, or make sure that we haven’t left any resources open (ie databases, files, usb devices, etc), or at the very least print the reason why there is a problem before exiting.

We can do this by using the exception handler to “catch” the error.

CS 5JA Introduction to Java

ExceptionsCertain objects will throw errors when something inappropriate happens.

So we can wrap code in a try-catch block to try and make sure the code works, and if not, catch the error and then decide what to do.

Scanner s = new Scanner(System.in);

while(s.hasNext())

{

int num = s.nextInt();

}

If a user types letters instead of number, the Scanner method will throw a run-time error, and the program will exit and print an error message to the screen.

CS 5JA Introduction to Java

ExceptionsBut if we wrap it in a try-catch block, then we can stop the code from exiting and

decide if it’s really a problem or not.

Scanner s = new Scanner(System.in);try{

while(s.hasNext()){

int num = s.nextInt(); }

}catch (InputMismatchException ime){

System.out.println(“hey– you did something wrong! But no worries!”);}

You can look to see what errors might be thrown by a method by looking at the JavaDocs

CS 5JA Introduction to Java

Exceptionspublic int nextInt()

Scans the next token of the input as an int. Returns:

the int scanned from the input

Throws: InputMismatchException - if the next token does not

match the Integer regular expression, or is out of range

NoSuchElementException - if input is exhausted IllegalStateException - if this scanner is closed

CS 5JA Introduction to Java

ExceptionsSome methods require that you catch the errors.

Someone asked about pausing the program. Since pausing the program basically creates a new temporary process which can potentially be interrupted (we don’t need to get into the details of threading right now), we are required to wrap it in a try-catch block.

try{

Thread.sleep(1000); //pause for 1000 milliseconds, or 1 second}catch(InterruptedException ie){ System.out.println(“just to let you know, we didn’t actually sleep for 1

second because we were interrupted!”);}

CS 5JA Introduction to Java

ExceptionsAnother example: if you try to use a file ten you are required to wrap it in a try-catch

block in order to handle the possibility that the file doesn’t actually exist.

File file = new File(“text.txt”); Scanner scanner = null; try { // Create a scanner to read the file scanner = new Scanner (file); } catch (FileNotFoundException e) { System.out.println ("File not found!"); // Stop program if no file found System.exit (0); // or we could force the user to entire a new filename, or browse for the file, etc }

And this is the main reason I’m introducing this now, because your homework will require that you read from and write to a file.

CS 5JA Introduction to Java

Reading from a fileThere are different ways to read from a file. But this one makes it

especially easy to read text from a file. Others are better for images, etc.

We’ve used the Scanner to read text from the command prompt, but it can also be used to read from a file.

First, create a File object with a filename:

File file = new File(“myTextFile.txt”);

Then make a Scanner that scans from that file:

Scanner fileScanner = new Scanner(file);

CS 5JA Introduction to Java

ExceptionsSince this particular constructor explicitly throws an exception, we just

need to wrap it in the appropriate try-catch block

Scanner fileScanner;

try

{

fileScanner = new Scanner(file);

}

catch (FileNotFoundException e)

{

//handle error in some way...

}

CS 5JA Introduction to Java

Parsing text from a fileNow we can use the normal Scanner operations to put the contents of the

file into variables that we can use in our program.

Here’s a file called “grades.txt”:

87

99

12

80

100

CS 5JA Introduction to Java

Parsing text from a fileScanner fileScanner;

try

{

fileScanner = new Scanner(“grades.txt”);

}

catch (FileNotFoundException e)

{ System.out.exit(0); }

int[] grades = new int[5];

for(int i = 0; i < 5; i++)

{

grades[i] = fileScanner.nextInt();

}

CS 5JA Introduction to Java

Writing text to a fileThe opposite of reading text to a file is writing text to a file. Java has a

simple method for formatting data to a String, the terminal, or to a file. It uses the same conventions as the “printf” command you may have seen in the textbook.

It interprets special codes as particular data types, these are the only ones we’ll be concerned with

%d = number (int or long)

%s = string

%f = decimal (float or double)

int temperature = 55;

System.out.printf(“It is %d degrees out today\n”, temperature);

CS 5JA Introduction to Java

Writing text to a fileFile file = new File(filename);

Formatter formatter = null; try { formatter = new Formatter (file);}catch (FileNotFoundException e) {

//not a problem because we are about to create the file!!!}for(int i = 0; i < grades.length; i++){

formatter.format (“Grade for student %d is %d\n”, i, grades[i]); }//need to “flush” the data to the file, then close the file.formatter.flush ();formatter.close ();