Java - University of Technology - 11

ass 9

a = 2;

;

Maybe you are interested!


u add

Java - University of Technology - 11

sum = a + ;

sum


" RB ! #

< #

u addI a ! @ m

dummy;

sum = a + dummy;

sum

W - # (

# 2 3

" R


Figure 5.10: Instance variables and local variables.


As said, a method's parameter is also a local variable of that method. It has been initialized with the value of the argument passed to the method.

These are syntactic and language-specific features. In terms of conceptual nature, these two types of variables are quite different in the following sense:

A local variable belongs to a method – where it is declared. It is created when the method is called and the statement that declares it is executed. It expires when it goes out of scope – the end of the statement block that declares it or when the method ends.

An instance variable belongs to an entity – its owner object. It is created when the object is created and expires when the object is destroyed.

Exercise

1. Fill in each blank with one or more of the following words: instance variable, argument, return value, get method, set method, encapsulation, public, private, pass by value, method.

A class can have any number of. A method can have only one.

can be implicitly converted to data type.

means "I want to make my entity private".

actually means "make a copy".

should only be updated by setter methods. A method can have multiple .

return some value

should not be used for instance variables.

can have multiple arguments.

help implement packaging principles.

there is always only one

2. Fill in the appropriate word in each blank in the following sentence:

a) Each parameter must be specified with aand one

b) The keyword placed in the return type declaration specifies that a method will not return any value after it completes its task.

3. Are the following statements true or false? If false, explain.

a) Empty parentheses () after a method name in a method declaration indicate that the method does not require any parameters.

b) Instance variables or methods declared with the private keyword can only be accessed from methods within the class where they are declared.

c) The method body is enclosed within a pair of braces {}.

d) It is possible to call a method from a base type variable.

e) Basic local variables are initialized by default.

f) The number of arguments contained in a method call must match the number of parameters in the parameter list of that method declaration.

4. Distinguish between instance variables and local variables.

5. Explain the purpose of method parameters. Distinguish between parameters and arguments.

6. Why might a class need to provide a set method and a get method for an instance variable?

7. Write an Employee class that contains three pieces of information as data members: first name (String), last name (String), and salary (double). The Employee class needs a constructor that initializes these three data members. Write a set function and a get function for each data member. If the monthly salary is negative, assign it a value of 0.0. Write an EmployeeTest program to test the features of the Employee class. Create two Employee objects and print each employee's total annual salary. Then give each employee a 10% raise and display their annual salary again.

8. Create a class called Invoice that a store can use to represent an invoice for an item sold at the store. Each Invoice object needs four pieces of information as its data members: the item number (partNumber of type String), the item description (partDescription of type String), the quantity sold (quantity of type int), and the unitPrice of type double. The Invoice class needs a constructor that initializes these four data members. Write a set method and a get method for each data member. Also, write a method called getInvoiceAmount that calculates the invoice amount (i.e., the quantity multiplied by the unit price), and returns the invoice amount as a double. If the quantity is not positive, it should be set to 0. If the unit price is negative, it should also be set to 0.0. Write a test application called InvoiceTest to test the features of the Invoice class.

9. Find and fix errors in the following programs (each part is a complete source code file).

a)

b)

Chapter 6. Using Java libraries


The reusability of object-oriented programming is reflected in Java's massive library of hundreds of prebuilt classes. These are the basic building blocks from which we assemble large programs. This chapter introduces these basic building blocks.


6.1. ArrayList


First, let's take an example of a class in the library: ArrayList. We already know about the array structure of Java. Like arrays of many other languages, Java arrays have limitations such as we must know the size when creating an array; deleting an element in the middle of the array is not simple; the array cannot store more elements than the declared size. The ArrayList class is an array-like structure that overcomes the disadvantages of the array structure. We do not need to know how big an ArrayList needs to be when creating it, it will automatically expand or contract when objects are inserted or removed. In addition, ArrayList is also a structure with type parameters, we can create ArrayList<String> to store elements of type String, ArrayList<Cow> to store elements of type Cow, etc.

ArrayList gives us the following utilities:

add(Object item)

append object to end of list

add(int i, Object item)

insert object at position i in list

get(int i)

returns the object at position i in the list

remove(int index)

delete object at index position

remove(Object item)

delete object if it is in the list

contains(Object item)

Returns true if the list contains the item object.

isEmpty()

Returns true if list is empty

size()

returns the number of elements currently in the list

get(int index)

Returns the object currently located at index position


An example of using ArrayList is given in Figure 6.1. In it, the initialization statement new ArrayList<String> creates a list object of type String, temporarily empty. The first call to add increases the size of the list from 0 to 1. The second call adds the string "Goodbye" to position 1 in the list and increases the size of the list by 2. After remove(a), the size of the list decreases back to 1. Essentially, an ArrayList object stores a list of references to objects of the declared type. As in this example, at the time after calling add(0,b), our ArrayList object contains a list of two references of type String, one referring to the String object "Goodbye" that b is referring to, the other referring to the String object "Hello".


Figure 6.1: Example using ArrayList.


The <String> syntax in the ArrayList declaration line will be explained in detail in Chapter 13. For now, we will accept ArrayList<String> as a list type of String objects, and ArrayList<Cow> as a list type of Cow objects.

6.2. USING JAVA API


In the Java API, classes are grouped into packages. To use a class in a library, we need to know which package it is in. Each package has a name, for example java.util. Scanner is in the java.util package. It contains many utility classes. We have also used the System class (System.out.println), String, and Math which are in the java.lang package.

Details about packages, including how to put your own classes in your own package, are presented in Appendix B. In this chapter, we only briefly introduce the use of some classes in the Java library.

We will take the example of ArrayList in the previous section to illustrate the contents in this section.

First, we need to know the full name of the class we want to use in the program. The full name of ArrayList is not ArrayList but java.util.ArrayList. Where java.util is the package name and ArrayList is the class name.

We have to tell the Java virtual machine which ArrayList we are going to use. We have two options:

1. Use the import command at the beginning of the source code file. For example, the first line in the ArrayListTest program file in the previous section is:

import java.util.ArrayList;

2. Call the full name of the class every time you call its name. For example:

java.util.ArrayList<Cow> =

new java.util.ArrayList<Cow>


The java.lang package is pre-loaded. So we don't have to import java.lang or use the full name to use the String and System classes.

There are three reasons for organizing classes into packages: First, packages help organize a project or library. Instead of having a bunch of classes in one place, classes are placed in different packages based on their functionality, such as GUI, data structure, or database. Second, packages provide a namespace, which helps avoid duplicate names. If a bunch of programmers create classes with the same name but in different packages, the Java virtual machine can still access those classes. Third, packages provide a level of security (the package level), so that we can restrict the code we write in a package so that only the classes in that package can access it. We'll talk more about this later.

How to use API?

We need to know two things: (1) what classes are in the library, and (2) once we find a class, how do we know what it can do? To answer these two questions, we can consult a Java book or the API documentation.


Figure 6.2: Java 6 API documentation, page about ArrayList.


The API documentation is the best source for details about each class and its methods. You can search and browse by package, search and look up by class name. For each class, you will find a full description of the class, related classes, a list of methods, and detailed specifications for each method.


6.3. SOME COMMON CLASSES IN API


6.3.1. Math

Math is a class that provides common mathematical functions.

Math.random() : returns a double value in the range [0.0,..,1.0).

Math.abs() : returns a double value which is the absolute value of the argument of type double, similarly for the argument and return value of type int.

Math.round() : returns an int or long value (depending on whether the argument is a float or double) that is the rounded value of the argument to the nearest integer value. Note that float constants are interpreted by Java as being of type double unless the f character is added to the end, for example 1.2f.

Math.min() : returns the smaller value of two arguments. The argument can be int, long, float, or double.

Math.max(): returns the larger of two arguments. The argument can be int, long, float, or double.

In addition, Math has other methods such as sqrt(), tan(), ceil(), floor(), and sin(). We should look up the details in the API documentation.

Comment


Agree Privacy Policy *