Download Composite Data Types

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Composite Data Types
A composite data type is any data type that is composed of primitive data types as its based type. In other
words, it is an aggregate of primitive types. Composite types in Java are the array data structure and the
class data type. In this section we will briefly discuss the concept of array. We will and we will discuss the
class type to the extent of the fundamental classes of Java.
Array
An array is a contiguous set of storage locations set aside to hold one type of data. Array is simply a means
where by we can store values of the same type by using one generic name. The list of items are stored
linearly, hence the items can be accessed by their relative position in the list.
Arrays are regarded as real objects in Java. Storage space is not allocated for an array during compilation
time, but rather during execution time. This means that the declaration alone does not imply that memory is
allocated. The concept will be discussed fully in chapter 6.
Class
The concept of class is fundamental construct upon which Java is built. A class serves as a blueprint or a
template for a certain type of object. Against this background all data types other than the primitive type or
the array must be addressed in terms of a class. This is evident in the way that we use a class. For instance,
going back to the class areaAndCircumference. In order to use this class we had to declare variables of the
type:
areaAndCircumference circle1;
Notice that this declaration follows the definition of how to declare primitive data type. This construct
implies that the identifier areaAndCircumference is a type and circle1 is an identifier of that type.
Standard Packages
Java has a vast and rich collection of classes. These classes are reposited in respective directories and
subdirectories. Each directory or subdirectory is called, a package. Programmers can use these classes in
their specific applications. There are several packages in Java. Two of the most important packages in the
language are java and javax. Figure 3.15 shows these packages and along with their sub-packages. In our
study we will focus on the package java and in particular the sub-package called lang.
Figure 3.15 Java packages and sub-packages.
Figure 3.15 shows Java’s two most important packages, namely java and javax. Most of the classes found
in the package javax and its sub-packages are designed to be used for Graphical User Interface (GUI)
programming. We will be using the class JOptionPane from javax for input and output later in this course
of study.
As we have seen from the figure, the package java contains several sub-packages. Some of these subpackages contain sub-packages also. The most important package in the Java language is the package
called lang. It is so important that its content is automatically loaded in memory when the Java compiler is
invoked. For all other classes, the package must be imported, using the import statement. The following
section explores the package java.lang.
The Package java.lang
As was mentioned earlier, the java.lang package contains classes that are fundamental to Java. All of the
classes are available in your program automatically. That is, as soon as the Java compiler is loaded, all of
these classes are loaded into every Java source file. Figure 3.16 shows java.lang two sub-packages and all
the classes that are directly in the package java.lang.
There is no intention for you to memorize the classes in this package, but over time you will get to know
them by name and their intended purpose.
Figure 3.16 All the classes that directly belongs to the package java.lang.
Chief among these fundamental classes are the following:






