Download Java Data Types

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

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

Document related concepts
no text concepts found
Transcript
LAB – Java Variables, Data, and Program
Structure
Abstract
In this lab, you will work in more detail with the input, process, output programming cycle. You will:






Learn about the Java data types and how to declare variables using those data types
Create a first class made up of properties and methods
Create a main procedure (entry point), to use the class and its methods
Convert textual data entered by the user into numbers
Perform arithmetic calculations on those numbers
Convert numbers to strings and format output
Key Terms

A class is a template or blueprint for an object. It commonly contains actions (methods), and
stores data (properties).

An event (callback function), is called by implicitly by the run time when something happens.
Callback functions are implemented by calling a function and passing the name of the callback
function to the argument. When the event fires, the callback function is implicitly called by the
run time.

A method is an action performed by a class. Methods are created by writing procedures in a
class.

Objects are created from classes. Most often, we create many objects from the same class. For
example, a Button class is used to create several Button objects.

A property is a data item stored in a class. When creating many objects from a class, each object
has the same properties, but separate data copies for each object. Properties are implemented
by declaring variables in a class or creating accessor / mutator methods
The Input / Process / Output Cycle
To review for a moment, programs with which users interact typically go through a cycle where the user
enters input, that input gets processed somehow, and then the program produces output(s), a result or
results. Very often, that user input needs to be checked and validated, then converted to numeric
values. That numeric data is then processed, and finally converted back to text, formatted, and
displayed to the user.
Page 1 of 21
In this lab, you will write a simple program that will get user input from the Console View, convert it to
numeric values, perform calculations, convert the results back to strings, and display those strings to the
Console View.
Java Data Types
Java is a strongly typed language, meaning that variables have a data type, which is defined when the
variable is declared. The possible values for a variable are defined by its data type. Java variables must
also be declared before they are used. Java data types can be categorized as primitive data types and
reference data types.

Primitive data types are those built-in to a programming language. Java has eight primitive data
types.

All other Java data types are reference types. All classes and the objects created from them are
considered reference types.
Primitive Data Types
Java supports the following primitive data types used to store whole numbers, floating-point numbers,
Boolean values, and a single character. Note that in Java, a string is not a primitive type. Rather, strings
are implemented as the java.lang.String class. Strings are considered reference types, which are
discussed next.
Data Type
byte
short
int
long
float
double
bool
char
Description
8-bit signed two’s complement integer (-128 to
+127)
16-bit signed two’s complement integer( -2
billion to +2 billion)
32-bit signed two’s complement integer( -32,768
to +32,767)
64-bit signed two’s complement integer
32 bit floating point number
64 bit floating point number
One bit (true or false)
16 bit Unicode character
Example
byte b = -42;
short s = 15000;
int i = 324555;
long l = 10444L;
float f = 123.45f;
double d1 = 123.456;
bool b = true;
char letter = ‘a’;
Reference Data Types
In addition to primitive data types, Java (and other object-oriented languages) support what are called
reference data types. All classes are reference types. In other words, all data types that are not one of
the primitive data types are reference types. When using a primitive data type, the memory allocated to
a variable stores the variable’s value. When using a reference data type, the memory allocated to a
variable stores a pointer to the actual object. In other words, the variable references an object.
One important Java reference type is a String. In Java, a String is class having properties and
methods just like any other class. Unlike in some languages the String data type is not a primitive
type.
Page 2 of 21
Variables, Procedures, and Access Modifiers
Variables, procedures, and access modifiers operate the same way in Java as they do in Visual Basic.

All variables have exactly one and only one data type that is defined when the variable is
declared.

Variables declared in a class but outside a procedure are called fields. Their values are persistent
for each class instance. Fields can be referenced by all procedures in a class. Fields declared with
the public access modifier can be used by other classes.

Variables declared in a procedure or code block are called local variables. The variable and its
value only exists while the procedure executes. Local variables do not have an access modifier.
They are accessible only to the procedure containing the declaration.

Variables declared in a method (function) declaration are called parameters. Parameters
provide the means to pass data values to a procedure each time it is called (executed). All
parameters have a data type. A function can have zero, one, or many parameters.

