• No results found

Introduction to Java Lecture Notes. Ryan Dougherty

N/A
N/A
Protected

Academic year: 2021

Share "Introduction to Java Lecture Notes. Ryan Dougherty"

Copied!
52
0
0

Loading.... (view fulltext now)

Full text

(1)

Introduction to Java

Lecture Notes

Ryan Dougherty [email protected]

(2)

1 Versions . . . 2 2 Introduction . . . 3 3 Computers . . . 4 4 Data Types . . . 8 5 Decisions . . . 18 6 Loops . . . 24 7 Introduction to Classes . . . 29 8 Methods . . . 35 9 Static . . . 39 10 Method Overloading . . . 41 11 Arrays . . . 43 12 Searching . . . 45 13 Sorting . . . 48

Versions

Here are the versions of the book over time.

(3)

Introduction

Welcome to these lecture notes for CSE110! This guide will help you on your journey in learning the basics of programming in Java, including methodologies for problem solving using computers. Programming is becoming more of an important tool in the last few decades. Understanding of these technological shifts, therefore, is imperative.

The topics are split up according to the Table of Contents above, and their corresponding page numbers. At the end of each chapter are written and programming exercises. The written exercises are for testing your knowledge of the material, and the programming ones are to see if you can write programs using the material from that chapter.

If there are any questions/errors/comments that you want to send regarding the material, send an email to:

(4)

Computers

3.1 Motivation

This chapter concerns basic knowledge of computers. In order to write programs for computers, we need to have a basic understanding of how computers work. Once we have this understanding, we can write programs that make use of the computer’s hardware and software.

A computer is a general-purpose device that can be programmed to carry out a set of arithmetic or logical operations automatically. Since a sequence of operations can be readily changed, the computer can solve more than one kind of problem.

In recent years, computers have become much faster due to advancements in hardware speed and software breakthroughs. However, there is only a limit to how fast these advancements can take us. Therefore, we need to write programs that use the hardware efficiently.

3.2 Introduction to Java/Programming Languages

Java is an object-oriented programming language invented by Sun Microsystems in 1995, and Sun was acquired by Oracle in 2009. One large benefit of Java is that it is run in a virtualmachine, which means that it can be run on almost all major platforms: Windows, Mac OS X, Linux, Solaris, etc.

A programming language is a formal constructed language designed to communicate instructions to a machine; particularly, a computer. Basically, it allows a person to code a sequence of instructions that makes the computer do what he/she wants. A computer program, or just a program, is a sequence of instructions, written to perform a specified task on a computer. A computer requires programs to function, typically executing the program’s instructions in a central processor. 3.3 Java Program Structure

All Java programs follow the same basic structure. A typical Java file (with a “.java” extension) is composed of 1 or more classes, which have 1 or more methods, which have 1 or more statements. We will give more rigor to what these terms mean later. Java classes are (typically) provided in packages, which contain one 1 or more classes.

3.4 First Java Program

A typical first program for a programmer in any programming language is called a “Hello, World” program, which prints that phrase to the screen/console. The reason that this is the first program for many programmers is that they can demonstrate that they know the basic structure of a Java program.

To print to the screen, a program (that must be saved in a text file that is called HelloWorld.java) to do this is:

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

(5)

S y s t e m . out . p r i n t l n (" Hello , W o r l d ") ; }

}

You must type this program in a raw text editor, not in a rich text editor such as Microsoft Word. The reason for this is that Microsoft Word adds special characters, which are not recognized when you compile and run your program (see below).

For many beginners, this program may be a little daunting and confusing. But as we can see, this program follows the basic structure of a Java program: it has 1 class, named HelloWorld; it has one method, named main, and it has one statement, which prints to the screen.

For each of the terms, the precise meaning of them will be covered in later chapters. However, the basic structure of:

p u b l i c c l a s s Y o u r P r o g r a m {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) {

// I n s e r t s t a t e m e n t s h e r e

} }

will be enough for most beginning Java programs. As a programmer, you will put the statements between the opening and closing brace of the main method.

Note: the main method is the starting point of execution for every Java applica-tion/program.

Note: the text “Insert statements here” is in green. This is a “comment”, in which you can add any text. There are 3 types of Java comments:

– Line comments - start with //, and last for the rest of the line.

– Multiline comments - start with /* and end with */, and last until the */ is reached.

– JavaDoc comments - these have the same form as multiline comments, but have a purpose in providing documentation for Java code. They are typically put right before a method declara-tion.

3.5 Running/Compiling Java Programs

Now that we understand how to create Java programs, we want to run them on our computers. In order to run a Java file, we need to do 2 steps: compile it, and then run it.

A compiler (for most programming languages) is software that translates the user-created code into object (or “machine”) code. Obviously, user-created code is readable by the user, since the user created it. However, object code is not readable, since it is code that the computer can read, and then execute.

There are a few ways of compiling a Java file:

– If you have an Integrated Development Environment (IDE), such as Eclipse, Netbeans, etc. on your machine (they are available on the web for free), running your program is done by clicking the green arrow (“Run”) button in the toolbar. This operation will compile and run the program.

– If you are not using an IDE, and have a Terminal/Command Prompt, etc. application in which you supply commands, you enter these commands to compile and then run a Java program:

(6)

• java YourProgramName (Note: no “.java” extension on this command)

– If you do not have a Terminal/Command Prompt application, consult sources online on how to use the “JDK” (which means Java Development Kit).

3.6 Compilation Errors

However, if you mistyped during creating your program, you encounter what is called a “compilation error”, which shows an appropriate error message. Common errors include:

– Incorrect class name - the name of the class must exactly match the name of the file that it is saved in.

– Invalid class name - there are rules for what a class name can be. For example, it cannot be a Java keyword (i.e. public, class; all of the words that highlight in blue).

– No semicolon after statements - all statements must end in a semicolon.

– Not putting quote marks around what is put inside the System.out.println statement. This is called a “string” of characters. If no quote marks are put, then the Java compiler cannot recognize what Hello, World means. However, it does know what “Hello, World” means.

3.7 Notes

– There are 2 kinds of print statements in Java:

• System.out.print - prints out exactly what is given in the parentheses.

• System.out.println - same as print but adds a newline after the text given in the paren-theses. The next time something is printed, it will start on the next line.

– There are numerous special characters that appear in between quote marks (called “escape characters”):

• \n - a newline character. Suppose we have this line of code: S y s t e m . out . p r i n t (" T e s t i n g n e w l i n e \ n T e s t 2 ") ; The output for this code would be:

Testing newline Test2

Notice that the character \n was not printed because it has a special purpose: providing a new line. Therefore, one can see that the following lines of code do the same thing:

System.out.println("Text"); System.out.print("Text\n");

• \t - a tab character. The text that follows \t will appear in the same manner as a tab key is used in any other text document.

• \" - to print a double quote. 3.8 Written Exercises

1. What does a compiler do?

(7)

p u b l i c c l a s s V e n d i n g M a c h i n e {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) {

S y s t e m . out . p r i n t l n (" P l e a s e i n s e r t 25 c ") ; }

}

By what name would you save this program on your hard disk?

3. Is Java a functional language, procedural language, object-oriented language, or logic language? 4. What is a plain text file?

5. How is a text file different than a .doc file? 6. What is a source program?

7. What is Java bytecode?

8. What is the program that translates Java bytecode instructions into machine-language instruc-tions?

9. Is Java case-sensitive?

3.9 Programming Exercises

1. Write a program to print the following to the screen using a number of print statements: 1 2 3 4 5

2 3 4 5 1 3 4 5 1 2 4 5 1 2 3 5 1 2 3 4

(8)

Data Types

4.1 Motivation

Now that we know how to compile and run programs, and print to the screen, we will bump up the complexity of our programs a little. In this chapter, we will be exploring data types, and how to do basic calculations.

4.2 Types

There are 8 “primitive” (fundamental) data types in Java (we will explain constraints that they have later):

– byte - an integer with a small range. – short - same as byte, but a larger range. – int - same as short, but even larger range. – long - same as int, but even still larger range. – float - a “real” value, that has some precision. – double - same as float but with more precision.

– boolean - a type that takes one of two possible values: true, or false.

– char - a Unicode character. Think of a or b as chars - any single character is a char.

Now, we give the range for each of the primitive data types (all inclusive on both ends). These are all of the values that they can hold:

– byte: -128 to +127. – short: -32768 to +32767. – int: −231 to +231− 1. – long: −263 to +263− 1. – float: 1.4 × 10−45to 3.4 × 1038. – double: 4.9 × 10−324 to 1.7 × 10308.

– boolean: true or false. – char: 0 to 65535.

Now that we know the 8 fundamental data types, we want to know how to use them. To do that, we have to declare a variable with a type.

(9)

4.3 Variable Declaration