Object
String
Math
System
The wrapper classes – Byte, Short, Integer, Long, Character, Float, Double, Boolean, and Void.
That is, for each primitive type there is a corresponding class.
Throwable.
We will discuss the first three classes in this section; others will be discussed as needed. Remember that the
intent was to show that classes are also data types; and that we can declare variables of each type as we
would for primitive types. In addition, their functionality is based on their method definitions.
The class Object,java
The class called Object is the heart of the Java programming language. All classes including user-defined
classes depend on it, whether directly or indirectly. This class has one default constructor. The class defines
the basic functionality that all objects exhibit. These functionalities are defined by the eleven methods
shown if Figure 17.
Methods in class Object
Functionality of each of these methods.
protected Object clone()
Creates and returns a copy of a current object.
public boolean equals(Object o)
Indicates whether some other object is "equal to" this one.
protected void finalize()
Called by the garbage collector on an object when garbage
collection determines that there are no more references to the
object.
public Class getClass()
Returns the runtime class of an object.
public int hashCode()
Returns a hash code value for the object.
public void notify()
Wakes up a single thread that is waiting on this object's monitor.
public void notifyAll()
Wakes up all threads that are waiting on this object's monitor.
public String toString()
Returns a string representation of the object.
public void wait()
Causes current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object.
public void wait(long)
Causes current thread to wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a
specified amount of time has elapsed.
void wait(long, int )
Causes current thread to wait until another thread invokes the
notify() method or the notifyAll() method for this object, or some
other thread interrupts the current thread, or a certain amount of
real time has elapsed.
Figure 3.17 The eleven methods that defined in the class Object and can be redefined by other classes.
These methods can be redefined by all other classes. Two of the most frequently used ones at an earlier
stage are the methods equals() and toString(). Two objects are said to be equal if they compare to
themselves. Listing 3.6 defines the class object_equality. In the following example Listing 3.7, obj1 and
obj2 are located at different memory locations, hence in this context they are not the same objects.
However, obj3 was made to assume the address of obj1. That is, both reference variables are pointing so to
speak at the same thing (the same object). Hence they are equal.
1. class object_equality
2. {
3.
String str;
4.
int x;
5.
6.
public object_equality(int x, String str)
7.
{
8.
this.x = x;
9.
this.str = str;
10.
}
11. }
Listing 3.5 defines the class object_equality.
1. class testEquality
2. {
3.
public static void main(String arg[])
4.
{
5.
object_equality obj1, obj2;
6.
obj1 = new object_equality(1, "First Object");
7.
obj2 = new object_equality(2, "Second Object");
8.
9.
System.out.println("Object 1 is stored at address: "
10.
System.out.println("Object 2 is stored at address: "
11.
System.out.println("Objects 1 & 2 are the same: " +
obj1.equals(obj2));
12.
13.
object_equality obj3 = obj1;
14.
15.
System.out.println("\nObject 1 is stored at address:
16.
System.out.println("Object 3 is stored at address: "
17.
System.out.println("Objects 1 & 3 are the same: " +
obj1.equals(obj3));
18.
System.out.println();
19.
}
20. }
Listing 3.6 The test of equality between objects.
Figure 3.18 Output showing which objects are equal.
+ obj1);
+ obj2);
" + obj1);
+ obj3);
Every class that uses this method can use it to give the right semantics. In the example above, the semantics
assumed is equality based on the address of the objects. We will see other semantics later.
The method toString can be redefined by a class to return any string object. If the programmer chooses to
redefine it, then the method signature must be the same as specified in the language. That is, the method
signature must be of the form:
public String toString()
Failure to express it this way will result in syntax error.
For instance Listing 3.7 Lines 12 – 15 redefines the instance toString method, and Listing 3.8 shows how
the method is called.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
class to_string
{
private int x;
private String str;
public to_string(int x, String str)
{
this.x = x;
this.str = str;
}
public String toString()
{
return "The " + str + " object is number " + x;
}
}
Listing 3.7 shows how the toString method can be redefined within a user-defined class.
1. class test_to_string
2. {
3.
public static void main(String[] arg)
4.
{
5.
6.
to_string obj1, obj2;
7.
8.
obj1 = new to_string(1, "First");
9.
obj2 = new to_string(2, "Second);
10.
11.
System.out.println(obj2.toString());
12.
System.out.println(obj1.toString());
13.
}
14. }
Listing 3.8 calls the method toString redefined in the class to_string
Figure 3.19 shows the output after the toString method has been called.
Other methods in this class will be discussed as needed.
String
The composite type String has a unique feature. On the one hand it resembles an ordinary data type, but in
fact it is an object represented by a class called String. The data representation of a string is a finite
sequence of characters, be it chars or digits or special characters. We will study strings from both
perspectives: treated as an ordinary type, and treated in its full for, a class.
Declaring and Initializing String Variables
Treated as an ordinary type, a string variable is declared and initialized the same way variables of primitive
types are declared. That is, the declaration follows the pattern:
String
myString;
Where String is the data type, and myString is the name of the variable.
String values are not treated the same way as character and numeric arrays. When assigning a value to a
string variable, the value to be assigned must be enclosed within double quotation marks. For example, the
following is a valid declaration and assignment:
String myString;
myString = “I am learning Java”;
Alternately,
String myString = “I am learning Java”;
Two strings can be joined as we have seen by use of the plus ( + ) symbol to form a third string. Hence if
str1, str2, and str3 are string objects, then the following statement simply join str2 to the tail of str1, and
the contents is stored in str3.
str3 = str1 + str2;
This is the only operation that can be performed on strings without looking to the class String.
The class String
The class String has eleven overloaded constructors. Figure 3.20 shows two of them. All the others are
defined in terms of arrays. Those will be discussed after we have studied array.
Two String Constructors
Purpose
public String()
Initializes a newly created String object so that it represents an
empty character sequence.
public String(String str)
Allocates a new string that contains the sequence of characters
currently contained in the string buffer argument.
Figure 3.20 Two constructors from the class String.
String Operations
In addition to the constructors, the class has forty-nine methods, many of which are overloaded. That is, the
class String provides methods for:






Examining individual characters of the sequence
Comparing strings
Searching strings
Extracting sub-strings
Creating a copy of a string, and
Concatenate strings
Figure 3.21 shows the most frequently used methods at this level of programming.
Methods
Purpose
Example
char charAt(int)
Returns the character at the specified index.
str.charAt(14)
int compareTo(String)
Compares two strings lexicographically.
str.compareTo(“java”)
int
compareToIgnoreCase
(String)
Compares two strings lexicographically,
ignoring case considerations.
str.compareToIgnoreCase
(“JavA”)
Concatenates the specified string to the end
of this string.
str.concat(“Yes”);
boolean
endsWith(String)
Tests if this string ends with the
Specified suffix
str.endsWith(“Java”);
boolean equals(Object)
Compares this string to the specified object.
“Java.equals(”Java”);
boolean
equalsIgnoewCase
Compares this String to another String,
String str.concat(String)
(String)
ignoring case considerations.
“JaVa”.equals(“java”)
int length()
Returns the length of this string; ie. The
number of characters in the string.
str.length()
String substring
(int beginIndex)
Returns a new string that is a substring of
this string.
str.substring(5)
String substring
( int beginIndex,
int endIndex )
Returns a new string that is a substring of
this string.
Substring (5, 8)
Figure 3.21 The most frequently used methods in the class String
The Lexicographical order of two words is defined as follows:



The value 0 if the argument is a string lexicographically equal to this string.
A value less than 0 if the argument is a string lexicographically greater than this string
A value greater than 0 if the argument is a string lexicographically less than the string.
Listing 3.9 shows two ways of creating a string object. See Lines 5 and 6. In addition Lines 8 – 11
show various methods being called.
1. class test_strings
2. {
3.
public static void main(String [] arg)
4.
{
5.
String str1 = "Hello! I am learning Java";
6.
String str2 = new String ("Hi, I am about to learn strings
in Java");
7.
8.
System.out.println("str1 has " + str1.length() + "
characters");
9.
System.out.println("The first six characters of str1 is: "
+ str1.substring(0,6));
10.
System.out.println("The 16th character is str1 is: " +
str1.charAt(15));
11.
System.out.println(
str1.substring(0,6).concat(str2.substring(3)));
12.
}
13. }
Listing 3.9 Creating strings and operations on strings.
The class Math.java
The class Math contains methods for performing basic numeric operations such as the elementary
exponential, logarithm, square root, and trigonometric functions. This class is regarded as a service class. It
does not have any public constructor, it has only one private constructor, and hence you cannot create a
Math object. All of the methods in the class are class methods. The class comes with two class constants.
They are shown in Figure 3.22.
static double E
The double value that is closer than any other to e, the base of the
natural logarithms.
static double PI
The double value that is closer than any other to pi, the ratio of the
circumference of a circle to its diameter.
Figure 3.22 Shows the two class constants in the class java.lang.Math.
Listing 3.10 shows how these methods are called, and Figure 3.23 shows the value for each constants.
1. class E_PI
2. {
3.
public static void main(String[] arg)
4.
{
5.
System.out.println("The value of pi is: " + Math.PI);
6.
System.out.println("The value of E is: " + Math.E);
7.
}
8. }
Listing 3.10 The class methods are called using the class name.
The following output shows the value of pi and E respectively.
Figure 3.23 Shows the output for both values pi and E respectively.
As was mentioned earlier, the class Math contains only class methods. To use them you simply use the
pattern:
Math.method(parameter);
Where Math is the name of the class, method represents any of the class methods, and parameter
represents the argument list of each method. Figure 3.24 shows the more frequently used methods.
Static methods from class Math
Their return type and parameter listing
double abs(double a)
Returns the absolute value of a double value.
float abs (float a)
Returns the absolute value of a float value.
int abs(int a)
Returns the absolute value of an int value.
long abs(long a)
Returns the absolute value of a long value.
double acos(double a)
Returns the arc cosine of an angle, in the range of 0.0
through pi.
double asin(double a)
Returns the arc sine of an angle, in the range of -pi/2
through pi/2.
double atan(double a)
Returns the arc tangent of an angle, in the range of -pi/2
through pi/2.
double atan2(double a, double b)
Converts rectangular coordinates (b, a) to polar (r, theta).
double ceil(double a)
Returns the smallest (closest to negative infinity) double
value that is not less than the argument and is equal to a
mathematical integer.
double cos(double a)
Returns the trigonometric cosine of an angle.
double exp(double a)
Returns the exponential number e (i.e., 2.718...) raised to
the power of a double value.
double floor(double a)
Returns the largest (closest to positive infinity) double value
that is not greater than the argument and is equal to a
mathematical integer.
double IEEEremainder(double f1,
double f2)
Computes the remainder operation on two arguments as
prescribed by the IEEE 754 standard.
double log(double a)
Returns the natural logarithm (base e) of a double value.
double max(double a, double b)
Returns the greater of two double values.
float max(float a, float b)
Returns the greater of two float values.
int max(int a, int b)
Returns the greater of two int values.
long max(long a, long b)
Returns the greater of two long values.
double min(double a, double b)
Returns the smaller of two double values.
float min(float a, float b)
Returns the smaller of two float values.
int min(int a, int b)
Returns the smaller of two int values.
long min(long a, long b)
Returns the smaller of two long values.
double pow(double a, double b)
Returns of value of the first argument raised to the power of
the second argument.
double random()
Returns a double value with a positive sign, greater than or
equal to 0.0 and less than 1.0.
Returns the double value that is closest in value to a and is
double rint(double a)
equal to a mathematical integer.
long round(double a)
Returns the closest long to the argument.
int round(float a)
Returns the closest int to the argument.
double sin(double a)
Returns the trigonometric sine of an angle.
double sqrt(double a)
Returns the correctly rounded positive square root of a
double value.
double tan(double a)
Returns the trigonometric tangent of an angle.
double toDegrees(double angrad)
Converts an angle measured in radians to the equivalent
angle measured in degrees.
double toRadians(double angdeg)
Converts an angle measured in degrees to the equivalent
angle measured in radians.
Figure 3.24 The class methods in class java.lang.Math
The class Number.java
This class defines six method prototypes, one for each of the primitive numeric types. This class cannot be
used exclusively by itself; instead other numeric classes called wrapper classes are allowed to use them.
byte
byteValue()
Returns the value of the specified number as a byte.
abstract double
doubleValue() Returns the value of the specified number as a double.
abstract float
floatValue()
Returns the value of the specified number as a float.
abstract int
intValue()
Returns the value of the specified number as an int.
abstract long
longValue()
Returns the value of the specified number as a long.
short
shortValue()
Returns the value of the specified number as a short.
Figure 3.25
The Wrapper Classes
Primitive values in Java are not objects; however, Java provides matching classes for each of the primitive
types, so that they can manipulate the primitive types as objects. As shown in Figure 3.16, the wrapper
classes are:
Byte, Short, Integer, Long, Character, Float, Double, Boolean, and Void. The numeric wrapper classes
have all of the methods shown in Figure 3.xx. Each of the classes defines each of these methods in its own
way. There are several other methods in each of the classes, but they are not frequently used at this level.
There is one other method, a class method that is frequently used; each of these classes has a version of this
method. The versions of this method are:
static byte parseByte(String)
Returns the byte represented by the string value of the
string.
static double parseDouble(String)
Returns the double represented by the string value of the
string.
static float parseFloat(String)
Returns the float represented by the string value of the
string.
static int parseInt(String)
Returns the int represented by the string value of the string.
static long parseLong(String)
Returns the long represented by the string value of the
string.
static short parseShort(String)
Returns the short represented by the string value of the
string.
Figure 3.26
Example.
A boat C is 200 meters from the foot B of a vertical cliff, which is 40 meters high. What is the angle of
elevation of the top of the cliff from the boat? Find the line of sight of the boat from the top of the cliff.
Design a class that accepts the two values, calculates the angle and the line drawn from the top of the cliff
to the boat.
Extract the two values from the following strings as input to the class:
Distance from foot of cliff 200
Height of cliff is 40 meters
Solution
 Name the class math.
 Instance variables- call them distance and height
 Instance methods - to return the measure of the angle and the line if drawn from top of cliff to
boat. Let us call them findAngle and lineOfSight respectively.
Algorithm

Finding angle - apply the arctangent of the height of a right triangle and its base.
Listing 3. 10 Line 14 shows how the method is applied. In addition, Line 16 shows two concepts:
converting the radian measure to degrees, and rounding of the value generated.

Finding the slant side of a right triangle – apply Pythagoras rule for right triangle. Lines 21 and 22
show how Pythagoras rule is applied. In addition, we are making use of the method pow that is
used to raise a number to some power, and the method sqrt that finds the square root of a number.

Assume that the values sent to the constructor are strings. Convert these values to double by using
parseDouble method from the class Double. Lines 7 and 9 demonstrate the usage.
1. class math
2. {
3.
double distance, height;
4.
5.
public math(String x, String y)
6.
{
7.
distance = Double.parseDouble(x);
8.
9.
height = Double.parseDouble(y);
10.
}
11.
12.
double findAngle()
13.
{
14.
double x = Math.atan(height/ distance);
15.
16.
return Math.round(Math.toDegrees(x));
17.
}
18.
19.
double lineOfSight()
20.
{
21.
double x = Math.pow(height, 2) + Math.pow(distance, 2);
22.
return Math.sqrt(x);
23.
}
24. }
Listing 3.10
In the test class we have made use the string method substring to extract the numeric string
representations. See Figure 3.11 Lines 8 and 9. Finally Line 18 shows one way of converting a double to
the next integer value equal to or larger than the value itself.
1. class testMath
2. {
3.
public static void main(String arg[])
4.
{
5.
String distance = "Distance from foot of cliff 200";
6.
String height = "Height of cliff is 40 meters";
7.
8.
distance = distance.substring(28);
9.
height = height.substring(19,21);
10.
11.
System.out.println("Distance of boat from foot of cliff is: " + distance);
12.
System.out.println("The height of the cliff is: " + height);
13.
14.
math m = new math(distance, height);
15.
16.
System.out.println("The angle of elevation is: " + m. findAngle() + " degrees");
17.
18.
System.out.println("The line of sight is " + (int)Math.ceil(m.lineOfSight()) + " meter");
19.
}
20. }
Listing 3.11.
Figure 3.27
Summary
In this chapter you have learned about variables, data types, and operations on data Most importantly, you
should have learned the following:

The conventions that are use to name variables:

Each variable must be declared before it can be used.

Java primitive data types and composite types. The primitive type includes numeric types, which
includes integer and floating-point types; character types; and boolean types.

The integer types are: byte, short, int, long. The corresponding storage requirements for each of
these types are 1 byte, 2 bytes, 4 bytes, and 8 bytes, respectively. The default for an integer value
is int.

Java floating-point types are float and double. The default of a floating-point number is a double.
The storage requirements are 4 bytes and 8 bytes, respectively.

The character type, char, is a 2 bytes Unicode representation.

The third and final primitive data type is the boolean, which has values true or false.

There are two composite types in Java, namely: array and string. Arrays are used to house more
than one data values of the same type. Individual elements are accessed by use of the index. A
string stores a fixed number of characters that cannot be changed. You can create an array of
string objects.

You can know the number of items that are in an array by using the string operator length.