Functions have a data type. A function can return a value. When it does, the value must match
the data type of the variable. Functions that do not return a value have a data type of void.

Variables, functions, and parameters all have a name called an identifier. An identifier must
begin with a letter, followed by letters and numbers. Special characters other than the
underscore (_) character should not be used as identifier names.
Classes, procedures, and fields (variables declared inside a class but outside a procedure), have what are
called access modifiers. Access modifiers work the same way in Java as they do in most other languages,
including C# and Visual Basic. Classes and methods also have access modifiers.
Java has three access modifiers:

The public access modifier means that the class, method, or variable is visible to other classes
and packages.

The private access modifier means that the member (variable, method, etc…) can only be
accessed from its own class.

The protected access modifier will be discussed later when the topic of inheritance and
subclassing is discussed.
Java packages provide a way of organizing related classes and interface. In .NET, these organizational
units are called assemblies.
Page 3 of 21
Working with Classes and the Basics of Object-oriented Programming
Object-oriented programming is based on the idea that we create things programmatically such that
they represent real world things. We try to make programmatic things work in a way that they mimic
the functionality of the real-world thing.
Using object-oriented terminology, these things are called classes. The following list describes some
basic characteristics of a classes and object-oriented programming:

Classes have methods. Think of methods as verbs in a sentence, an activity, a calculation, or a
task. Methods can have 0, 1, or many parameters. Data is sent (passed) to a method via these
parameters. Data can also be returned to from a method via a parameter. Methods are
implemented as functions having function parameters.

Classes have properties. Think of properties as the nouns in a sentence. They represent the data
resulting from an activity, calculation or class.

Classes, methods, and properties, have access modifiers. (public, protected, private,
etc…) which dictate whether or not the member is visible outside of the class.

A class contains a constructor. A constructor is a “special” method. The code for this “special”
method executes when a class instance (object) is created from its class. The method always has
the same name as the class. A constructor is called using the new keyword. Constructors will be
discussed in more detail as you create objects from classes and build your own instance
methods.

The members of a class (properties and methods) have an instance indicator – the static
keyword. When applied to a member (function, field), it means that the member is called on the
class itself, rather than an instance of the class. There exists one copy of static data no matter
how many instances of a class have been created.
To get started, you will create a class named MyMath that will calculate the area of a rectangle and the
volume of a cube with methods (functions) named areaRectangle and volumeCube. The following code
segment shows the structure of the class:
public class MyMath
{
}

The class has an access modifier (public). This access modifier indicates that the class will be
visible to other classes and packages. In this lab, the MyMath class will be used by the main
procedure and class (NumericJavaMain).

Following the access modifier appears the class name (MyMath). This is the identifier by which
the class will be known to other classes.
Page 4 of 21

All of the members of the class (properties and methods) appear between the {} characters.
Again, in Java, the {} characters mark a block.
Next a static property is added to the class.
public class MyMath
{
public static int callCount = 0;
}
Note the following about a property (field) declaration:

Properties (fields) have an access modifier. The public access modifier allows all classes to
reference this property.

The keyword static indicates that data exists once for the class, rather than once for each
class instance. Thus, a static variable’s value is the same for all class instances because it is
shared by all the class instances.

The property has a data type (int), just as all properties have a data type. Here, the property’s
data type is the primitive int data type, meaning that the property will store an integer value.

The property has a name (callCount). Again, this name is the unique identifier name.

The variable’s value is initialized to 0.

Like all statements, it is terminated by a semicolon.
In the following code block, the methods (procedures) are added to the class.
public class MyMath {
public static int callCount = 0;
public static double areaRectangle(double length, double width)
{
}
public static double volumeCube(double length, double width, double height)
{
}
}