Like classes in the previous chapter, declaring variables follow the same basic structure, which is: < T ype > < V ariableN ame >= < V alue >;

For example, if we want a int variable called val to have a value of 2, we would write the line of code as:

int val = 2; // a s s i g n val to a v a l u e of 2

Also, we can declare several variables of the same type in the same line using a comma between the names:

int val = 2 , o t h e r V a l = 3; Notes:

– In a list of declarations, there is no need to declare the type twice (in fact, there will be a compiler error if this is done)

– The convention in Java names is to follow camel casing: the first “word” is lowercase, and the subsequent “words” in the same variable are capitalized (see example above).

Now, there are only certain names that our Java variables can have. The rules are:

– The name cannot be a “keyword” (any of the words in this document that are colored blue, such as int, public, etc.).

– The first character must be a letter (either upper or lowercase), the underscore symbol, or a dollar sign (“$”). However, a variable name cannot start with a number.

– Any character other than the first may be letters, underscores, the dollar sign, or also numbers. Here are some variable declarations using all primitive types:

b y t e b = 1; s h o r t s = 2; int i = 3 0 0 ; l o n g l = 1 0 0 0 L ; // n o t e the ’ L ’ f l o a t f = 0 . 5 6 f ; // n o t e the ’ f ’ d o u b l e d = 5 2 3 . 6 ; // no s u f f i x b o o l e a n b = t r u e; c h a r c = ’ a ’; // c h a r s are s u r r o u n d e d in s i n g l e q u o t e s

After we have initialized a variable, we can also modify it without having to declare it again. Here is an example:

int i = 3 0 0 ;

i = 3 0 1 ; // m o d i f i e s i ’ s v a l u e to be 301

// int i = 3 0 1 ; // t h i s c a u s e s a c o m p i l e r e r r o r // ( d e c l a r e o n c e )

(10)

4.4 Primitive Operators

Now that we know how to declare and modify values, we need to learn how to do various operations on them, such as addition, subtraction, multiplication, and division. An example showing all of them is the following (with comments):

/* A d d i t i o n */

// int w o r k s the s a m e as b y t e and s h o r t

int i1 = 0 , i2 = 3;

int i3 = i1 + i2 ; // a d d s i1 ’ s v a l u e (0) and i2 ’ s (3) // d o u b l e s and f l o a t s w o r k the s a m e way :

d o u b l e d1 = 2.5 , d2 = 3 . 0 ;

f l o a t d3 = d1 + d2 ;

f l o a t f1 = 2.5 f , f2 = 3.0 f ;

f l o a t f3 = f1 + f2 ;

// Can add a c r o s s types , but is p r o m o t e d to " m o s t p r e c i s e " // If we add d o u b l e + int , the r e s u l t is a d o u b l e

int i4 = 4;

d o u b l e d4 = 5 . 3 ;

d o u b l e d5 = d4 + i4 ;

// But we can a l s o " c a s t " ( w i t h p a r e n t h e s e s ) to the t y p e we w a n t if it is l e s s " p r e c i s e " - t h i s t r u n c a t e s the f r a c t i o n a l p a r t :

int c a s t e d = (int) ( d4 + i4 ) ; // e r r o r w i t h o u t ( int ) // c a n n o t do o p e r a t i o n s on b o o l e a n s ( c o m p i l e r e r r o r ) // b o o l e a n b1 = t r u e + f a l s e ; /* S u b t r a c t i o n */ // W o r k s w i t h p r i m i t i v e t y p e s the s a m e way as a d d i t i o n int i5 = 0 , i6 = 3; int i7 = i5 - i6 ; // i6 has v a l u e -3 /* M u l t i p l i c a t i o n */ // M u l t i p l i c a t i o n is the s a m e as a d d i t i o n in the s a m e t y p e // However , we p r o m o t e to " m o s t p r e c i s e " v a l u e if m u l t i p l e t y p e s int i8 = 5; d o u b l e d6 = 5 . 3 ; d o u b l e d7 = d6 * i8 ; // p r o m o t e i8 to a d o u b l e v a l u e d 5.0 /* D i v i s i o n */

// D i v i s i o n is e a s y to u n d e r s t a n d e x c e p t for w h e n the n u m e r a t o r and d e n o m i n a t o r are b o t h int / s h o r t / b y t e .

int i9 = 10 , i10 = 3;

// W h a t is i9 / i10 ? We e x p e c t 3 . 3 3 3 3 3 . . . , but we get 3 i n s t e a d . J a v a d o e s " i n t e g e r d i v i s i o n " , w h e r e the n u m e r a t o r and d e n o m i n a t o r

are b o t h ints , w h i c h is t r u n c a t i n g all the f r a c t i o n a l p a r t s . int i11 = i9 / i10 ; // i11 has v a l u e 3.

(11)

// However , if we " c a s t " one of the v a l u e s to a double , t h e n we do not h a v e t h i s p r o b l e m

d o u b l e d8 = (d o u b l e) i9 / i10 ; // c a s t i9 to a d o u b l e of v a l u e 1 0 . 0 // d8 now has v a l u e 3 . 3 3 3 3 3 3 . . .

Another operation is called the mod operator (or “remainder”):

int i1 = 10 , i2 = 3;

int i3 = i1 % i2 ; // i3 has v a l u e 1 , s i n c e 10 r e m a i n d e r 3 = 1.

We can also “shorten” times when we are modifying the same value with another. For example:

int i = 5;

i += 3; // e q u i v a l e n t to : i = i + 3;

i -= 3; // e q u i v a l e n t to : i = i - 3;

i *= 3; // e q u i v a l e n t to : i = i * 3;

i /= 3; // e q u i v a l e n t to : i = i / 3;

For int variables, there are 2 operations that are done very often, so they were put into the language: increment and decrement:

int i = 2;

i ++; // e q u i v a l e n t to : i += 1;

i - -; // e q u i v a l e n t to : i -= 1;

4.5 Boolean

So how do we compare values? There are various operators (parentheses added for clarity - they are not needed):

int i1 = 5 , i2 = 6; b o o l e a n l a r g e r = ( i1 > i2 ) ; // false , s i n c e 5 < 6 b o o l e a n l a r g e r O r E q u a l = ( i1 >= i2 ) ; // a l s o f a l s e b o o l e a n s m a l l e r = ( i1 < i2 ) ; // t r u e b o o l e a n s m a l l e r O r E q u a l = ( i1 <= i2 ) ; // t r u e b o o l e a n n o t E q u a l = ( i1 != i2 ) ; // t r u e b o o l e a n e q u a l = ( i1 == i2 ) ; // f a l s e // N o t e t h a t == m e a n s c o m p a r e value , = m e a n s a s s i g n

There are also operators to work with booleans: “and”, “or”, and “not”.

/* And = && */ b o o l e a n t = true, f = f a l s e; b o o l e a n a n d T r u e T r u e = t && t ; // t r u e b o o l e a n a n d T r u e F a l s e = t && f ; // f a l s e b o o l e a n a n d F a l s e T r u e = f && t ; // f a l s e b o o l e a n a n d F a l s e F a l s e = f && f ; // f a l s e /* Or = || */ b o o l e a n o r T r u e T r u e = t || t ; // t r u e b o o l e a n o r T r u e F a l s e = t || f ; // t r u e b o o l e a n o r F a l s e T r u e = f || t ; // t r u e b o o l e a n o r F a l s e F a l s e = f || f ; // f a l s e /* Not = ! */

(12)

b o o l e a n n o t T r u e = ! t ; // f a l s e b o o l e a n n o t F a l s e = ! f ; // t r u e

// We can use m u l t i p l e o p e r a t o r s at o n c e :

b o o l e a n m y s t = !(t r u e && (t r u e || f a l s e) ) ; // f a l s e

What if we do not want our variable values to change? There is a way, with the final keyword:

f i n a l int NUM = 1 0 0 ; // c o n v e n t i o n : all c a p i t a l l e t t e r s for f i n a l v a r i a b l e s

// NUM ++; // c o m p i l a t i o n e r r o r

4.6 String

Now that we fully understand how primitive data types work, we can move on to using classes provided by the Java API (Application Programmer Interface). One such class is provided in the Java package java.lang, called String. This package is so often that Java automatically imports it for you, so the programmer does not have to do extra work.

A String is a set of characters in between double quotes. Any character can be inside a string, except for a double quote. Examples are:

S t r i n g s t r 1 = " I l o v e "; S t r i n g s t r 2 = " J a v a "; S t r i n g s t r 3 = s t r 1 + s t r 2 ; // is now " I l o v e J a v a " // s t r 3 is c a l l e d the " c o n c a t e n a t i o n " of s t r 1 and s t r 2 int i1 = 3; s t r 3 = s t r 1 + i1 ; // has v a l u e " I l o v e 3 "

