Computer Programming 1: Using Data

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 75

Computer

Programming 1

Using Data
Learning Objectives
Learning Objectives

At the end of the chapter, students are expected to:


a) Familiarized with the used of constant, variables and data types
b) Display data and perform arithmetic
c) Use the Scanner class to accept keyboard input
d) Use the JOptionPane class for GUI input
Declaring and Using
Constants and Variables
Declaring and Using Constants and Variables

A data item is constant when its value cannot be changed while a


program is running. For example, when you include the following
statement in a Java class, the number 459 is a constant: 

System.out.println(459);
Declaring and Using Constants and Variables

Every time an application containing the constant 459 is executed, the


value 459 is displayed. Programmers refer to a number such as 459 in
several ways:

●It is a literal constant because its value is taken literally at each use.
●It is a numeric constant as opposed to a character or string
constant.
●It is an unnamed constant as opposed to a named one, because no
identifier is associated with it.
Declaring and Using Constants and Variables

Instead of using constant data, you can set up a data item to be variable. A
variable is a named memory location that can store a value. A variable can
hold only one value at a time, but the value it holds can change. For
example, if you create a variable named ovenTemperature, it might hold 0
when the application starts, later be altered to hold 350, and still later be
altered to hold 400.
Declaring and Using Constants and Variables

Whether a data item is variable or constant, in Java it always has a data


type. An item’s data type describes the type of data that can be stored
there, how much memory the item occupies, and what types of operations
can be performed on the data. Java provides for eight primitive types of
data. A primitive type is a simple data type.
Declaring and Using Constants and Variables

The eight data types are called primitive because they are simple and
uncomplicated. Primitive types also serve as the building blocks for more
complex data types, called reference types, which hold memory addresses.
A primitive data type specifies the size and type of variable values, and it
has no additional methods.
Declaring Variables
Declaring Variables

A variable declaration is a statement that reserves a named memory


location and includes the following:

●A data type that identifies the type of data that the variable will
store
●An identifier that is the variable’s name
●An optional assignment operator and assigned value, if you want a
variable to contain an initial value
●An ending semicolon
Declaring Variables

Variable names conventionally begin with lowercase letters to


distinguish them from class names. However, as with class names, a
program can compile without error even if names are constructed
unconventionally. Beginning an identifier with a lowercase letter and
capitalizing subsequent words within the identifier is a style known as
camel casing. An identifier such as lastName resembles a camel because
of the uppercase “hump” in the middle.
Declaring Variables

For example, the following declaration creates a conventionally named int


variable, myAge, and assigns it an initial value of 25:

int myAge = 25;


Declaring Variables

This declaration is a complete, executable statement, so it ends with a


semicolon. The equal sign ( = ) is the assignment operator. Any value to
the right of the assignment operator is assigned to the memory location
named on the left. An assignment made when you declare a variable is an
initialization; an assignment made later is simply an assignment. Thus,
the first statement that follows is an initialization, and the second is an
assignment:

int myAge = 25;


myAge = 42;
Declaring Variables

You declare a variable just once in a method, but you might assign new
values to it any number of times. (A compiler error message will be
displayed when there is a conflict between two variables with the same
name.) You can declare multiple variables of the same type in separate
statements. You also can declare two or more variables of the same type in
a single statement by separating the variable declarations with a comma,
as shown in the following statement: 

int height = 70, weight = 190;


Declaring Variables

By convention, many programmers declare each variable in its own


separate statement, but some follow the convention of declaring multiple
variables in the same statement if their purposes are closely related.
Remember that even if a statement occupies multiple lines, the statement
is not complete until the semicolon is reached.
Declaring Variables

You can declare as many variables in a statement as you want, as long as


the variables are the same data type. However, if you want to declare
variables of different types, you must use a separate statement for each
type.
Declaring Named Constants
Declaring Named Constants

A variable is a named memory location for which the contents can change.
If a named location’s value should not change during the execution of a
program, you can create it to be a named constant. A named constant is
also known as a symbolic constant. A named constant is similar to a
variable in that it has a data type, a name, and a value. A named constant
differs from a variable in several ways:

● In its declaration statement, the data type of a named constant is


preceded by the keyword final.
Declaring Named Constants

● A named constant can be assigned a value only once, and then it cannot
be changed later in the program. Usually you initialize a named
constant when you declare it; if you do not initialize the constant at
declaration, it is known as a blank final, and you can assign a value
later. Either way, you must assign a value to a constant before it is
used.

● Although it is not a requirement, named constants conventionally are


given identifiers using all uppercase letters, using underscores as
needed to separate words.
Declaring Named Constants

● A named constant can be assigned a value only once, and then it cannot
be changed later in the program. Usually you initialize a named
constant when you declare it; if you do not initialize the constant at
declaration, it is known as a blank final, and you can assign a value
later. Either way, you must assign a value to a constant before it is
used.

● Although it is not a requirement, named constants conventionally are


given identifiers using all uppercase letters, using underscores as
needed to separate words.
The Scope of Variables and
Constants
The Scope of Variables and Constants

A data item’s scope is the area in which it is visible to a program and in


which you can refer to it using its simple identifier. A variable or constant
is in scope from the point it is declared until the end of the block of code
in which the declaration lies. A block of code is the code contained
between a set of curly braces. So, for example, if you declare a variable or
constant within a method, it can be used from its declaration until the end
of the method unless the method contains multiple sets of curly braces.
Then, a data item is usable only until the end of the block that holds the
declaration.
Learning About Integer Data
Types
Byte

The byte data type can store whole numbers from -128 to 127. This can be
used instead of int or other integer types to save memory when you are
certain that the value will be within -128 and 127:
Short

The short data type can store whole numbers from -32768 to 32767:
Int

The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the
preferred data type when we create variables with a numeric value.
Long

The long data type can store whole numbers from


-9223372036854775808 to 9223372036854775807. This is used when int
is not large enough to store the value. Note that you should end the value
with an "L":
Using the boolean Data Type
Using the Boolean Data Type

Boolean logic is based on true or false comparisons. Whereas an int


variable can hold millions of different values (at different times), a
variable that is the Boolean data type can hold only one of two values—
true or false.
Using the Boolean Data Type

Besides assigning true and false, you also can assign a value to a Boolean
variable based on the result of a comparison. Java supports six relational
operators that are used to make comparisons. A relational operator
compares two items; it is sometimes called a comparison operator. The
value of an expression that contains a relational operator is always true or
false.
Using the Boolean Data Type
Learning about Floating-point
Data Types
Float

The float data type can store fractional numbers from 3.4e−038 to
3.4e+038. Note that you should end the value with an "f":
Double

The double data type can store fractional numbers from 1.7e−308 to
1.7e+308. Note that you should end the value with a "d":
Using the char Data Type
Using the char Data Type

You use the char data type to hold any single character. You place constant
character values within single quotation marks because the computer
stores characters and integers differently. For example, the following are
typical character declarations:
char middleInitial = ‘M’;
char gradeInChemistry = ‘A’;
char aStar = ‘*’;
Using the char Data Type

A character can be any letter—uppercase or lowercase. It also might be a


punctuation mark or digit. A character that is a digit is represented in
computer memory differently from a numeric value represented by the
same digit.
Using the char Data Type

A variable of type char can hold only one character. To store a string of
characters, such as a person’s name, you must use a data structure called a
String. In Java, String is a built-in class that provides you with the means
for storing and manipulating character strings.
Using the char Data Type

Unlike single characters, which use single quotation marks, string


constants are written between double quotation marks. For example, the
expression that stores the name Audrey as a string in a variable named
firstName is as follows:
String firstName = "Audrey";
Using the char Data Type

You can store any character—including nonprinting characters such as a


backspace or a tab—in a char variable. To store these characters, you can
use an escape sequence, which always begins with a backslash followed
by a character—the pair represents a single character. For example, the
following code stores a newline character and a tab character in the char
variables aNewLine and aTabChar:
char aNewLine = '\n’;
char aTabChar = '\t';
Using the char Data Type

In the declarations of aNewLine and aTabChar, the backslash and


