Docsity

Java Expressions: Primitive Data Types and Operators - Prof. Jennifer E. Walter, Study notes of Computer Science

Toggle sidebar
bg1
Chapter 3—Expressions
The Art and Science of
An Introduction
to Computer Science
ERIC S. ROBERTS
Java
Expressions
C H A P T E R 3
“What’s twice eleven?” I said to Pooh.
(“Twice what?” said Pooh to Me.)
“I think that it ought to be twenty-two.”
“Just what I think myself,” said Pooh.
—A. A. Milne, Now We Are Six, 1927
CMPU-101
Computer Science I:
Problem-Solving and Abstraction
Fall 2008
Jennifer Walter
(adapted from slides by Eric Roberts)
Expressions in Java
• The heart of the Add2Integers program from Chapter 2 is
the line
• The n1 + n2 that appears to the right of the equal sign is an
example of an expression, which specifies the operations
involved in the computation.
• An expression in Java consists of terms joined together by
operators.
• Each term must be one of the following:
– A literal constant (such as 3.14159265 or "hello, world")
– A variable name (such as n1, n2, or total)
– A method call that returns a value (such as readInt)
– An expression enclosed in parentheses
int total = n1 + n2;
that performs the actual addition.
Primitive Data Types
• Although complex data values are represented using objects,
Java defines a set of primitive types to represent simple data.
• Of the eight primitive types available in Java, the programs in
our text use only the following four:
int This type is used to represent integers, which are whole
numbers such as 17 or –53.
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 nam e double comes from the
fact that the representation uses twice the minimum precision.
char This type represents a single character and is described in
Chapter 8.
boolean This type represents a logical value (true or false).
Summary of the Primitive Types
A data type is defined by a set of values called the domain and a
set of operations. The following table shows the data domains
and common operations for all eight of Java’s primitive types:
Type
short
int
long
float
double
char
boolean
8-bit integers in the range –128 to 127
16-bit integers in the range –32768 to 32767
32-bit integers in the range
–2146483648 to 2146483647
64-bit integers in the range
–9223372036754775808 to 9223372036754775807
32-bit floating-point numbers in the range
± 1.4 x 10-45 to ± 3.4028235 x 10-38
64-bit floating-point numbers in the range
± 4.39 x 10-322 to ± 1.7976931348623157 x 10308
16-bit characters encoded using Unicode
the values true and false
The arithmetic operators:
+
-
*
/
%
add
subtract
remainder
divide
multiply
= =
<
!=
<=
>=
equal to
less than
greater or equal
less or equal
not equal
>greater than
The arithmetic operators except %
The relational operators:
The relational operators
The relational operators
The logical operators:
&& add || or !not
Domain (literals) Common operations
byte
Literals and Variables
• The simplest terms that appear in expressions are literals and
variables. The value of a literal 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.
• The format of a constant depends on its type:
– Integral constants consist of a string of digits, optionally preceded by a
minus sign, as in 0, 42, -1, or 1000000.
– Floating-point constants include a decimal point, as in 3.14159265
or 10.0. Floating-point constants can also be expressed in scientific
notation by adding the letter E and an exponent after the digits of the
number, so that 5.646E-8 represents the number 5.646 x 10-8.
– The two constants of type boolean are true and false.
– Character and string constants are discussed in detail in Chapter 8.
For the moment, all you need to know is that a string constant consists
of a sequence of characters enclosed in double quotation marks, such
as "hello, world".
• A variable in Java is most easily envisioned as a box capable
of storing a value.
• Each variable has the following attributes:
–A name, which enables you to differentiate one variable from another.
–A type, which specifies what type of value the variable can contain.
–A value, which represents the current contents of the variable.
total
(contains an int)
42
• The name and type of a variable are fixed. The value changes
whenever you assign a new value to the variable using =
Literals and Variables
• The format of a literal depends on its type:
– Integer literals consist of a st ring of d igits, optionally preceded by a
minus sign, as in 0, 42, -1, or 1000000.
– Floating-point literals include a decimal point, as in 3.14159265 or
10.0. Floating-point literals can also be expressed in scientific
notation by adding the letter E and an exponent after the digits of the
number, so that 5.646E-8 represents the number 5.646 x 10-8.
– The two literals of type boolean are true and false.
– Character and string literals are discussed in detail in Chapter 8. For
the moment, all you need to know is that a string literal consists of a
sequence of characters enclosed in quotation marks, such as "hello,
world” and a char literal is enclosed in single quotes ‘A’.
pf3
pf4
pf5

