DATA TYPES AND EXPRESSIONS IN JAVA
TOPICS
Primitive data types in Java
Declarations
Arithmetic Operators
The Assignment Operator
The Increment (++) and Decrement (--) Operators in Java
Operator
precedence
Type casting in
Java
Additional Java Programming Concepts:
String
concatenation in Java
Named constants/static class constants
in Java
Program #1: Simple Arithmetic Operators Example
Program #2: Simple Increment/Decremet
Operators Example
Program #3: Mixed Expressions Example
Program #4: BMI Program Example
Program #5: String Concatenation Example
OUTLINE
Internally, the computer stores all data as 0s and 1s (binary). All
programming languages have the notion of data types and ask the programmer to
specify what type of data is being manipulated (integer, real number,
character, string.)
Data type = a set of data values (called domain) and a set of operations
on those values. The data type determines:
· How the data is internally represented in the computer.
· Storage size.
· Range of values.
· What processing/operations the computer can perform on it.
Java primitive types: Java's built-in simple data types for numbers, text
characters, and logic ==>Java has eight primitive types to represent simple
data. Types that are not primitive are called object types (to be discussed
later.)
Of the eight primitive types available in Java, we will mostly use the following four this semester:
- int: This type is used to represent integers, which are whole numbers such as 49 or –37. Comma and decimal point not allowed.
- double: This type is used to represent numbers that include a decimal fraction, such as 3.14159265. In Java, such values are called floating-point numbers; the name double comes from the fact that the representation uses twice the minimum precision. Must contain a decimal point; must contain a digit to left and right of decimal point. Comma not allowed.
- boolean: This type represents a logical value (true or false).
- char: This type represents a single character. Must contain a single character within single quotes.
The
following table shows the storage size, default values, and data domains (range
of values) for all eight of Java’s primitive types:
Note: In addition to these eight primitive data types, Java also
provides special support for character strings via the java.lang.String
class. Strings must be contained within double quotes. Enclosing characters
within double quotes will automatically create a new String object (for example, String s = "Hello
World!";). Once created, the values of string objects cannot be
changed. The String class
is not technically a primitive data type, but most programmers tend to think of
it as such. We will discuss more about the String class later.
Declaration: the mechanism used to define/declare
identifiers. For data objects, two attributes of an identifier are specified in
the declaration: (1) the data type associated with the identifier and (2)
whether the identifier represents a variable or a constant.
A declaration tells the compiler to allocate enough memory to hold a value of a
particular data type, and to associate the identifier with that memory
location.
We use declarations to define for the compiler the terms that we will use in
the program (like defining technical terms before they are used in a paper).
In Java, you must declare a variable before you can use it. The
declaration establishes the name and type of the variable and, in most cases,
specifies the initial value as well. The most common form of a variable declaration
is
DataType VariableName = value;
where DataType is the name of a Java
primitive type or class, VariableName is an identifier that
indicates the name of the variable, and value is an expression specifying
the initial value.
Expression: A data value, or a set of operations that compute a data
value. The simplest expression is a literal value. A complex expression can use
operators and parentheses. The values to which an operator applies are called
operands.
The simplest terms that appear in expressions are constants and variables.
The value of a constant does not change during the course of a program. A
variable is a placeholder for a value that can be updated as the program runs.
A variable in Java is most easily envisioned as a box capable of storing a
value.
Example:
int salary = 60000;
60000 |
Each variable has the following attributes:
Note:
The name and
type of a variable are fixed. The value changes whenever you assign a new
value to the variable.
As in most languages, computation in Java is specified in the form of
arithmetic expressions that closely resemble expressions in mathematics.
Calculations are performed with expressions, and expressions are made up of
constants, variables, and operators. Operators in Java usually appear between two
subexpressions, which are called its operands.
Operators that take two operands are called binary operators. The -
operator can also appear as a unary operator, as in the expression -x,
which denotes the negative of x (unary plus is very rarely used; numbers
without sign are assumed to be positive numbers.) The operators allowed in an
expression depend on the data types of the constants and variables involved in
the expression.
1. Arithmetic Operators: The most
common operators in Java are the arithmetic operators: + (addition), - (subtraction), *(multiplication), / (division), and % (modulus, or
remainder).
7 / 2 = 3
7.0 / 2.0 = 3.5
Note: Division by 0 is illegal
(runtime error!)
15 / 8 = 1
15.0 / 8 = 1.875
18 / 4 = 4
18 % 4 = 2
Note: % by 0 is illegal (runtime
error!)
2. The Assignment Operator: stores into a variable the
value of an expression (arrangement of identifiers, literals, and operators
that can be evaluated to compute a value of a given type).
VariableName
= Expression;
x += 15; <==> x = x + 15;
x -= 5; <==> x = x - 5;
x *= 10; <==> x = x * 10;
x /= 3; <==> x = x / 3;
In
general:
Shorthand |
Equivalent longer version |
<variable> += <value>
; |
<variable> =
<variable> + <value> ; |
<variable> -= <value>
; |
<variable> =
<variable> - <value> ; |
<variable> *= <value>
; |
<variable> =
<variable> * <value> ; |
<variable> /= <value>
; |
<variable> =
<variable> / <value> ; |
<variable> %= <value>
; |
<variable> =
<variable> % <value> ; |
3. The Increment (++) and
Decrement (--) Operators: unary
operators (take one operand) (x++, ++x, x--, --x)
int
a;
int
n = 13;
a = ++n * 3; //n = 14, a = 42
int
a;
int
n = 13;
a = n++ * 3; //n = 14, a = 39
You can specify the order of the operations by inserting ( ) parentheses (square brackets are not allowed in Java). They make the expressions easier to read and less prone to programmer error. If you omit parentheses, Java will follow rules (called precedence rules) that determine the order in which the operators are performed (who goes first). Precedence rules are similar to rules used in algebra.
Precedence
Operator
Description
Associativity
Highest
Unary Operators
(+, -, ++, --, !)
(right-to-left)
*
Multiplication
(left-to-right)
/
Division
(left-to-right)
%
Modulus (Remainder)
(left-to-right)
+
Addition
(left-to-right)
-
Subtraction
(left-to-right)
Lowest
=, +=, -=, *=, /=
Assignment
(right-to-left)
Higher
precedence determines which operator is applied first in an expression having
several operators. Parentheses will override the precedence rules.
Left-to-right associativity means that in an expression having 2 operators with
the same priority, the left operator is applied first (right-to left
associativity is what?). All binary operators except for the assignment
operators are evaluated from left to right; assignment operators are evaluated right
to left.
Examples:
The Java programming language allows you to construct compound expressions from various smaller expressions as long as the data type required by one part of the expression matches the data type of the other. What about the use of mixed type expressions and assignments? What if we mix integer and floating-point values together in an assignment statement or in an arithmetic expression?
Type coercion = automatic (implicit) conversion of a value from one data type to another. If you are not careful, implicit type coercion can generate unexpected results. Example:
int int_number; //int_number can hold ONLY integer values.
double float_number; //float_number can hold ONLY floating-point values.
float_number = 20; // Java will convert 20 to 20.0 - type coercion
int_number = 5.5; // ERROR
float_number = 2 * int_number + 3; // type coercion to double: 13.0
float_number = 5 * int_number - 7; // convert the result to double: 18.0
int_number = 7.8 / float_number - 12.5; // ERROR
Observation: Converting from int to double doesn't cause loss of
information (12 =
12.0); converting from double
to int
will generate a compiling error. Take a look at Program
#4
To make the programs clear and error free we can use type casting (or type
conversion)
Type casting = The explicit conversion of a
value from one data type to another. The unary cast operator is used to
explicitly convert a type, truncating the result, if necessary (i.e., with
information loss) and it has the following form:
(dataTypeName) expression.
First,
the expression is
evaluated; next, its value is treated temporarily as a value of the type
specified by dataTypeName.
Examples:
float_number
= (double)(15/2 * int_number
+ 3);
int_number
= (int)(7.8/float_number -
12.5);
Mixed
types expression
= expression that contains operands of different data types. Java automatically
promotes (converts) mixed-type values to a common type if they are compatible
(that is, both can represent the same value) and loss of information will not
occur. For example, for variable declarations int
i = 15 and double x = 10.8,
i
+ x = 15 + 10.8 = 15.0 + 10.8 = 25.8
i
+ (int)x = 15 + (int)10.8 = 15 + 10 = 25
Observation: Relying on implicit type
coercion within expressions and across the assignment operator can lead to
unexpected results in two situations: (1) assigning a floating point value to
an integer variable (error) and (2) unintended integer division. Mixing types can
yield many errors. Example:
int
sum = 90;
int
count = 120;
double avg; //expected result avg = 0.75
avg
= sum / count; // Wrong, with implicit type
coercion; avg is 0.0!
avg
= (double)(sum / count);// Still wrong, with type
casting; avg still 0.0!
avg
= (double)sum / (double)count; // Correct, avg is 0.75;
avg
= (double)sum / count; // Correct, avg is 0.75;
avg
= sum / (double)count; // Correct, avg is 0.75;
1. Output using String Concatenation:
Data types reminder: A string is a sequence of zero or more characters and they
are enclosed in double quotation marks (" ", not single quotation
marks, as in the char
data type). Because strings are not primitive data types, Java provides the
class String to
effectively process them. This class is very common and it is used very
frequently - will be discussed more in depth later; for now we just need to
know how to use strings in output statements with the concatenation operation.
Output reminder: We have seen output sent
to the console window with System.out.println. Unfortunately, you
can pass just one value to println, which is a limitation - to get around it, Java provides the concatenation operation to put
together more pieces into one long string.
Concatenation: Combining several strings into a single string, or
combining a string with other data into a new, longer string. We use the
addition (+) operator to concatenate these pieces together. The result is an
expression (including numbers and text) that can be evaluated.
Examples (Look at Program #5 to see the
implementation in Java):
"The sum =
" + 10 + 20 <==> The sum = 1020
"The sum = "
+ (10 + 20) <==> The sum = 30
"The sum of " + 10 + " and " + 20 + " =
" + (10 + 20) <==> The sum of 10 and 20 = 30
Note: A variation of the println statement in Java is a print statement.
System.out.print("First part.
");
System.out.print("Second
part. ");
System.out.print("Third
part.");
will generate the output:
First part.
Second part. Third part.
The
statements
System.out.println("First part.
");
System.out.println("Second
part. ");
System.out.println("Third
part.");
will generate the output:
First part.
Second part.
Third part.
Class constant: A variable that can be seen throughout the entire
program. The value of a constant can only be set when it is declared. It can not be changed while the program is running.
Syntax: public
static final <type> <name> = <value> ;
Note #1: Because everything must be part of a class in Java, the usual
way to declare a constant is as a "class constant."
Note #2: In Java, static
and final are
reserved words. The reserved word final specifies that the value stored is fixed and cannot
be changed.
Naming conventions reminder: The names of constants are written in all
uppercase letters. If the name you choose is a run-together-word, then the
words are separated with the underscore character.Choose
meaningful names that explain what they represent. By using constants programs
become more readable and adaptable (any future changes are easier to make
because if the fixed values change, you don't need to edit the entire program
and make the appropriate changes; instead, you can make the change at just one
place, where the constant was dwclared). Like
variables, constants can be declared anywhere, but because they are generally
used by multiple methods, we generally declare constants outside of methods,
just before main(). In this way, all
methods can access the constants, and the constants are said to be
"global" to the program (class).
Examples:
public static final int DAYS_IN_WEEK = 7;
public static final int MAX_SIZE = 100;
public static final double OVERTIME_FACTOR = 1.5;
public static final double INTEREST_RATE = 3.5;
public static final char BLANK = ' ';
Note
#3: In Java,
the default data type for floating-point numbers is double (not float) --> if you declare a
named constant of type float, you must specify it in declaration (if not -->
compiling error)
public static final float
INTEREST_RATE = 3.5f; //the letter f at the end
specifies that 3.5 is a float value
public static final
float OVERTIME_FACTOR = 1.5f; //the letter f at the
end specifies that 1.5 is a float value
Reminder: float values are stored on 4 bytes, double values are stored on 8 bytes, but memory size is not that important with modern computers --> use the type double to work with floating-point values.
Program #1: Arithmetic Operators Example
class ArithmeticOp {
public static void main (String[] args){
int n = 13;
System.out.println(n);
n = n - 3; // n is now 10
//Same as n -= 3;
System.out.println(n);
n = n * 2; // n is now 20
//Same as n *= 2;
System.out.println(n);
n = n / 3; // n is now 6; lost decimals
//Same as n /= 3;
System.out.println(n);
n = n + 18; // n is now 24
//Same as n += 18;
System.out.println(n);
n = n % 5; // n is now 4
//Same as n %= 5;
System.out.println(n);
}
}
Program #2: Increment/Decrement Operators Example:
class IncrBoolOp {
public static void main(String[] args){
int n = 1;
System.out.println(n);
n++; // n is now 2; Same as n = n + 1;
System.out.println(n);
n++; // n is now 3; Same as n = n + 1;
System.out.println(n);
n--; // n is now 2; Same as n = n - 1;
System.out.println(n);
boolean dataOK = true;
System.out.println(dataOK);
// true
System.out.println(!dataOK);// false
}
}
Program #3: Mixed expressions, type casting and string concatenation example:
class MixedExpr {
public static void main(String[] args){
System.out.println("5 / 2 + 6.5 = " + (5 /
2 + 6.5));
System.out.println("5 + 16.8 / 2 = " + (5 +
16.8 / 2));
System.out.println("5 * 3 + 8 / 3 - 6.5 = "
+ (5 * 3 + 8 / 3 - 6.5));
System.out.println("(7 * (10 - 5) % 3) * 4.2 + 9
= " + (7 * (10 - 5) % 3) * 4.2 + 9);
System.out.println("5 * 7 + 19 / 5 + 37 % 11 -
15.8 = " + (5 * 7 + 19 / 5 + 37 % 11 - 15.8 ));
System.out.println("(double)(87) / 4 = " +
(double)(87) / 4);
System.out.println("(double)(87 / 4) = " +
(double)(87 / 4));
System.out.println("(int)(5.9
+ (double)(25) / 2) = " + ((int)(5.9 +
(double)(25) / 2)));
System.out.println("(int)(5.9
+ (double)(25 / 2)) = " + (int)(5.9 +
(double)(25 / 2)));
}
}
Sample Output:
5 / 2 + 6.5 = 8.5
5 + 16.8 / 2 = 13.4
5 * 3 + 8 / 3 - 6.5 =
10.5
(7 * (10 - 5) % 3) *
4.2 + 9 = 8.49
5 * 7 + 19 / 5 + 37 %
11 - 15.8 = 26.2
(double)(87) / 4 =
21.75
(double)(87 / 4) =
21.0
(int)(5.9
+ (double)(25) / 2) = 18
(int)(5.9
+ (double)(25 / 2)) = 17
Program #4: BMI (Body Mass Index)
Program Example:
Version #1 |
Version #2
(With Errors) |
public class BMICalculator
{ |
public class BMICalculator
{ |
Output: Current BMI:
27.976530612244897
|
2 errors found: |
Program #5: String Concatenation Example:
class Concatenation
{
public static final int MAX = 3;
public static void main(String[] args){
System.out.println("Will show " + MAX +
" examples of string concatenation.");
System.out.println("The sum = " + 10 + 20);
System.out.println("The sum = " + (10 +
20));
System.out.println("The sum of " + 10
+ " and " + 20 + " = " + (10 + 20));
}
}
Sample Output:
Will show 3 examples
of string concatenation.
The sum = 1020
The sum = 30
The sum of 10 and 20 =
30
Additional
Resources:
1. (Oracle) The Java Tutorials: Primitive Data Types http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.htmll
2. (Oracle) The Java Tutorials: Arithmetic Operators http://docs.oracle.com/javase/tutorial/java/nutsandbolts/op1.html
3. (Oracle) The Java Tutorials: Operators http://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
References:
Building Java Programs: A Back to Basics Approach, by Stuart Reges, and Marty Stepp, Addison
Wesley, 2008.