character pair acts as a single character; the escape sequence serves to
give a new meaning to the character. That is, the literal characters in the
preceding code have different values from the “plain” characters ‘n’ or ‘t’.
The table on the next slide describes some common escape sequences that
you can use with command window output in Java.
Using the char Data Type
Using the Scanner Class to
accept Keyboard Input
Using the Scanner Class to accept Keyboard
Input
Although you can assign values to variables you declare, programs
typically become more useful when a user can supply different values for
variables each time a program executes. To create interactive programs
that accept input from a user, you can use System.in, which refers to the
standard input device (normally the keyboard).
Using the Scanner Class to accept Keyboard
Input
The System.in object is not as flexible; it is designed to read only bytes.
That’s a problem, because you often want to accept data of other types.
Fortunately, the designers of Java have created a class named Scanner that
makes System.in more flexible.
Using the Scanner Class to accept Keyboard
Input
To create a Scanner object and connect it to the System.in object, you
write a statement similar to the following:
Scanner inputDevice = new Scanner(System.in);
Using the Scanner Class to accept Keyboard
Input
The portion of the statement to the left of the assignment operator,
Scanner inputDevice, declares an object of type Scanner with the
programmer-chosen name inputDevice, in exactly the same way that int x;
declares an integer with the programmer-chosen name x.
Using the Scanner Class to accept Keyboard
Input
The portion of the statement to the right of the assignment operator, new
Scanner(System.in), creates a Scanner object that is connected to the
System.in property. In other words, the created Scanner object is
connected to the default input device. The keyword new is required by
Java; you will use it whenever you create objects that are more complex
than the primitive data types.
Using the Scanner Class to accept Keyboard
Input
The assignment operator in the Scanner declaration statement assigns the
value of the new object—that is, its memory address—to the inputDevice
object in the program.
Using the Scanner Class to accept Keyboard
Input
The Scanner class contains methods that retrieve values from an input
device. Each retrieved value is a token, which is a set of characters that is
separated from the next set by whitespace.
Using the JOptionPane Class
to accept GUI Input
Using the JOptionPane Class to accept GUI
Input
You also can accept input in a GUI dialog box using the JOptionPane
class. Two dialog boxes that can be used to accept user input are as
follows:
●InputDialog—Prompts the user for text input
●ConfirmDialog—Asks the user a question, providing buttons that
the user can click for Yes, No, and Cancel responses
Using the JOptionPane Class to accept GUI
Input
import javax.swing.JOptionPane;
public class HelloNameDialog
{
public static void main(String[] args)
{
String result;
result = JOptionPane.showInputDialog(null, "What is your name?");
JOptionPane.showMessageDialog(null, "Mabuhay!, " + result + "!");
}
}
 
Using Input Dialog Boxes
Using Input Dialog Boxes

An input dialog box asks a question and provides a text field in which the
user can enter a response. You can create an input dialog box using the
showInputDialog() method. Six versions of this method are available, but
the simplest version uses a single argument that is the prompt you want
to display within the dialog box. The showInputDialog() method returns a
String that represents a user’s response; this means that you can assign the
showInputDialog() method to a String variable and the variable will hold
the value that the user enters.
Using Input Dialog Boxes

An input dialog box asks a question and provides a text field in which the
user can enter a response. You can create an input dialog box using the
showInputDialog() method. Six versions of this method are available, but
the simplest version uses a single argument that is the prompt you want
to display within the dialog box. The showInputDialog() method returns a
String that represents a user’s response; this means that you can assign the
showInputDialog() method to a String variable and the variable will hold
the value that the user enters.
Using Input Dialog Boxes

A different version of the showInputDialog() method requires four


arguments that allow the programmer flexibility in controlling the
appearance of the input dialog box. The four arguments to
showInputDialog() include the following:
● The parent component, which is the screen component, such as a
frame, in front of which the dialog box will appear. If this argument is
null, the dialog box is centered on the screen.
Using Input Dialog Boxes

● The message the user will see before entering a value. Usually this
message is a String, but it actually can be any type of object.
● The title to be displayed in the title bar of the input dialog box.
Using Input Dialog Boxes