However, there is another way to declare a String variable, and that is done using the Java keyword new:

S t r i n g s t r 1 = new S t r i n g (" I l o v e ") ; // s a m e as a b o v e

String is the only Java class that can declare (also called “instantiate”) a variable without the new keyword. All other Java classes must be instantiated with this keyword.

Now we need to see what we can do with these String variables. As we covered in the last chapter, every Java class has one or more methods. The syntax for calling a method is:

variable.methodname(optionalparameters)

Note: we cannot call methods on primitive data types (see later chapters on classes and methods). Examples of various methods in Java for the String class are:

S t r i n g s t r 1 = " I l o v e J a v a "; /* S t r i n g . t o U p p e r C a s e () and t o L o w e r C a s e */ S t r i n g u p p e r = s t r 1 . t o U p p e r C a s e () ; // " I L O V E J A V A " S t r i n g l o w e r = s t r 1 . t o L o w e r C a s e () ; // " i l o v e j a v a " /* S t r i n g . r e p l a c e ( c h a r c , c h a r d ) */ // R e p l a c e s all i n s t a n c e s of c w i t h d S t r i n g r e p l = s t r 1 . r e p l a c e (’ a ’, ’ p ’) ; // " I l o v e J p v p "

(13)

// We can e v e n c h a i n m e t h o d c a l l s

S t r i n g m y s t = s t r 1 . r e p l a c e (’ a ’, ’ p ’) . t o U p p e r C a s e () ; // " I L O V E J P V P " /* S t r i n g . l e n g t h () - int w h i c h is # of c h a r a c t e r s */

int len = s t r 1 . l e n g t h () ; // 11 , s i n c e t h e r e are 11 c h a r a c t e r s /* S t r i n g . c h a r A t ( int n ) - g e t s the nth c h a r a c t e r */

// S t r i n g s are 0 - indexed , so the f i r s t c h a r a c t e r is at i n d e x 0 // E r r o r at r u n t i m e if i n p u t >= l e n g t h () c h a r f i r s t C h a r = s t r 1 . c h a r A t (0) ; // has v a l u e ’ I ’ c h a r s e c o n d C h a r = s t r 1 . c h a r A t (1) ; // has v a l u e ’ ’ c h a r l a s t C h a r = s t r 1 . c h a r A t ( str . l e n g t h () -1) ; // ’ a ’ /* S t r i n g . s u b s t r i n g ( int n , int m ) */ // g i v e s a S t r i n g t h a t c o n s i s t s of i n d e x n t h r o u g h m , not i n c l u s i v e on m S t r i n g s u b s t r 1 = s t r 1 . s u b s t r i n g (0 , 3) ; // " I lo " S t r i n g s u b s t r 2 = s t r 1 . s u b s t r i n g (2 , 6) ; // " l o v e " /* S t r i n g . e q u a l s ( S t r i n g o t h e r ) */ // g i v e s t r u e ( b o o l e a n ) if the f i r s t S t r i n g is e x a c t l y the s a m e as the o t h e r b o o l e a n e q u a l 1 = s u b s t r 1 . e q u a l s ( s u b s t r 2 ) ; // f a l s e b o o l e a n e q u a l 2 = " E q u a l ". e q u a l s (" E q u a l ") ; // t r u e // We can a l s o c h e c k for e q u a l i t y i g n o r i n g the c a s e

b o o l e a n e q u a l 3 = " E q u a l ". e q u a l s I g n o r e C a s e (" e q U a l ") ; // t r u e /* S t r i n g . i n d e x O f ( c h a r c ) */ // R e t u r n s i n d e x ( int ) of the f i r s t i n s t a n c e of c ; o t h e r w i s e , -1 int f o u n d 1 = s t r 1 . i n d e x O f (’ o ’) ; // 4 int f o u n d 2 = s t r 1 . i n d e x O f (’ f ’) ; // -1 /* S t r i n g . c o m p a r e T o ( S t r i n g o t h e r ) */ // R e t u r n s int s h o w i n g l e x i c o g r a p h i c o r d e r i n g of s t r i n g s a c c o r d i n g to A S C I I t a b l e ( n e g a t i v e if f i r s t < second , 0 if equal , p o s i t i v e if f i r s t > s e c o n d ) int c1 = " A ". c o m p a r e T o (" B ") ; // n e g a t i v e int c2 = " A ". c o m p a r e T o (" b ") ; // m o r e n e g a t i v e , l o w e r c a s e has h i g h e r A S C I I v a l u e int c3 = " A ". c o m p a r e T o (" A ") ; // 0 int c4 = " B ". c o m p a r e T o (" A ") ; // p o s i t i v e 4.7 Scanner

Now that we know how to create and modify modify String variables, it is important to know how to get input from the user so that we can make our programs usable. For that, we use the Scanner class in the java.util package.

(14)

However, since this class is not in the package java.lang, we must import it from the Java library, by putting an import statement at the beginning of our file:

i m p o r t j a v a . u t i l . S c a n n e r ; // i m p o r t the S c a n n e r c l a s s f r o m the j a v a . u t i l p a c k a g e // E q u i v a l e n t : i m p o r t j a v a . u t i l .*; // i m p o r t e v e r y t h i n g f r o m t h i s p a c k a g e p u b l i c c l a s s S o m e C l a s s { // ... }

So how do we use this class? We must initialize it with the new keyword:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; // S y s t e m . in m e a n s f r o m the k e y b o a r d

This code creates an variable (often called “object” in this case, since it is a class) in which we can call various methods on it to get input from the user. There are various ways of getting input from the user:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

int x = s . n e x t I n t () ; // the f i r s t i n t e g e r e n t e r e d by the u s e r ( a f t e r p u s h i n g the e n t e r / r e t u r n key ) w i l l be put i n t o x

// If an i n t e g e r is not entered , t h e n a run - t i m e e r r o r w i l l o c c u r . d o u b l e y = s . n e x t D o u b l e () ; // if a u s e r e n t e r s a d o u b l e S t r i n g s t r 1 = s . n e x t () ; // t h i s is the n e x t " w o r d " ( d o e s not i n c l u d e s p a c e s ) S t r i n g s t r 2 = s . n e x t L i n e () ; // t h i s is the e n t i r e l i n e of c h a r a c t e r s b e f o r e p r e s s i n g the e n t e r / r e t u r n key 4.8 Math

There is another class, called Math (in the java.lang package) that provides some useful function-alities: /* S q u a r e r o o t */ d o u b l e n u m 1 = 1 0 5 . 0 ; d o u b l e d1 = M a t h . s q r t ( n u m 1 ) ; /* PI - c o n s t a n t */ d o u b l e pi = M a t h . PI ; /* M a t h .{ min , max } - m i n i m u m or m a x i m u m of 2 i n t s */ int n u m 1 = 5 , n u m 2 = 3;

int max = M a t h . max ( num1 , n u m 2 ) ; // 5 // a l s o can be : M a t h . max ( num2 , n u m 1 ) ; int min = M a t h . min ( num1 , n u m 2 ) ; // 3

/* Pow - t a k e f i r s t d o u b l e to p o w e r of s e c o n d */ d o u b l e d2 = 3.5 , d3 = 4 . 3 ;

(15)

4.9 Written Exercises

1. Give the output of the following program:

p u b l i c c l a s s E x a m p l e { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { int y = 2 , z = 1; z = y * 2; S y s t e m . out . p r i n t ( y + z ) ; } }

2. What will be the output of the following program?

p u b l i c c l a s s E x a m p l e { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { S t r i n g s = new S t r i n g (" A r i z o n a s t a t e u n i v e r s i t y ") ; c h a r ch1 = s . t o L o w e r C a s e () . t o U p p e r C a s e () . c h a r A t (0) ; c h a r ch2 = s . t o U p p e r C a s e () . c h a r A t (8) ; c h a r ch3 = s . t o U p p e r C a s e () . c h a r A t ( s . l e n g t h () - 1) ; S y s t e m . out . p r i n t l n (" ch 1 is : " + ch1 ) ; S y s t e m . out . p r i n t l n (" ch 2 is : " + ch2 ) ; S y s t e m . out . p r i n t l n (" ch 3 is : " + ch3 ) ; } }

3. What will be the output of the following program?

p u b l i c c l a s s E x a m p l e { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { int n u m 1 = 4 , n u m 2 = 5; S y s t e m . out . p r i n t l n (" 4 "+" 5 ") ; S y s t e m . out . p r i n t l n ( n u m 1 + n u m 2 ) ; S y s t e m . out . p r i n t l n (" n u m 1 "+" n u m 2 ") ; S y s t e m . out . p r i n t l n ( 4 + 5 ) ; } }

4. Which of the following correctly invokes the method length() of the String variable str and stores the result in val of type int?