Partial preview of the text

Download Java Expressions: Primitive Data Types and Operators - Prof. Jennifer E. Walter and more Study notes Computer Science in PDF only on Docsity!

Chapter 3—Expressions The Art and Science of An Introduction

ERIC S. ROBERTS^ Java^ to Computer Science

Expressions

C H A P T E R 3 “ (What“Twice what?’s twice eleven?” said Pooh to” I said to Pooh. Me.) “ “I think that itJust what I think myself, ought to be” twenty-two. said Pooh.” —A. A. Milne, Now We Are Six, 1927

CMPU-

Computer Science I:

Problem-Solving and Abstraction

Fall 2008

Jennifer Walter

(adapted from slides by Eric Roberts)

Expressions in Java

  • The heart of the Add2Integers program from Chapter 2 is the line
  • The n1 + n2 that appears to the right of the equal sign is an example of an expression , which specifies the operations involved in the computation.
  • An expression in Java consists of terms joined together by operators.
  • Each term must be one of the following:
    • A literal constant (such as 3.14159265 or "hello, world" )
    • A variable name (such as n1 , n2 , or total )
    • A method call that returns a value (such as readInt )
    • An expression enclosed in parentheses int total = n1 + n2; that performs the actual addition.

Primitive Data Types

  • Although complex data values are represented using objects, Java defines a set of primitive types to represent simple data.
  • Of the eight primitive types available in Java, the programs in our text use only the following four: int (^) This type is used to represent integers, which are whole numbers such as 17 or – 53. 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. char (^) This type represents a single character and is described in Chapter 8. boolean This type represents a logical value ( true or false ).

Summary of the Primitive Types