● The message the user will see before entering a value. Usually this
message is a String, but it actually can be any type of object.
● The title to be displayed in the title bar of the input dialog box.
Using Input Dialog Boxes

● A class field describing the type of dialog box; it can be one of the
following:

○ ERROR_MESSAGE,

○ INFORMATION_MESSAGE,

○ PLAIN_MESSAGE,

○ QUESTION_MESSAGE,

○ WARNING_MESSAGE.
Using Confirm Dialog Boxes
Using Using Confirm Dialog Boxes

Sometimes, the input you want from a user does not have to be typed from
the keyboard. When you present simple options to a user, you can offer
buttons that the user can click to confirm a choice. A confirm dialog box
that displays the options Yes, No, and Cancel can be created using the
showConfirmDialog() method in the JOptionPane class.
Using Using Confirm Dialog Boxes

Four versions of the method are available; the simplest requires a parent
component (which can be null) and the String prompt that is displayed in
the box. The showConfirmDialog() method returns an integer containing
one of three possible values: JOptionPane.YES_OPTION,
JOptionPane.NO_OPTION, or JOption Pane.CANCEL_OPTION.
Using Using Confirm Dialog Boxes

You can also create a confirm dialog box with five arguments, as follows:
●The parent component, which can be null
●The prompt message
●The title to be displayed in the title bar
●An integer that indicates which option button will be shown; it
should be one of the constants YES_NO_CANCEL_OPTION or
YES_NO_OPTION
●An integer that describes the kind of dialog box; it should be one of
the constants ERROR_MESSAGE, INFORMATION_MESSAGE,
PLAIN_MESSAGE, QUESTION_MESSAGE, or
Using Using Confirm Dialog Boxes

●An integer that indicates which option button will be shown; it


should be one of the constants YES_NO_CANCEL_OPTION or
YES_NO_OPTION
●An integer that describes the kind of dialog box; it should be one of
the constants ERROR_MESSAGE, INFORMATION_MESSAGE,
PLAIN_MESSAGE, QUESTION_MESSAGE, or
WARNING_MESSAGE
Understanding Type
Conversion
Using Using Confirm Dialog Boxes

When you perform arithmetic with variables or constants of the same


type, the result of the operation retains the same type. For example, when
you divide two ints, the result is an int, and when you subtract two
doubles, the result is a double. Often, however, you might want to perform
mathematical operations on operands with unlike types. The process of
converting one data type to another is type conversion. Java performs
some conversions for you automatically or implicitly, but other
conversions must be requested explicitly by the programmer.
Automatic Type Conversion
Automatic Type Conversion

When you perform arithmetic operations with operands of unlike types,


Java chooses a unifying type for the result. The unifying type is the type
to which all operands in an expression are converted so that they are
compatible with each other. Java performs an implicit conversion; that is,
it automatically converts nonconforming operands to the unifying type.
Implicit conversions also are called promotions.
Automatic Type Conversion

Highest

Lowest
Automatic Type Conversion

When two unlike types are used in an expression, the unifying type is the
one that is higher in the list in the previous figure. In other words, when
an operand that is a type lower on the list is combined with a type that is
higher, the lower-type operand is converted to the higher one. For
example, the addition of a double and an int results in a double, and the
subtraction of a long from a float results in a float.
Explicit Type Conversions
Automatic Type Conversion

You can purposely override the unifying type imposed by Java by


performing a type cast. type casting forces a value of one data type to be
used as a value of another type. To perform a type cast, you use a cast
operator, which is created by placing the desired result type in
parentheses. Using a cast operator is an explicit conversion. The cast
operator is followed by the variable or constant to be cast.
Automatic Type Conversion

● You use the char data type to hold any single character. You type
constant character values between single quotation marks and String
constants between double quotation marks. You can store some
characters using an escape sequence, which always begins with a
backslash.
● You can use the Scanner class and the System.in object to accept user
input from the keyboard. Several methods are available to convert
input to usable data, including nextDouble(), nextInt(), and nextLine().

You might also like