int val = str . l e n g t h () ;

int val = l e n g t h . str () ;

int val = l e n g t h () . str ;

int val = l e n g t h ( str ) ;

5. Evaluate each of the following expressions. S t r i n g s = " P r o g r a m m i n g is Fun "; S t r i n g t = " W o r k s h o p is c o o l ";

S y s t e m . out . p r i n t l n ( s . c h a r A t (0) + t . s u b s t r i n g (3 , 4) ) ; S y s t e m . out . p r i n t l n ( t . s u b s t r i n g (7) ) ;

(16)

6. Evaluate each of the following expressions, assuming j is an int with value 11, k is an int with value 3, and s is a String with value “Ford Rivers”.

j / k j % k

s . s u b s t r i n g (1 , 5) s . l e n g t h ()

s . c h a r A t (3)

7. True or False? The type String is a primitive data type. 8. True or False? The type char is a primitive data type. 9. Write the output of the following program:

p u b l i c c l a s s Q u e s t i o n { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { S t r i n g str = " h e l l o "; S y s t e m . out . p r i n t l n (" a b c d e f ". s u b s t r i n g (1 , 3) ) ; S y s t e m . out . p r i n t l n (" p i z z a ". l e n g t h () ) ; S y s t e m . out . p r i n t l n ( str . r e p l a c e (’ h ’, ’ m ’) ) ; S y s t e m . out . p r i n t l n (" h a m b u r g e r ". s u b s t r i n g (0 , 3) ) ; S y s t e m . out . p r i n t l n ( str . c h a r A t (1) ) ; S y s t e m . out . p r i n t l n ( str . e q u a l s (" h e l l o ") ) ; S y s t e m . out . p r i n t l n (" p i z z a ". t o U p p e r C a s e () ) ; S y s t e m . out . p r i n t l n ( M a t h . pow (2 , 4) ) ; d o u b l e n u m 4 = M a t h . s q r t ( 1 6 . 0 ) ; S y s t e m . out . p r i n t l n ( n u m 4 ) ; } }

10. Write the output of the following program:

p u b l i c c l a s s Q u e s t i o n { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { S t r i n g s1 = " Clinton , H i l l a r y "; S t r i n g s2 = new S t r i n g (" Obama , B a r a c k ") ; S y s t e m . out . p r i n t l n ( s1 . c h a r A t (2) ) ; S y s t e m . out . p r i n t l n ( s1 . c h a r A t ( s1 . l e n g t h () -1) ) ; S y s t e m . out . p r i n t l n ( s2 . t o U p p e r C a s e () ) ; S y s t e m . out . p r i n t l n ( s2 . s u b s t r i n g ( s2 . i n d e x O f (" , ") +2 , s2 . l e n g t h () ) ; } }

11. What value is contained in the int variable length after the following statements are executed? l e n g t h = 2;

l e n g t h *= 9; l e n g t h -= 6;

(17)

4.10 Programming Exercises

1. Write a Java program that asks the user for the radius of a circle and finds the area of the circle.

2. Write a Java program that prompts the user to enter 2 integers. Print the smaller of the 2 integers.

(18)

Decisions

Note: all code snippets from here on are assumed to be in a main method (they will not compile if not).

5.1 Motivation

We now know basic data types and how to use them. Now, we will see how to execute conditional code based on values. We will cover if, if-else, and switch statements.

5.2 If Statements

Suppose we were given a task of printing “True” only when a value entered by the user was larger than another value. Currently, we do not know of a way to do this. Therefore, we have if statements. They have the form:

if (condition){...}

where “...” means other lines of code, and condition is evaluated to a boolean value. The rule for if statements is: if the condition evaluates to true, then the code between the braces is executed; if false, then it is not executed. If we have one line of code that will be executed in the if statement, then the braces are optional:

int x = 8;

if ( x > 7)

S y s t e m . out . p r i n t (" T h i s one l i n e ") ;

However, the second line after the if statement in the following example will not execute as if it were in the if statement, even though it is indented:

int x = 8;

if ( x > 7)

S y s t e m . out . p r i n t (" T h i s one l i n e ") ;

S y s t e m . out . p r i n t l n (" W h a t a b o u t t h i s l i n e ? ") ; The above code is functionally equivalent to:

int x = 8;

if ( x > 7) {

S y s t e m . out . p r i n t (" T h i s one l i n e ") ; }

S y s t e m . out . p r i n t l n (" W h a t a b o u t t h i s l i n e ? ") ; // a l w a y s p r i n t s

To fix this, we add braces:

int x = 8;

if ( x > 7) {

S y s t e m . out . p r i n t (" T h i s one l i n e ") ;

S y s t e m . out . p r i n t l n (" W h a t a b o u t t h i s l i n e ? ") ; }

(19)

and therefore, both lines will print if the condition evaluates to true (which it does in this case). Now suppose we want to execute some code when the condition is true, and some other code when the condition is false (and only when it is false). Therefore, we need an if-elsestatement, which is of the form:

if (condition){...}else{...}

If the condition is false, then the code in the else section will automatically execute, and the code in the if section will not. If the condition is true, then the else section will not execute, and the if section will.

Suppose we have been given a task of printing “true” if the user’s input is greater than or equal to 8, and “false” otherwise. Our code then will look like:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; int i n p u t = s . n e x t I n t () ; if ( i n p u t >= 8) { S y s t e m . out . p r i n t (" t r u e ") ; } e l s e { S y s t e m . out . p r i n t (" f a l s e ") ; }

We can even chain multiple if-else statements together (and even nested ones!): S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; int i n p u t = s . n e x t I n t () ; if ( i n p u t >= 8) { if ( i n p u t == 8) { S y s t e m . out . p r i n t (" E q u a l to 8 ") ; } e l s e { S y s t e m . out . p r i n t (" L a r g e r t h a n 8 ") ; } } e l s e if ( i n p u t >= 4) { if ( i n p u t == 4) { S y s t e m . out . p r i n t (" E q u a l to 4 ") ; } e l s e { S y s t e m . out . p r i n t (" L a r g e r t h a n 4 , < 8 ") ; } } e l s e { S y s t e m . out . p r i n t (" L e s s t h a n 4 ") ; } 5.3 Switch Statements

An alternative to if-else statements are switch statements, because if-else statements can be very complex and lengthy. A switch statement structure consists of 1 or more case statements (with an optional default case). The programmer supplies a switch statement with a value:

s w i t c h( v a l u e ) {

// ...

(20)

where value is a primitive type or a String (Note: String is only allowed in later versions of Java). For each of the case statements, value is compared to the value supplied in the case statement (see form below). Only if they are equal will the code after the case statement be executed.

– Each case statement is of the form: case value: /* statements */. At the end of the code section for a case statement, an optional break; statement is allowed. However, not putting this statement at the end of the code section for the case statement will immediately execute the next case statement, regardless of the value.

– An optional default: case statement at the end of the switch block is allowed, which is executed if the input value is not equal to any other case statement’s value.

For example, if we were to print “1” if the input value is equal to 1, and “2” if equal to 2, and ignore any other inputs, our code might look like:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; int i n p u t = s . n e x t I n t () ; s w i t c h( i n p u t ) { c a s e 1: S y s t e m . out . p r i n t (" 1 ") ; b r e a k; c a s e 2: S y s t e m . out . p r i n t (" 2 ") ; b r e a k; }

Now, if we remove the break statements:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; int i n p u t = s . n e x t I n t () ; s w i t c h( i n p u t ) { c a s e 1: S y s t e m . out . p r i n t (" 1 ") ; c a s e 2: S y s t e m . out . p r i n t (" 2 ") ; }

this code will output “12” if the input is 1, and “2” if the input is 2, which is not the behavior we might want. This is because we removed the break statements, and so the code flows through until it hits a break statement. What a break statement does is exit the switch statement altogether.

On the other hand, if we want to add the requirement of printing “other” if we have any other value than 1 or 2, then we use a default statement:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; int i n p u t = s . n e x t I n t () ; s w i t c h( i n p u t ) { c a s e 1: S y s t e m . out . p r i n t (" 1 ") ; b r e a k; c a s e 2: S y s t e m . out . p r i n t (" 2 ") ; b r e a k;

(21)

d e f a u l t:

S y s t e m . out . p r i n t (" o t h e r ") ;

b r e a k; }

We can see that this code can be constructed in an if-else statement fashion. However, sometimes switch and case statements are easier to understand and read.

5.4 Written Exercises

1. What is the output of the following code?

int d e p t h = 30;

if ( d e p t h >= 29) {

S y s t e m . out . p r i n t (" B i g g e r t h a n 8! ") ; S y s t e m . out . p r i n t (" Don ’ t s w i m ! ") ; }

S y s t e m . out . p r i n t l n (" Yes , you can s w i m . ") ; 2. What is the output of the following code?

int m y s t e r y 1 = 12; int m y s t e r y 2 = 42; S y s t e m . out . p r i n t (" You h a v e : ") ; if ( m y s t e r y 1 >= 8) S y s t e m . out . p r i n t (" 1 ") ; if ( m y s t e r y 2 <= 50 && m y s t e r y 1 <= 12) S y s t e m . out . p r i n t (" 2 ") ; S y s t e m . out . p r i n t l n (" 3. ") ;

3. If k holds a value of the type int, then the value of the expression: k <= 10 || k > 10

a) must be true b) must be false