A data type is defined by a set of values called the domain and a set of operations. The following table shows the data domains and common operations for all eight of Java’s primitive types: Type short int long float double char boolean 8-bit integers in the range – 128 to 127 16-bit integers in the range – 32768 to 32767 32-bit integers in the range – 2146483648 to 2146483647 64-bit integers in the range

  • 9223372036754775808 to 9223372036754775807 32-bit floating-point numbers in the range ± 1.4 x 10 -45^ to ± 3.4028235 x 10 - 64-bit floating-point numbers in the range ± 4.39 x 10 -322^ to ± 1.7976931348623157 x 10308 16-bit characters encoded using Unicode the values true and false The arithmetic operators: + - *** /** % add subtract remainder divide^ multiply = = < != <= >= equal to less than greater or equal less or equal not equal > greater than The arithmetic operators except % The relational operators: The relational operators The relational operators The logical operators: && add || or! not Domain (literals) Common operations byte

Literals and Variables

  • The simplest terms that appear in expressions are literals and variables. The value of a literal 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.
  • The format of a constant depends on its type:
    • Integral constants consist of a string of digits, optionally preceded by a minus sign, as in 0 , 42 , -1 , or 1000000.
    • Floating-point constants include a decimal point, as in 3. or 10.0. Floating-point constants can also be expressed in scientific notation by adding the letter E and an exponent after the digits of the number, so that 5.646E-8 represents the number 5.646 x 10 -^8.
    • The two constants of type boolean are true and false.
    • Character and string constants are discussed in detail in Chapter 8. For the moment, all you need to know is that a string constant consists of a sequence of characters enclosed in double quotation marks, such as "hello, world".
  • A variable in Java is most easily envisioned as a box capable of storing a value.
  • Each variable has the following attributes:
    • A name , which enables you to differentiate one variable from another.
    • A type , which specifies what type of value the variable can contain.
    • A value , which represents the current contents of the variable. total 42 (contains an int )
  • The name and type of a variable are fixed. The value changes whenever you assign a new value to the variable using =

Literals and Variables

  • The format of a literal depends on its type:
    • Integer literals consist of a string of digits, optionally preceded by a minus sign, as in 0 , 42 , -1 , or 1000000.
    • Floating-point literals include a decimal point, as in 3.14159265 or 10.0. Floating-point literals can also be expressed in scientific notation by adding the letter E and an exponent after the digits of the number, so that 5.646E-8 represents the number 5.646 x 10 -^8.
    • The two literals of type boolean are true and false.
    • Character and string literals are discussed in detail in Chapter 8. For the moment, all you need to know is that a string literal consists of a sequence of characters enclosed in quotation marks, such as "hello, world” and a char literal is enclosed in single quotes ‘A’.

Java Variable Identifiers

  • Names you make up for variables are called identifiers.
  • Identifiers in Java conform to the following rules:
    • A variable name must begin with a lower-case letter or the underscore character. abstract boolean break byte case catch char class const continue default do double else extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while
  • Identifiers should make their purpose obvious to the reader.
  • Identifiers should adhere to standard conventions.
  • The remaining characters must be letters, digits, or underscores.
  • The name must not be one of Java’s reserved words :

Variable Declarations

  • 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. type name = value ;
  • The most common form of a variable declaration is where type is the name of a Java primitive type or class, name is an identifier that indicates the name of the variable, and value is an expression specifying the initial value.
  • Until we get to Ch. 6, all variable declarations will appear as statements inside the curly braces of a method definition. These are called local variables and are accessible only inside that method.

Variable Declaration and Initialization

  • Declaration of a variable is the int total part of the statement below.
  • Initialization of a primitive variable is the total = 42 part.
  • Either of these parts can be a statement in itself, although the declaration must precede the initialization.
  • Each name for a variable can be declared only once, but the value stored in the name can be changed any number of times, within a given set of curly braces. int total = 42; int total; total = 42;

Variable Declaration and Instantiation

Declaration is also necessary when a variable is of object type The declaration of GRect rect1 is shown below Instantiation of an object variable requires using the new keyword and calling the class constructor. Objects can also be declared before they are instantiated. GRect rect1 = new GRect(100,200,50,50); GRect rect1; rect1= new GRect(100,200,50,50);

Operators and Operands

  • As in most languages, Java programs specify numeric computation in the form of arithmetic expressions that closely resemble expressions in mathematics.
  • Operators in Java usually appear between two subexpressions, which are called its operands. Operators that take two operands are called binary operators.
  • The most common operators in Java are the ones that specify arithmetic computation: + Addition - Subtraction ***** Multiplication / Division % (^) Remainder
  • The - operator can also appear as a unary operator , as in the expression -x , which denotes the negative of x.

Division and Type Casts

  • Whenever you apply a binary operator to numeric values in Java, the result will be of type int if both operands are of type int , but will be a double if either operand is a double.
  • This rule has important consequences in the case of division. For example, the expression 14 / 5 seems as if it should have the value 2.8, but because both operands are of type int , Java computes an integer result by throwing away the fractional part. The result is therefore 2.
  • If you want to obtain the mathematically correct result, you need to convert at least one operand to a double , as in (double) 14 / 5 The conversion is accomplished by means of a type cast , which consists of a type name in parentheses.

Assignment Statements

variable = expression ;

  • You can change the value of a variable in your program by using an assignment statement , which has the general form:
  • The effect of an assignment statement is to compute (I.e. evaluate) the value of the expression on the right side of the equal sign and assign that value to the variable that appears on the left. Thus, the assignment statement total = total + value; adds together the current values of the variables total and value and then stores that sum back in the variable total.
  • When you assign a new value to a variable, the old value of that variable is lost.

Shorthand Assignments

  • Statements such as total = total + value; are so common that Java allows the following shorthand form: total += value; variable op = expression ;
  • The general form of a shorthand assignment is where op is any of Java’s binary operators. The effect of this statement is the same as variable = variable op ( expression ); For example, the following statement multiplies salary by 2. *salary = 2;

Increment and Decrement Operators

  • Another important shorthand form that appears frequently in Java programs is the increment operator , which is most commonly written immediately after a variable, like this: x++; The effect of this statement is to add one to the value of x , which means that this statement is equivalent to x += 1; or in an even longer form x = x + 1;
  • The -- operator (which is called the decrement operator ) is similar but subtracts one instead of adding one.

Boolean Expressions

George Boole (1791-1871) In many ways, the most important primitive type in Java is boolean , even though it is by far the simplest. The only values in the boolean domain are true and false , but these are exactly the values you need if you want your program to make decisions. The name boolean comes from the English mathematician George Boole who in 1854 wrote a book entitled An Investigation into the Laws of Thought, on Which are Founded the Mathematical Theories of Logic and Probabilities. That book introduced a system of logic that has come to be known as Boolean algebra , which is the foundation for the boolean data type.

Boolean Operators

  • The operators used with the boolean data type fall into two categories: relational operators and logical operators.
  • There are six relational operators that compare values of other types and produce a boolean result: = = (^) Equals < (^) Less than != (^) Not equals <= (^) Less than or equal to > Greater than >= Greater than or equal to For example, the expression n <= 10 has the value true if n is less than or equal to 10 and the value false otherwise. p || q means either p or q (or both)
  • There are also three logical operators: && Logical AND || (^) Logical OR ! Logical NOT p && q means both p and q !p means the opposite of p

Notes on the Boolean Operators

  • Remember that Java uses = to denote assignment. To test whether two values are equal, you must use the = = operator.
  • The || operator means either or both, which is not always clear in the English interpretation of or.
  • It is not legal in Java to use more than one relational operator in a single comparison as is often done in mathematics. To express the idea embodied in the mathematical expression 0! x! 9 0 <= x && x <= 9 you need to make both comparisons explicit, as in
  • Be careful when you combine the! operator with && and || because the interpretation often differs from informal English.

Short-Circuit Evaluation

  • Java evaluates the && and || operators using a strategy called short-circuit mode in which it evaluates the right operand only if it needs to do so.
  • One of the advantages of short-circuit evaluation is that you can use && and || to prevent execution errors. If n were 0 in the earlier example, evaluating x % n would cause a “division by zero” error.
  • For example, if n is 0, the right hand operand of && in n != 0 && x % n == 0 is not evaluated at all because n != 0 is false. Because the expression false && anything is always false , the rest of the expression no longer matters.

Designing for Readability

  • While it is clearly necessary for you to write programs that the compiler can understand, good programmers are equally concerned with writing code that people can understand.
  • The importance of human readability arises from the fact that programs must be maintained over their life cycle. Typically, as much as 90 percent of the programming effort comes after the initial release of a system.
  • There are several useful techniques that you can adopt to increase readability: - Use names that clearly express the purpose of variables and methods - Use proper indentation to make the structure of your programs clear - Use named constants to enhance both readability and maintainability

Review

  1. Name the 4 primitive data types we will use in this class.
  2. Declare a whole number called numCars.
  3. Initialize numCars value to 4.
  4. Declare a boolean called applianceOn and set it equal to false.
  5. Declare and instantiate a GOval called outerRing (a GOval constructor needs an x, y coordinate, a width and a height).
  6. Declare a GOval called innerRing.
  7. Instantiate outerRing to be a circle with radius 50, positioned at the origin.

The End