All properties (fields) and methods (functions) are contained by the class (appear between an
enclosing {} block. That is, their declaration appears inside the class declaration block.

Both of the methods are public. Thus, they can be called by procedures (methods) outside of
the class.
Page 5 of 21

Both of the methods are static. While static and instance methods will be covered later,
static methods apply to the class, rather than a class instance. Thus, the method is called on the
class name rather than an instance of the class.

The methods are named areaRectance and volumeCube.

These methods accept arguments.
o Arguments appear in a list between the () characters.
o A comma separates each argument.
o Each argument has a data type (double), followed by the argument name.

The method named areaRectangle has two arguments named length and width. Both
have a data type of double.

The method named volumeCube has three arguments named length, width, and
height. All three have a data type of double.
In the following code block, each method’s functionality is implemented:
public class MyMath {
public static int callCount = 0;
public static double areaRectangle(double length, double width)
{
callCount++;
double result;
result = length * width;
return result;
}
public static double volumeCube(double length, double width, double height)
{
callCount++;
double result;
result = length * width * height;
return result;
}
}
Make note of the following:

The first statement in each method increments the value of the variable callCount. Thus, this
variable is a counter and stores the number of times the class’s procedures have been called.

The next statement declares a local variable named result having a data type of double.

The next statement contains an assignment statement. The arguments are multiplied together
to calculate the area and volume, respectively.
Page 6 of 21

The final statement (return) returns the result from the procedure. Note that the data type of
the return value is the same as the variable’s data type.

Both methods return a value having a data type of double.
HANDS-ON ACTIVITY – Creating the MyMath class
In this sequence of steps you will:

Create a new Java project.

Add the MyMath class.

Add a class named NumericJavaMain containing the program’s entry point. The main procedure
will call the members of the MyMath class.
1. Create a new project as you did in the first lab. On the Eclipse menu, click File, New, Java
Project. Name the project NumericJava.
2. Next, you will create the NumericJava class containing the main procedure. Click File, New,
Class.
3. Name the class NumericJavaMain. Make sure to check the box titled public static void
main(String[], args), so that Eclipse will create the main procedure. You will write the code for
this procedure later.
4. Click Finish to create the class.
5. Next, create the MyMath class. Click File, New, Class. Name the class MyMath. This time, do not
create the main procedure because a program should have only one entry point.
6. Next, create the field and methods. Be sure to create the following code in the class named
MyClass, rather than the class containing the main procedure.
public class MyMath {
public static int callCount = 0;
public static double areaRectangle(double length, double width)
{
}
public static double volumeCube(double length, double width,
double height)
{
}
}
You will write the code for these procedures in a moment.
Page 7 of 21
Working with Numbers
This section briefly discusses how to use the Java numeric data types, type conversion between them,
and how to convert strings to numbers. You should already be familiar with numeric data types. So this
section focuses on type conversion.

First, Java implicitly performs what is called widening type conversion. Simply put, more
restrictive types will be implicitly converted to less restrictive types. For example, a byte, to
short, to int, to long, to float to double.

Second, you must explicitly perform what is called narrowing type conversion using a cast. Less
restrictive types will not be implicitly converted to more restrictive types. In these cases,
numeric overflow or underflow will cause loss of information to occur. Casts will be discussed in
more detail later.
Converting Data from Strings to Numbers
In Java, strings must be explicitly converted to numbers for use in arithmetic and other operations. The
Number subclasses (Byte, Integer, Double, Float, Long, and Short, provide a method named
parseXXX that converts a string to an object of the desired type, where XXX is one of the Number
subclasses.
When input is entered by the user, the value usually has a data type of String. Each data type has a
method that will convert a string to its corresponding numeric type For example:

The Integer.parseInt method takes one argument, a String, converts it to a number,
and returns the numeric value. If the value cannot be converted, an exception will be thrown.
Exceptions have not been discussed yet.
string s = 42;
int i = Integer.parseInt(s);

The Float.parseFloat method converts a string to a Float.

The Double.parseDouble method converts a string to a Double.

Note that there are similar methods for the other primitive data types.
The following example reads a string from the user, and then converts that string to a double.
double length = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Length:");
String currentLengthInput = scanner.next();
length = Double.parseDouble(currentLengthInput);
Page 8 of 21

The Scanner, discussed in the first lab, gets a string from the user and the next method gets
the string from the user and returns the value in the variable.

Finally Double.parseDouble(currentLengthInput) converts the string to a double
and stores the result in the variable length. This numeric variable can be used in arithmetic
operations.
Operators
Just like most languages, Java supports operators. Operators are categorized as arithmetic, relational,
and logical operators.
The following table lists the Java arithmetic operators. With the exception of modulus arithmetic, the
operator names are the same for both Visual Basic and Java. For the following table, assume that the
variable A contains 4, and the variable B contains 2.
Operator
+
*
/
%
++
--
Description
Addition
Subtraction
Multiplication
Division
Modulus operator. Returns the remainder of
integer division
Increment
Decrement
Example
C = A +
C = A –
C = A *
C = A /
C = A %
B;
B;
B;
B;
B;
//
//
//
//
//
6
2
8
2
0
C = A++ // 5
C = A-- // 4
Relational operators in Java are the same as in other languages such as C# or C++. They compare the
values of two operands and return true or false. In the following table, assume that the variable A
contains 4 and the variable B contains 2.
Operator
==
!=
>
<
>=
<=
Description
Equality
Inequality
Greater than
Less than
Greater than or equal to
Less than or equal to
Example
(A == B) // false
(A != B) // true
(A > B) // true
(A < B) // false
(A >= B) // true
(A <= B) // false
Logical operators are used to create compound statements. They work similar to the words “and” and
“or” in English.
Operator
&&
||
!
Description
Logical AND operator
Logical OR operator
Logical NOT operator
Example
(true && true) // true
(true || true) // true
(!true) // false
Page 9 of 21
HANDS-ON ACTIVITY – Completing the MyMath class
In the following steps, you will:

Complete the code for the MyMath class to calculate the area and volume, and return the
result.

Complete the code for the main procedure to get the user input, call the class methods, and
display the output.
1. Complete the MyMath class by entering the following highlighted code. Make sure that you
enter the code in the MyMath class not the NumericJavaMain class.
public static int callCount = 0;
public static double areaRectangle(double length, double width)
{
callCount++;
double result;
result = length * width;
return result;
}
public static double volumeCube(double length, double width,
double height)
{
callCount++;
double result;
result = length * width * height;
return result;
}
Note the following about the preceding statements.

The preceding statements increment the value of the variable callCount. This value will be used
later in the tutorial.

Each procedure declares a variable result having a data type of double.

The arithmetic expression calculates the area and volume using the arguments, and stores the
result of the calculation in result.

The value of the variable result is returned from the procedure.
1. Complete the main method by entering the following code:
public static void main(String[] args) {
Page 10 of 21
double
double
double
double
double
length = 0;
width = 0;
height = 0;
area;
volume;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Length:");
String currentLengthInput = scanner.next();
length = Double.parseDouble(currentLengthInput);
System.out.print("Enter Width:");
String currentWidthInput = scanner.next();
width = Double.parseDouble(currentWidthInput);
System.out.print("Enter Height:");
String currentHeightInput = scanner.next();
height = Double.parseDouble(currentHeightInput);
area = MyMath.areaRectangle(length, width);
volume = MyMath.volumeCube(length, width, height);
scanner.close();
System.out.print("Area: ");
System.out.println(area);
System.out.print("Volume: ");
System.out.println(volume);
}

The first group of statements declares the numeric variables that will store the input data and
the results.

The next statement group creates the Scanner, displays a prompt, and reads the input. The
input is then converted to a double.

The next group of statement use the Scanner to get the width and height.

The MyMath methods are then called. Note the MyMath class name is followed by the method
name (areaRectangle), followed by the method’s arguments. The result is stored in the variable.

The final group of statements close the Scanner, and print the results.
1. Run the program. Enter input values into the Console View as shown in the following figure. The
program should display the results and then end.
Page 11 of 21
Working with Strings
Like most languages, a string is a sequence of characters. In Java, strings are both reference types and
objects. Strings are created from the String class, which is immutable. In other words, once a string is
declared, it cannot be changed. The String class supports a number of methods. Selected methods
appear in the following table
Method
concat
length
replace
startsWith
/ endsWith
substring
Trim
Description
Concatenates two strings.
Note the + operator can
also be used for string
concatenation
Returns the number of
characters in the string.
Replaces one substring
with another string
Returns true if this string
starts or ends with a
particular substring
Returns one or more
consecutive characters
from a string
Removes leading and
trailing whitespace from a
string
Example
int l = s.length()
String result;
result = s.replace("Ekedahl", "Zaphod");
Working with Dates
First, note that operations on dates and times have changed. The JDK 8 release provides a more
comprehensive date and time model in the API java.time. It has similar methods in the java.util
package.
The Date object represents an instant in time, and the Date constructor create a new Date and
initializes its value to the current date.
Date d = new Date();
To display a date to the user, it must be converted to a string.
String s;
s = d.toString();
Page 12 of 21
Dates will be discussed in more detail we they are used.
Decision-making Statements
The Java decision-making statements work the same way as decision-making statements in other
languages. There are three forms of the if statement:

The if-then statement is often referred to as a one-way if statement.

The if-then-else statement is often referred to as a two-way if statement.

The if-then-elseif-else statement is often referred to as a multi-way if statement.
In any form of an if statement, the condition must evaluate to a boolean value. The condition must
be enclosed in parenthesis (). Following each condition, is a block of statements enclosed in {}
characters just as any block.
The following code segment shows a one-way if statement:
int gradeNumber = 60;
boolean passing;
if (gradeNumber > 60)
{
passing = true;
}
In the above statement, the if statement tests whether the variable gradeNumber is greater than the
literal value 60. If it is, the statement in the if block executes, and the variable passing is set to true.
The following code segment shows a two-way if statement:
int gradeNumber = 60;
boolean passing;
if (gradeNumber > 60)
{
passing =true;
}
else
{
passing = false;
}
In the above statement, the if statement tests whether the variable gradeNumber is greater than the
literal value 60. If it is, the statement in the if block executes, and the variable passing is set to true.
Otherwise, the condition is false, so the variable passing is set to false.
The following code segment shows a multi-way if statement:
Page 13 of 21
if (gradeNumber > 90)
{
letterGrade = "A";
}
else if (gradeNumber > 80)
{
letterGrade = "B";
}
else if (gradeNumber > 70)
{
letterGrade = "C";
}
else if (gradeNumber > 60)
{
letterGrade = "D";
}
else
{
letterGrade = "F";
}
The above multi-way if statement first tests whether the numeric grade is greater than 90. If it is, the
letter grade “A” is assigned to the variable letterGrade If the numeric grade is not greater than 90, then
the next condition is tested. If the numeric grade is greater than 80, then the letter grade “B” is
assigned. The process continues until all conditions have been tests or a conditions becomes true.
A specialized form of an if statement is called the switch statement. A switch statement can be
used when the expression to be tested contains an integral or enumerated value, or a String object.

Like an if statement, the switch statement has a condition. However, this condition need not
evaluate to a Boolean value.

Following the switch statement is a block enclosed in {}. The body of the switch statement
is known as a switch block.

The statement(s) in the switch block are labeled with one or more case labels and an
optional default label.

The break keyword causes the case to exit.
The following code segment shows an example of the switch statement:
switch (Day)
{
case 0:
{
DayString = “Sunday”;
break;
}
case1:
{
Page 14 of 21
DayString = “Monday”;
break;
}
case2:
{
DayString
break;
}
case3:
{
DayString
break;
}
case4:
{
DayString
break;
}
case5:
{
DayString
break;
}
case6:
{
DayString
break;
}
= “Tuesday”;
= “Wednesday”;
= “Thursday”;
= “Friday”;
= “Saturday”;
}
Exceptions
Run time errors, called exceptions, happen when an executable statement tries to do something that
cannot be done. For example, trying to convert a non-numeric string to a number will cause an
exception to occur. In Java, exceptions are really objects. When the exception is thrown (error occurs),
the Java runtime creates an instance of a class that is derived from the java.lang.Exception class. There
are many different exception classes.
Exceptions can be handled (caught) by implementing a form of a decision making statement called a try
catch block as follows:
Page 15 of 21
The following code segment show a sample exception handler that you will write in this section:
The above function illustrates an exception handler.

The statements in the try block attempt to convert the String argument to a double.

If the value can be converted, the if statement executes so as to test that the value is positive,
and returns true or false, accordingly.

If the value cannot be converted to a double, then an exception is thrown. The data type of
the exception is NumberFormatException. The value false is returned from the method
indicating that the value is not legal.
HANDS-ON ACTIVITY – Input Validation
As you should be aware, input validation is important as it can prevent a program from crashing when
the user enters invalid input. In this activity, you will create another class named ValidateInput. It will
contain methods that to validate the input entered by the user. The application, as it exists so far, will
throw an exception if a non-numeric value is entered where a numeric value is expected. The following
figure shows the error that will be thrown if the user enters invalid input.
Page 16 of 21
1. Create a new class named ValidateInput. Do not create a main procedure in this class.
Note that you will use this class and expand upon it as you progress through the course.
2. Add the following code to the ValidateInput class:
public class ValidateInput {
public static boolean isNumeric(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
public static boolean isDouble(String str)
{
try
{
double d = Double.parseDouble(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
public static boolean isPositiveDouble(String str)
{
try
{
Page 17 of 21
double d = Double.parseDouble(str);
if (d > 0)
{
return true;
}
else
{
return false;
}
}
catch(NumberFormatException nfe)
{
return false;
}
}
public static boolean isInteger(String str)
{
try
{
int i = Integer.parseInt(str);
}
catch(NumberFormatException nfe)
{
return false;
}
return true;
}
public static boolean isPositiveInteger(String str)
{
try
{
int i = Integer.parseInt(str);
if (i > 0)
{
return true;
}
{
return false;
}
}
catch(NumberFormatException nfe)
{
return false;
}
}
}
Note the following about the above code:

The class contains methods named isNumeric, isDouble, isPositiveDouble,
isInteger, and isPositiveInteger. The all work similarly.
Page 18 of 21

Each method returns true if argument’s value is correct and false otherwise.

The parseDouble or parseInt method is called to determine whether the argument can
be converted to a number.

If it can, the result is stored in the variable d.

If the variable cannot be converted to a number, an exception is thrown and the statement in
the catch block executes. The value false is returned.

The functions isPositiveDouble and isPostiveInteger have an additional test. They
check to determine that the value is greater than zero.
3. Modify the code in the main procedure as follows to call the validation functions that you just
wrote.
public class NumericJavaMain {
public static void main(String[] args) {
double length = 0;
double width = 0;
double height = 0;
double area;
double volume;
boolean error = false;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter Length:");
String currentLengthInput = scanner.next();
if (ValidateInput.isPositiveDouble(currentLengthInput))
{
length = Double.parseDouble(currentLengthInput);
}
else
{
error = true;
}
System.out.print("Enter Width:");
String currentWidthInput = scanner.next();
if (ValidateInput.isPositiveDouble(currentWidthInput))
{
width = Double.parseDouble(currentWidthInput);
}
else
{
error = true;
}
Page 19 of 21
System.out.print("Enter Height:");
String currentHeightInput = scanner.next();
if (ValidateInput.isPositiveDouble(currentWidthInput))
{
height = Double.parseDouble(currentHeightInput);
}
else
{
error = true;
}
if (error)
{
System.out.println("Invalid input detected");
scanner.close();
return;
}
else
{
area = MyMath.areaRectangle(length, width);
volume = MyMath.volumeCube(length, width, height);
scanner.close();
System.out.print("Area: ");
System.out.println(area);
System.out.print("Volume: ");
System.out.println(volume);
}
}
}
Try it on your Own
1. Expand the validation class to contains method counterparts named isNegativeInteger and
isNegativeDouble that will test whether a value is negative and return true or false, accordingly.
2. Try creating a function that will compute the area of a circle given the circle’s radius. Name the
function areaCircle.
Page 20 of 21
3. Try creating a function that will compute the volume of a cylinder.
4. Write the code to test these functions.
Page 21 of 21