c) could be either true or false d) is a value of type int

4. For the following code, fill in the missing condition to check if str1 and str2 are the same. S t r i n g s t r 1 = " J a v a is fun ";

S t r i n g s t r 2 = " J a v a is fun ";

if ( /* */ )

S y s t e m . out . p r i n t l n (" S t r i n g 1 and S t r i n g 2 are the s a m e ") ;

e l s e

S y s t e m . out . p r i n t l n (" S t r i n g 1 and S t r i n g 2 are d i f f e r e n t ") ; 5. Evaluate the following expressions, assuming that x = -2 and y = 3.

x <= y

( x < 0) || ( y < 0) ( x <= y ) && ( x < 0)

(22)

6. Write the output of the following code: int g r a d e = 45; if ( g r a d e >= 70) S y s t e m . out . p r i n t l n (" p a s s i n g ") ; if ( g r a d e < 70) S y s t e m . out . p r i n t l n (" d u b i o u s ") ; if ( g r a d e < 60) S y s t e m . out . p r i n t l n (" f a i l i n g ") ; 7. Write the output of the following code:

S t r i n g o p t i o n = " A ";

if ( o p t i o n . e q u a l s (" A ") )

S y s t e m . out . p r i n t l n (" a d d R e c o r d ") ;

if ( o p t i o n . c o m p a r e T o (" A ") == 0)

S y s t e m . out . p r i n t l n (" d e l e t e R e c o r d ") ; 8. Write the output of the following code:

d o u b l e x = -1.5; if ( x < -1.0) S y s t e m . out . p r i n t l n (" t r u e ") ; e l s e S y s t e m . out . p r i n t l n (" f a l s e ") ; S y s t e m . out . p r i n t l n (" a f t e r if ... e l s e ") ; 9. Write the output of the following code:

int j = 8; d o u b l e x = -1.5; if ( x >= j ) S y s t e m . out . p r i n t l n (" x is h i g h ") ; e l s e S y s t e m . out . p r i n t l n (" x is low ") ; 10. Write the output of the following code:

d o u b l e x = -1.5; if ( x <= 0 . 0 ) { if ( x < 0 . 0 ) S y s t e m . out . p r i n t l n (" neg ") ; e l s e S y s t e m . out . p r i n t l n (" z e r o ") ; } e l s e S y s t e m . out . p r i n t l n (" pos ") ; 5.5 Programming Exercises

1. Write a program that asks for 3 integers and prints the median value of the 3 integers, using only if statements.

(23)
(24)

Loops

6.1 Motivation

With the last chapter, we now know how to execute conditional code. This chapter will greatly increase our powers in what we can do with programming, by being able to execute code many times without having to re-write (or copy and paste) code over and over.

6.2 Introduction to Loops

Loops are a way of executing some code an arbitrary number of times. What determines the number of times a loop executes is based largely on a condition, just like if and switch statements were. There are 3 kinds of loops in Java:

– while loops – do-while loops – for loops 6.3 While loops

while loops are the simplest to understand kind of loop. The structure of one is: while(condition){...}

The semantics are: the loop will continue as long as the condition evaluates to true. The main reason while loops are used is that we may not know the number of times looping occurs. If we do, we usually use a for loop (see below). However, both while and for loops can be converted back and forth.

For example, let’s say we are given a task of displaying a positive integer that the user enters, and continue doing so until the user enters 0. Setting up is easy:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

w h i l e(/* s o m e t h i n g */) {

// s o m e h o w t a k e u s e r i n p u t and d i s p l a y it

}

Let’s initialize an int variable, initialized to the first input a user gives: S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; S y s t e m . out . p r i n t l n (" E n t e r an i n t e g e r : ") ; int i n p u t = s . n e x t I n t () ; w h i l e(/* s o m e t h i n g */) { // s o m e h o w t a k e u s e r i n p u t and d i s p l a y it }

Now, we need to create the condition for the while loop. We stop after the user enters 0, so let’s make that condition (and display it):

(25)

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; S y s t e m . out . p r i n t l n (" E n t e r an i n t e g e r : ") ; int i n p u t = s . n e x t I n t () ; w h i l e( i n p u t != 0) { S y s t e m . out . p r i n t l n ( i n p u t ) ; // a n y t h i n g e l s e go h e r e ? }

This code seems good, but unfortunately we can encounter what is called an “infinite loop”, which does not stop looping. If we enter a non-zero integer, then we print that output. Then since there is nothing else to do in the loop body, we check the condition again, which evaluates to true, prints out, loops back, prints out, etc. We need to get the user input again at the end of the loop:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; S y s t e m . out . p r i n t l n (" E n t e r an i n t e g e r : ") ; int i n p u t = s . n e x t I n t () ; w h i l e( i n p u t != 0) { S y s t e m . out . p r i n t l n ( i n p u t ) ; S y s t e m . out . p r i n t l n (" E n t e r a n o t h e r i n t e g e r : ") ; i n p u t = s . n e x t I n t () ; // a v o i d i n f i n i t e l o o p }

Now our solution code for the example is correct. 6.4 Do-While loops

do-while loops are the same as while loops, but guarantee that the loop body will be executed at least once. Remember our earlier while loop example: if we initially entered 0, then the loop’s condition evaluates to false, and does not execute the body. Therefore, it loops 0 times.

The structure of a do-while loop is:

do{...}while(condition);

Note: the semicolon after the last parentheses of the while’s condition is necessary. For example, if we modify our example from above to be a do-while loop, we guarantee that the user must enter at least one integer:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ; S y s t e m . out . p r i n t l n (" E n t e r an i n t e g e r : ") ; int i n p u t = s . n e x t I n t () ; do { S y s t e m . out . p r i n t l n ( i n p u t ) ; S y s t e m . out . p r i n t l n (" E n t e r a n o t h e r i n t e g e r : ") ; i n p u t = s . n e x t I n t () ; // a v o i d i n f i n i t e l o o p } w h i l e( i n p u t != 0) ; 6.5 For loops

for loops are used when we know precisely how many times the loop will execute. However, they are equivalent in functionality to while loops (i.e. one can construct a for loop from a while loop, and vice versa). All for loops have the same structure:

(26)

f or(initialization; condition; modif ication){...} – Initialization - creating a variable, usually called the “loop control” variable.

– Condition - checking a condition, usually related to the loop control variable, against some value. The loop will continue to iterate (and do the modification step) as long as the condition is true.

– Modification - modify, usually the loop control variable, at each iteration of the loop.

For example, let’s say we are given the problem of summing all of the integers from 1 to n, where n is an integer ≥ 1. An example solving this problem is the following:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

int n = s . n e x t I n t () ;

int sum = 0;

// put s o m e k i n d of for l o o p h e r e

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

Now we need to reason how to construct our for loop. Let’s initialize a loop control variable, called i, to be 1. Then, for each iteration of the loop, add i to sum, and at each iteration, add 1 to i. An “unraveling” of the loop’s logic will be this:

– sum = 0.

– 1st iteration of loop: i = 1, add to sum, sum = 1, add 1 to i (i = 2). – 2nd iteration of loop: i = 2, add to sum, sum = 3, add 1 to i (i = 3). – 3rd iteration of loop: i = 3, add to sum, sum = 6, add 1 to i (i = 4).

and so on. By this logic, we want the loop to stop at n, inclusive. So, we need to have a condition of i <= n. And on each loop, we execute i++. Therefore, our final code will be:

S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

int n = s . n e x t I n t () ;

int sum = 0;

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

sum += i ; // add to sum

}

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

6.6 Loop Example

In many programming interviews, there are questions designed to test one’s knowledge of loops. One of them is called “FizzBuzz.” The idea is this: print “Fizz” if the number is divisible by 3, “Buzz” if the number is divisible by 5, “FizzBuzz” if the number is divisible by 3 and 5 (i.e., 15), and nothing otherwise. Now, we want the user to input an integer n, and from 1 to n, we want to print the appropriate value. We start with a setup of our program:

p u b l i c c l a s s F i z z B u z z {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) {

// s o m e t h i n g g o e s h e r e ...

} }

(27)

Now we need to add appropriate code to get an integer n from the user:

i m p o r t j a v a . u t i l . S c a n n e r ;

p u b l i c c l a s s F i z z B u z z {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

int n = s . n e x t I n t () ; // get the i n t e g e r

} }

Since we know the number of loop iterations (i.e., n), we can just use a for loop to iterate from 1 to n:

i m p o r t j a v a . u t i l . S c a n n e r ;

p u b l i c c l a s s F i z z B u z z {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

int n = s . n e x t I n t () ; // get the i n t e g e r for (int i = 1; i <= n ; i ++) {

// w h a t e l s e ?

} }

}

