Notes, Part II

Download Report

Transcript Notes, Part II

Variables and Data Types
1
Variable

Definition


a location in memory, referenced by a name
(identifier), where data of a given type can
be stored, changed, and retrieved
Using variables



establish its data type and initial value
(declaration)
set/change its value (assignment, input)
use/display its value (expressions, output)
2
Example:
Using Variables
int dimecount;
// declaration
double dimevalue = 0.10; // declaration with initial
value
double totalvalue;
dimecount = Input.readInt();
// input (assignment)
totalvalue = dimecount*dimevalue; // assignment
System.out.println(totalvalue);
// output
3
OUTPUT
dimevalue
System.out.println(totalvalue);
0.10
totalvalue
5.30
dimecount
53
totalvalue = dimecount*dimevalue;
INPUT
dimecount = Input.readInt();
4
Back to
Java Program Structure

A Java program (application or applet)
is a class that consists of methods


main(), init(), paint(), action(), setup(),
onButtonPressed(), …
Each method has a body


delimited by { }
consists of a sequence of statements
(including declarations)
5
Statements

Declarations
int dimecount;
double dimevalue = 0.10;

Assignment statements
dimecount = Input.readInt();
totalvalue = dimecount*dimevalue;

Output statements
System.out.println(totalvalue);
6
Identifier

A name in a Java program


Rules in forming an identifier:




used for variables, classes, methods, ...
consists of letters, digits, and underscores (_)
should start with letter or underscore
Examples: ateneo score5 total_credit
BigBlue _one4three x if
Some identifiers are reserved words
7
Data Type




Describes a domain or pool of values
Helps a compiler impose rules
Programming language needs rules for constructing
literals for a given data type
 e.g., 234 is an integer literal, ‘A’ is a character
literal, 2.1e-3 is a double floating point literal
Some primitive data types in Java:
 int, char, float, double, boolean
8
Understanding Data Types
Important components of a data type:



Range of values
Literals
Possible operations
9
The int Data Type

Range: -2,147,483,648 to 2,147,483,647


Literals



applies to all system platforms
sequence of digits
Examples: 22, 16, 1, 426, 0, 12900
Operations: usual arithmetic operations


+, -, *, /, %
negative numbers obtained using - as prefix
10
The double Data Type

Values: decimal numbers



Literals (examples)




Range: 4.94e-324 to 1.80e+308
precision: n.nnnnn... X 10(+/-)mmm
100.5, 0.33333, 200000.0
-8E10 (-80000000000), 2.1e-3 (0.0021)
Operations: arithmetic ops (division?)
float: lower precision
11
Constants

Literal values in a program



appear often enough and may be
associated with an appropriate name
declare as a “variable with a fixed value”
Examples



public static final int MAX = 100;
public static final double PI = 3.1415926;
public static final double DIMEVALUE =
0.10;
12
Input and Output
13
I/O in Java

Text output in Java


Input in pure Java is not straightforward



System.out.print & System.out.println
need to handle exception cases
uses notions of streams and files
Trend in current applications


perform I/O through visual components
GUIs
14
Input.java


A “home made” class designed to make
console input simpler
For use in Java applications


make sure that Input.java is in your
working directory
use Input.xxx() for text input of
ints/doubles
Input.readInt(),
Input.readDouble()
15
Input Statements are
Assignment Statements
Examples:
double interestRate;
...
int count = Input.readInt();
16
Applets

To create applets



need to process GUI events
need an init() method to set up visual
objects, an action() method to specify
associated actions
use InputOutputApplet


extend InputOutputApplet instead of
Applet
define setup() and onButtonPressed()
17
Using InputOutputApplet


Make sure InputOutputApplet.class is
present in your directory
In the setup() method




addInput(“name”) to add input objects
addButton(“label”) to add a button
addOutput() to add an output area
In the onButtonPressed method


getInt(), getDouble() for retrieving data
print(), println() for printing on output area
18
Operators and Expressions
19
Operators in Java

Arithmetic operators


Special operators



+, -, *, /, %
(, ) performs grouping
= (assignment)
Other operators
20
Understanding Operators

Operands



Calculation performed


count (binary/unary)
type
value (and type) returned
Other effects
21
Example: %




Binary operation
Both operands are ints
Returns the (int) remainder when left
operand is divided by the right operand
No additional effects
22
Another Example: =




Binary operation
Left operand must be a variable
Returns the value of the right operand
Effect: value of right operand is
assigned to left operand
* Note that a = b = c = 0; is valid
23
Other Operators

Increment and decrement operators



Assignment operators


++, -post- or pre+=, -=, *=, /=, …
“Built-in” Functions


not really operators (but similar)
Math.abs(), Math.sqrt(), Math.pow(), ...
24
Post-increment Operator: ++





Example: number++
Unary operator
Operand must be a variable
Returns the (original) value of the
operand
Effect: variable is incremented
25
Pre-increment Operator: ++





Example: ++number
Unary operator
Operand must be a variable
Returns the incremented value of the
operand
Effect: variable is incremented
26
About ++

Notice that a++; and ++a; are
virtually equivalent



return value is ignored in both cases
could be used as shorthands for a = a+1;
Distinction apparent when the return
value is used
a = 5;
b = a++;
// values of a & b?
a = 5;
b = ++a;
// values of a & b?
27
Decrement Operator: -Analogous definitions for


Post-decrement
Pre-decrement
number---number
28
Assignment Operators

There is a shorthand for constructs such
as
sum = sum + number;
sum += number;

+= is an operator:

such an operator exists for virtually every
arithmetic operator



+=, -=, *=. /=, %=, ...
effect: variable is updated
returned value: the updated value
29
Built-in Functions


Provided in Java to provide for more
complex operations
Example: Math.pow()



double result = Math.pow(5.5,3.0);
can be viewed as a binary operation that
calculates some power of a number
javap java.lang.Math

prints a list of available math functions
30
Operand Types vs
Result Type


There are cases where the type of the
result differs from the types of the
operands
Examples


division between an int and a double
returns a double
Math.round() has an operand (argument)
that is a float but returns an int
31
Expressions

Expression


Uses



sequence of variables, literals, operators,
and function calls
right operand of an assignment
argument for System.out.println()
Expression-statement

an expression terminated by a semicolon
32
Strings
33
Variables Revisited

A variable holds a value
num
int num = 5;

5
A variable may instead contain a
reference
String s = “Hello”;
s
“Hello”
34
String

A special kind of data type



called a class
allows for string objects
About Strings



sequences of characters (letters, digits,
etc)
literals: formed by delimiting the sequence
of characters with " "
operations?
35
Operations on Strings

Concatenation


Obtain length of string



“Hello” + “ there” equals “Hello there”
String s = “Hello”;
int len = s.length(); // len = 5
Obtain a substring


String s = “Hello”;
String t = s.substring(0,3); // t = “Hel”
36