Now we just need to insert an if and else statements to check if n is divisible by 3, 5, or 15 (and then print the appropriate value). However, we cannot just do this:

i m p o r t j a v a . u t i l . S c a n n e r ;

p u b l i c c l a s s F i z z B u z z {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

int n = s . n e x t I n t () ; // get the i n t e g e r for (int i = 1; i <= n ; i ++) { if ( i % 3 == 0) { S y s t e m . out . p r i n t l n (" F i z z ") ; } e l s e if ( i % 5 == 0) { S y s t e m . out . p r i n t l n (" B u z z ") ; } e l s e if ( i % 15 == 0) { S y s t e m . out . p r i n t l n (" F i z z B u z z ") ; } } } }

The last clause will never be reached. If i is divisible by 15, then it is divisible by 3 or 5 as well. Therefore, it would have went inside one of the other conditionals. Therefore, we just need to move it to be the first conditional:

i m p o r t j a v a . u t i l . S c a n n e r ;

p u b l i c c l a s s F i z z B u z z {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { S c a n n e r s = new S c a n n e r ( S y s t e m . in ) ;

(28)

int n = s . n e x t I n t () ; // get the i n t e g e r for (int i = 1; i <= n ; i ++) { if ( i % 15 == 0) { S y s t e m . out . p r i n t l n (" F i z z B u z z ") ; } e l s e if ( i % 3 == 0) { S y s t e m . out . p r i n t l n (" F i z z ") ; } e l s e if ( i % 5 == 0) { S y s t e m . out . p r i n t l n (" B u z z ") ; } } } }

There are other ways to do this - for example, we can just have the last 2 conditionals, but use print instead of println, and then add a newline afterwards.

6.7 Written Exercises

1. What are the 3 kinds of loops in Java?

2. What is the output of the following loop? How many times does the loop execute?

int n = 9 7 9 ;

for (int j = 0; j <= n ; j ++) { S y s t e m . out . p r i n t l n (" H e l l o ") ; }

3. What is the output of the following loop? How many times does the loop execute?

int j = 1; int n = 5; w h i l e ( j <= n ) { S y s t e m . out . p r i n t l n (" H e l l o ") ; n - -; }

4. What is the output of the following loop? How many times does the loop execute?

int n = 5; for (int j = 1; j <= n ; j += 3) { S y s t e m . out . p r i n t (" H e l l o ") ; int k = j ; w h i l e ( k < n ) { S y s t e m . out . p r i n t l n (" G o o d M o r n i n g ") ; k ++; } j - -; }

(29)

S t r i n g n a m e = " R i c h a r d M . N i x o n "; b o o l e a n s t a r t W o r d = t r u e; for (int i = 0; i < n a m e . l e n g t h () ; i ++) { if ( s t a r t W o r d ) S y s t e m . out . p r i n t l n ( n a m e . c h a r A t ( i ) ) ; if ( n a m e . c h a r A t ( i ) == ’ ’) s t a r t W o r d = t r u e; e l s e s t a r t W o r d = f a l s e; }

6. What is the output of the following loop? How many times does the loop execute?

int j = 1;

w h i l e ( j <= 11) {

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

}

7. What is the output of the following code?

int n = 1 , i = 1; w h i l e ( i < 7) { n = n * i ; i += 2; } S y s t e m . out . p r i n t ( n ) ; 6.8 Programming Exercises

1. Write a loop that reads in int values until the user enters 0 and prints out how many values entered are greater than 10.

2. Write a loop that will print out every other letter in a String variable called str. For example, if the String was “Hello There”, then “HloTee” will be printed.

(30)

Introduction to Classes

7.1 Motivation

Now that we understand how loops work, we want to be able to create our own classes! Just like the ones that we have been using, such as Scanner, String, Math, and others.

7.2 Class Structure

A class follows the same format as we have been for our main programs. However, there does not have to be a main method in a class. The only requirement for main is that the class we run a program from contains a main method.

A class contains what are called “instance variables”, a constructor, and 1 or more methods. But before we can talk about these, we need to cover visibility modifiers.

7.3 Visibility Modifiers

We have been using public when we create our programs so far. Now we will cover what this means, and what other visibility modifiers are. They are, for any variable/method/class:

– public - any class can see it.

– private - only the class that contains it can see it.

– protected - only the class that contains it and any children that inherit from it can see it. Do not worry about this visibility modifier - we will not use it in this chapter.

7.4 Instance Variables

Instance variables are variables that exist inside a class when they are created. We usually write instance variables to have a visibility of private, to enforce what is called “encapsulation”, which means that we hide data (the instance variables) that we do not want “outsiders” to change.

For example, let’s create a BankAccount class:

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

In order to make an instance of the class, we need to create a “constructor” for the class, which executes code inside it when we use the new operator on the class, in the exact same way that we have used it for other Java-provided classes. Notes about the constructor:

– No return type – Optional parameters

– Any number of constructors allowed as long as they differ in signature (number of arguments or different types of arguments).

(31)

– The default constructor–with no arguments–is provided by Java if none is provided by the programmer.

For example, let’s modify our BankAccount class that has the name of the person with the account, and a starting balance. When we initialize our BankAccount object in the main method, we will use the new operator, which passes in the values supplied to name and startAmount below:

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

// v i s i b i l i t y of p u b l i c - n e e d to see o u t s i d e of c l a s s p u b l i c B a n k A c c o u n t ( S t r i n g name , d o u b l e s t a r t A m o u n t ) { }

}

Now what do we do with these parameters? We need a way of “saving” them inside the class for later use. That is where instance variables come in. Let’s create our instance variables with public visibility for now:

p u b l i c c l a s s B a n k A c c o u n t { p u b l i c S t r i n g p e r s o n N a m e ; p u b l i c d o u b l e b a l a n c e ; // v i s i b i l i t y of p u b l i c - n e e d to see o u t s i d e of c l a s s p u b l i c B a n k A c c o u n t ( S t r i n g name , d o u b l e s t a r t A m o u n t ) { p e r s o n N a m e = n a m e ; // set n a m e b a l a n c e = s t a r t A m o u n t ; // set a m o u n t // o p t i o n a l : use t h i s o p e r a t o r // t h i s . p e r s o n N a m e = n a m e ; // t h i s r e f e r e n c e s the B a n k A c c o u n t c l a s s w h e n i n s i d e the class , and w h a t c o m e s a f t e r the dot r e f e r e n c e s the i n s t a n c e v a r i a b l e w i t h t h a t n a m e

} }

And in our main (or other that instantiates a BankAccount object) method:

p u b l i c c l a s s B a n k A c c o u n t T e s t {

p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) {

B a n k A c c o u n t b = new B a n k A c c o u n t (" J a n e ", 0 . 0 ) ; }

}

Since we have declared our instance variables as public, we can modify the corresponding values of our instance to anything we want by using the “dot” operator, in the same way we use Math.PI on the Math class:

p u b l i c c l a s s B a n k A c c o u n t T e s t { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { B a n k A c c o u n t b = new B a n k A c c o u n t (" J a n e ", 0 . 0 ) ; b . p e r s o n N a m e = " A n o t h e r N a m e "; b . b a l a n c e = 5 0 0 0 0 0 ; } }

(32)

We can clearly see why this is not preferred. Therefore, we need to mark the visibility of our instance variables as private (and the operations above will result in a compile-time error):

p u b l i c c l a s s B a n k A c c o u n t { p r i v a t e S t r i n g p e r s o n N a m e ; p r i v a t e d o u b l e b a l a n c e ; p u b l i c B a n k A c c o u n t ( S t r i n g name , d o u b l e s t a r t A m o u n t ) { p e r s o n N a m e = n a m e ; // set n a m e b a l a n c e = s t a r t A m o u n t ; // set a m o u n t } }

This is a good start, but we want to be able to deposit or withdraw some amount into balance. Therefore, we need to use “setters” (also called “mutators”) and “getters” (also called “accessors”). Setters are about changing some internal value to a passed-in value, and getters are about getting internal values back to the user:

p u b l i c c l a s s B a n k A c c o u n t { p r i v a t e S t r i n g p e r s o n N a m e ; p r i v a t e d o u b l e b a l a n c e ; p u b l i c B a n k A c c o u n t ( S t r i n g name , d o u b l e s t a r t A m o u n t ) { p e r s o n N a m e = n a m e ; // set n a m e b a l a n c e = s t a r t A m o u n t ; // set a m o u n t } /* G e t t e r s h a v e the f o r m : p u b l i c < Type > get < N a m e O f V a r >() { r e t u r n < N a m e O f V a r >; } */ // get the c u r r e n t b a l a n c e p u b l i c d o u b l e g e t B a l a n c e () { r e t u r n b a l a n c e ; } /* S e t t e r s h a v e the f o r m : p u b l i c v o i d set < N a m e O f V a r >( < Type > o t h e r ) { < I n s t a n c e Var > = o t h e r ; } */

// set the b a l a n c e to the i n p u t

(33)

b a l a n c e = o t h e r ; }

}

But this introduces the same problem as earlier - we can make our balance be any value we want. Therefore, we should get rid of the setter, and introduce a deposit method, which adds to the balance with the input. We can leave the getter because it does not modify the value of balance.

p u b l i c c l a s s B a n k A c c o u n t { p r i v a t e S t r i n g p e r s o n N a m e ; p r i v a t e d o u b l e b a l a n c e ; p u b l i c B a n k A c c o u n t ( S t r i n g name , d o u b l e s t a r t A m o u n t ) { p e r s o n N a m e = n a m e ; // set n a m e b a l a n c e = s t a r t A m o u n t ; // set a m o u n t } // get the c u r r e n t b a l a n c e p u b l i c d o u b l e g e t B a l a n c e () { r e t u r n b a l a n c e ; } p u b l i c v o i d d e p o s i t (d o u b l e a m o u n t ) { b a l a n c e += a m o u n t ; } }

And in main, we can use these methods accordingly:

p u b l i c c l a s s B a n k A c c o u n t T e s t { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { B a n k A c c o u n t b = new B a n k A c c o u n t (" J a n e ", 0 . 0 ) ; b . d e p o s i t ( 5 0 . 0 ) ; S y s t e m . out . p r i n t ( b . g e t B a l a n c e () ) ; } }

Notes about classes:

– A method (terminology to be covered in the next chapter) called toString, which returns a String, is commonly implemented among programmer-created classes. The returned String is a textual description of the state of the class and instance variables. For instance, we could use our BankAccount class and create a toString method that returns:

Name: Jane Balance: 50.0

with the following code:

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

// r e t u r n t e x t u a l d e s c r i p t i o n

(34)

t o R e t u r n += " N a m e : " + p e r s o n N a m e ; t o R e t u r n += " \ n ";

t o R e t u r n += " B a l a n c e : " + b a l a n c e ;

r e t u r n t o R e t u r n ; }

And when the object is printed out, even without calling .toString(), the textual description will be printed: // in m a i n B a n k A c c o u n t b = . . . ; S y s t e m . out . p r i n t ( b ) ; // c a l l s t o S t r i n g () a u t o m a t i c a l l y // e q u i v a l e n t to : S y s t e m . out . p r i n t ( b . t o S t r i n g () ) ;

Note: Not providing a toString() method in a class, when printing an instance, will print a hash value (i.e. random letters and numbers) instead of what is expected, along with the name of the class.

7.5 Written Exercises

1. Which of the following enforces Encapsulation? a) Make instance variables private

b) Make methods public c) Make the class final d) Both a and b

e) All of the above

2. Use the following class to answer the questions below:

p u b l i c c l a s s S t o r e { p r i v a t e int q u a n t i t y ; p r i v a t e d o u b l e p r i c e ; p u b l i c S t o r e (int q , d o u b l e p ) { q u a n t i t y = q ; p r i c e = p ; } p u b l i c int g e t Q u a n t i t y () { r e t u r n q u a n t i t y ; } p u b l i c v o i d s e t P r i c e (d o u b l e p ) { p r i c e = p ; } p u b l i c d o u b l e c a l c T o t a l () { r e t u r n p r i c e * q u a n t i t y ; } }

(35)

a) What is the name of the class? b) List all instance variables of the class.

c) List all methods of the class. d) List all mutators in the class.

e) List all accessors in the class.

f) List which method is the constructor.

3. True or False? If no constructor is provided, then Java automatically provides a default con-structor.

4. True or False? A method must have at least 1 return statement. 7.6 Programming Exercises

1. For the Store class in the Written Exercises above, do the following: a) Write a mutator for the quantity.

b) Write an accessor for the price.

c) Write a line of code that will create an instance called videoStore that has quantity 100 and a price of 5.99.

d) Call the calcTotal method with the videoStore object (from part c) to print out the total. 2. Correct the following class definition if you think it will not work:

p u b l i c c l a s s S t u d e n t { p r i v a t e S t r i n g name , m a j o r ; p u b l i c S t u d e n t () { n a m e = " ??? "; m a j o r = " xxx "; } p u b l i c S t u d e n t ( S t r i n g n , S t r i n g m ) { n = n a m e ; m = m a j o r ; } p u b l i c S t r i n g g e t M a j o r () { r e t u r n m ; } p u b l i c S t r i n g g e t N a m e () { r e t u r n n ; } }

3. Implement a class called AsuStudent. The class should keep track of the student’s name, number of classes registered, hours spent per week for a class (consider a student devotes the same amount of time for each of his/her classes per week). Implement a toString method to show the name and number of classes registered by a student, a getName method to return the name of the student, a getTotalHours method to return the total number of hours per week, and a setHours method to set the number of hours the student devotes for each class.

(36)

Methods

8.1 Motivation

We have seen various “methods” in the last chapter, but we want to improve on the functionality of our classes that we create. Therefore, we use methods to act on the objects we create.

8.2 Structure

The typical structure of a method is:

< visibilitymodif ier >< returntype >< methodname > (< optionalparameters >){...} For example, if I want to create a method called “test” which takes a String parameter and returns nothing (i.e. void), we would probably write it like this:

p u b l i c v o i d t e s t ( S t r i n g p a r a m ) {

// ...

}

Let’s say that this method is in a class called “A”. Therefore, to call the method on the class, we would write (in main):

A a = new A () ; // or s o m e o t h e r c o n s t r u c t o r

a . t e s t (" H e l l o ") ;

We say that we “call” the method “test” on the object “a” of type “A”. We will get a compilation error if instead of public, we make the visibility modifier be private. Also, a method can only have one return type, or void, which means “not returning a value,” but is nevertheless a return type (just not a value). However, if we put void as our return type, we can have a return statement to immediately exit from the method:

p u b l i c v o i d s o m e M e t h o d () { for (int i =0; i < 1 0 0 ; i ++) { if ( i == 57) { r e t u r n; // w i l l i m m e d i a t e l y s t o p e x e c u t i o n of m e t h o d // r e t u r n 5; // c o m p i l a t i o n error , s i n c e we h a v e v o i d } } }

8.3 Methods Returning Values

Methods can “return” types, with the return keyword. For example, if we want to implement a method that takes in 2 int parameters and returns their product, we can do this:

p u b l i c int m u l t i p l y (int num1 , int n u m 2 ) {

r e t u r n n u m 1 * n u m 2 ; // r e t u r n t h i s v a l u e

(37)

We can use this method, say in a class called C, to call the method and use the value that is returned:

C c = new C () ;

int r e s u l t = c . m u l t i p l y (3 , 4) ; // r e s u l t is 12

Since we specified int as the return type of multiply, we must return a int at some point in the method. We will have a compilation error if we don’t return a type when we say there will be, or returning an incorrect type.

Also, we must have a return statement at all points that are reachable within the program (or combine them). For example, here is a method that will cause a compilation error:

p u b l i c int m u l t i p l y (int num1 , int n u m 2 ) {

if ( n u m 1 > 0) { S y s t e m . out . p r i n t (" n u m 1 > 0 ") ; // c o m p i l e r e r r o r h e r e b e c a u s e no r e t u r n v a l u e } e l s e { r e t u r n n u m 1 * n u m 2 ; // r e t u r n t h i s v a l u e } }

We can see that if num1 > 0, then we print that statement out, do not execute the else clause, and continue. Since we can have a way through the method without returning, it causes a compilation error. We can mitigate this by adding a return statement either inside the if statement or at the end of the method (the “catch-all” case):

p u b l i c int m u l t i p l y (int num1 , int n u m 2 ) {

if ( n u m 1 > 0) { S y s t e m . out . p r i n t (" n u m 1 > 0 ") ; r e t u r n 0; // f i x e d c o m p i l a t i o n e r r o r } e l s e { r e t u r n n u m 1 * n u m 2 ; // r e t u r n t h i s v a l u e } // can a l s o put h e r e : r e t u r n 0; } 8.4 Written Exercises

1. Write the output generated by the following program:

p u b l i c c l a s s Two { p r i v a t e d o u b l e real , i m a g ; p u b l i c Two (d o u b l e i n i t R e a l , d o u b l e i n i t I m a g ) { r e a l = i n i t R e a l ; i m a g = i n i t I m a g ; } p u b l i c d o u b l e g e t R e a l () { r e t u r n r e a l ; } p u b l i c d o u b l e g e t I m a g () { r e t u r n i m a g ;

(38)

}

p u b l i c Two m y s t e r y ( Two rhs ) {

Two t e m p = new Two ( g e t R e a l () + rhs . g e t R e a l () , g e t I m a g () + rhs . g e t I m a g () ) ; r e t u r n t e m p ; } } p u b l i c c l a s s T e s t { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { Two a = new Two (1.2 , 3 . 4 ) ;

Two b = a . m y s t e r y ( a ) ; Two c = b . m y s t e r y ( b ) ; S y s t e m . out . p r i n t l n (" 1. " + a . g e t R e a l () ) ; S y s t e m . out . p r i n t l n (" 2. " + a . g e t I m a g () ) ; S y s t e m . out . p r i n t l n (" 3. " + b . g e t R e a l () ) ; S y s t e m . out . p r i n t l n (" 4. " + b . g e t I m a g () ) ; S y s t e m . out . p r i n t l n (" 5. " + c . g e t I m a g () ) ; } }

2. Using these 2 classes, write the output of the following program:

p u b l i c c l a s s C D P l a y e r { p r i v a t e int t o t a l T i m e ; p u b l i c C D P l a y e r () { t o t a l T i m e = 0; } p u b l i c int t o t a l P l a y T i m e () { r e t u r n t o t a l T i m e ; } p u b l i c v o i d p l a y ( C D T r a c k a T r a c k ) { t o t a l T i m e += a T r a c k . g e t P l a y T i m e () ; } } p u b l i c c l a s s C D T r a c k { p r i v a t e S t r i n g m y T i t l e ; p r i v a t e int m y P l a y T i m e , m y T i m e s P l a y e d ; p u b l i c C D T r a c k ( S t r i n g t r a c k T i t l e , int p l a y T i m e ) { m y T i t l e = t r a c k T i t l e ; m y P l a y T i m e = p l a y T i m e ; m y T i m e s P l a y e d = 0; } p u b l i c int g e t P l a y T i m e () { r e t u r n m y P l a y T i m e ; } p u b l i c v o i d w a s P l a y e d () { m y T i m e s P l a y e d ++; } p u b l i c S t r i n g t o S t r i n g () {

(39)

S t r i n g r e s u l t = " "; int m i n u t e s = m y P l a y T i m e / 60; int s e c o n d s = m y P l a y T i m e % 60; r e s u l t += m y T i t l e + " " + m i n u t e s + " : " + s e c o n d s ; r e s u l t += " # p l a y s = " + m y T i m e s P l a y e d ; r e t u r n r e s u l t ; } } p u b l i c c l a s s R u n C D P l a y e r { p u b l i c s t a t i c v o i d m a i n ( S t r i n g [] a r g s ) { C D T r a c k t1 = new C D T r a c k (" Day T r i p p e r ", 1 5 0 ) ;

C D T r a c k t2 = new C D T r a c k (" We Can W o r k it Out ", 2 0 0 ) ; C D T r a c k t3 = new C D T r a c k (" P a p e r b a c k W r i t e r ", 1 3 8 ) ; C D P l a y e r d i s k P l a y e r = new C D P l a y e r () ; t1 . w a s P l a y e d () ; d i s k P l a y e r . p l a y ( t1 ) ; t2 . w a s P l a y e d () ; d i s k P l a y e r . p l a y ( t2 ) ; t1 . w a s P l a y e d () ; d i s k P l a y e r . p l a y ( t1 ) ; S y s t e m . out . p r i n t l n ( t1 . t o S t r i n g () ) ; S y s t e m . out . p r i n t l n ( t2 . t o S t r i n g () ) ; S y s t e m . out . p r i n t l n ( t3 . t o S t r i n g () ) ; S y s t e m . out . p r i n t l n (" T o t a l p l a y t i m e : " + ( d i s k P l a y e r . t o t a l P l a y T i m e () / 60) + " : " + ( d i s k P l a y e r . t o t a l P l a y T i m e () % 60) ) ; } } 8.5 Programming Exercises

1. Write a boolean method called allDifferent that takes 3 int numbers and returns true if they are all different, and false otherwise.

2. Write a boolean method called isPrime that takes in an int number and returns true if it is prime, and false otherwise.

(40)

Static

9.1 Motivation

Now that we have created instance methods in the last chapter, we want to create class methods, which do not involve any instance state.

9.2 Static

The keyword static in Java is meant to mean “only one of these exists”. If I have a static variable in a class (in the same place an instance variable will be), there will only be one copy of that variable, regardless of how many instances there are of that class.

For example, let’s say we have a class called B that has a static field called numInstances of type int which is incremented every time the constructor is called. We would design the code like this: p u b l i c c l a s s B { p r i v a t e s t a t i c int n u m I n s t a n c e s = 0; // s t a r t w i t h a v a l u e p u b l i c B () { n u m I n s t a n c e s ++; } p u b l i c int g e t N u m I n s t a n c e s () { r e t u r n n u m I n s t a n c e s ; } }

If we call this from main: B b1 = new B () ;

S y s t e m . out . p r i n t l n ( b1 . g e t N u m I n s t a n c e s () ) ; // p r i n t s 1

B b2 = new B () ;

S y s t e m . out . p r i n t l n ( b2 . g e t N u m I n s t a n c e s () ) ; // p r i n t s 2

Now if we change the code to not have the instance variable be static, then we have:

p u b l i c c l a s s B { p r i v a t e int n u m I n s t a n c e s = 0; // r e m o v e " s t a t i c " p u b l i c B () { n u m I n s t a n c e s ++; } p u b l i c int g e t N u m I n s t a n c e s () { r e t u r n n u m I n s t a n c e s ; } }

(41)

B b1 = new B () ;

S y s t e m . out . p r i n t l n ( b1 . g e t N u m I n s t a n c e s () ) ; // p r i n t s 1

B b2 = new B () ;

S y s t e m . out . p r i n t l n ( b2 . g e t N u m I n s t a n c e s () ) ; // p r i n t s 1

which is not the behavior that we want.

Now we can get a larger understanding of various conventions we have been using:

– The main method’s use of static in its signature shows that only 1 copy of that method can exist at a time in a Java program. Therefore, there is no ambiguity as to where execution starts. – For other code, such as Math.PI, we can have an understanding as to possibly how it and some

of its static methods are implemented:

p u b l i c c l a s s M a t h { // ... p u b l i c f i n a l s t a t i c d o u b l e PI = 3 . 1 4 1 5 9 2 6 ; // ... p u b l i c s t a t i c d o u b l e pow (d o u b l e base , d o u b l e e x p o n e n t ) { ... } // ... p u b l i c s t a t i c d o u b l e s q r t (d o u b l e num ) { ... } } 9.3 Written Exercises

1. What is a static variable? What is a static method?

2. Using the code below, how many copies of the variable number exist after instantiating 374 different AmazingClass objects?

p u b l i c c l a s s A m a z i n g C l a s s { p r i v a t e s t a t i c int n u m b e r ; p u b l i c A m a z i n g C l a s s (int a ) { n u m b e r = a ; } p u b l i c int t w i c e () { n u m b e r *= 2; r e t u r n n u m b e r ; } }

3. Using the code from above, what is the value of number after each of the following statements? (For each line below, assume the preceding ones have already been executed).

A m a z i n g C l a s s ac1 = new A m a z i n g C l a s s (3) ; A m a z i n g C l a s s ac2 = new A m a z i n g C l a s s (7) ; ac1 . t w i c e () ;

References

Related documents

3.3 Any claim for extension of the completion date of the Project shall be made by the Contractor in writing to the Employer, through the Consulting Engineer, not more than _____

Such filmmaking education has been able to weave its contexts in ever lesser funding streams by being innovative, flexible and open and spanning not only the arts, education,

Along with acquiring essential knowledge about important early childhood development, our students may gain highly practical experience through simulating techniques and best

[r]

except “Showtime” produced by Danja for Danja Handz Productions and “No Hay Igual” produced by Timbaland for Timbaland Productions, Danja for Danja Handz Productions and Nisan

1854 limitation on limited partner as creditor 1858 liabilities of limited partner in partnership 1862 creditors of limited partners. Agency WHAT 1868 definition 1875 presumption

Now we consider the various types of data that can be used as inputs to this adaptive filter structure. Real data types have been used in the early types of adaptive filters.

In this work, a hybrid topology design over the WDM networks is proposed to support multicast sessions. The hybrid topology is composed of light paths, light trees and the