Download Java Basics: Data Types, Variables, and Constants and more Study notes Computer Science in PDF only on Docsity!
CS201 1/
Accelerated Introduction to CS
Using Java 5
© 2004 Illinois Institute of Technology
Chapter 2
Programming Building Blocks
— Java Basics
CS201 3/
Java Syntax
Java Syntax for Instructions
- Keywords
- Operators
- Punctuations
Java Syntax for Expressing Data
- Keywords
- Symbolic Names
- Data Types
CS201 4/
Java Basics
Java Application Structure
Data Types, Variables, and Constants
Expressions and Arithmetic Operators
CS201 5/
Java Application Structure
All programs consist of at least one class.
See Example 2.1 SkeletonApplication for
standard form of Java application
Java source code file must have the same
name as class with .java extension.
CS201 6/
Identifiers - Symbolic Names
Identifiers are used to name classes,
variables, and methods
Identifier Rules:
- Must start with a "Java letter"
- A - Z, a - z, _, $, and Unicode letters
- Can contain essentially any number of Java letters
and digits, but no spaces
- Case sensitive!!
- Number1 and number1 are different!
- Cannot be keywords or reserved words
CS201 7/
Program Building Blocks
The Statement
- Performs some action
- Terminates with a semicolon (;)
- Can span multiple lines
CS201 8/
Building Blocks - The Block
The Block
- 0, 1, or more statements
- Begins and ends with curly braces { }
- Can be used anywhere a statement is allowed.
CS201 9/
Building Blocks - White Space
Space, tab, newline are white space characters
At least one white space character is required
between a keyword and identifier
Any amount of white space characters are
permitted between identifiers, keywords,
operators, and literals
CS201 10/
Building Blocks - Comments
Comments explain the program to yourself
and others
Block comments
- Can span several lines
- Begin with /*
- End with */
- Compiler ignores all text between /* and */
Line comments
- Start with //
- Compiler ignores text from // to end of line
CS201 11/
Data Types, Variables, and Constants
We use Symbolic Names to refer to data
We must assign a data type for very identifier
(symbolic name)
Declaring Variables
Primitive Data Types
Initial Values and Literals
String Literals and Escape Sequences
Constants
CS201 12/
Data Types
For all data, assign a name (identifier) and a
data type
Data type tells compiler:
- How much memory to allocate
- Format in which to store data
- Types of operations you will perform on data
Compiler monitors use of data
- Java is a "strongly typed" language
Java "primitive data types"
byte, short, int, long, float, double, char, boolean
CS201 19/
boolean Data Type
Two values only:
true false
Used for decision making or as "flag" variables
Example declarations:
boolean isEmpty; boolean passed, failed;
CS201 20/
Assigning Values to Variables
Assignment operator =
- Value on the right of the operator is assigned to the
variable on the left
- Value on the right can be a literal (text representing a
specific value), another variable, or an expression
(explained later)
Syntax:
dataType variableName = initialValue;
Or
dataType variable1 = initialValue1, variable2 = initialValue2, …;
CS201 21/
Literals
int, short, byte
Optional initial sign (+ or -) followed by digits 0 –
9 in any combination.
int testGrade = 100 ;
long
Optional initial sign (+ or -) followed by digits 0–
9 in any combination, terminated with an L or
l.
***Use the capital L because the lowercase l
can be confused with the number 1.
CS201 22/
Floating-Point Literals
float
Optional initial sign (+ or -) followed by a floating-
point number in fixed or scientific format,
terminated by an F or f.
double
Optional initial sign (+ or -) followed by a floating-
point number in fixed or scientific format.
CS201 23/
char and boolean Literals
char
- Any printable character enclosed in single quotes
- A decimal value from 0 – 65535
- '\m' , where \m is an escape sequence. For example,
'\n' represents a newline, and ' \t' represents a tab
character.
boolean
true or false
See Example 2.2 Variables.java
CS201 24/
Assigning the Values of Other Variables
Syntax:
dataType variable2 = variable1;
Rules:
1. variable1 needs to be defined before this statement
appears in the source code
2. variable1 and variable2 need to be compatible data
types; in other words, the precision of variable1 must
be lower than or equal to that of variable.
CS201 25/
Compatible Data Types
Any type in right column can be assigned to type in left column:
Data Type Compatible Data Types byte byte short byte, short int byte, short, int, char long byte, short, int, long, char float float, byte, short, int, long, char double float, double, byte, short, int, long, char boolean boolean char char
CS201 26/
Sample Assignments
This is a valid assignment:
float salesTax = .05f; double taxRate = salesTax;
This is invalid because the float data type is
lower in precision than the double data type:
double taxRate = .05; float salesTax = taxRate;
CS201 27/
String Literals
String is actually a class, not a basic data type;
String variables are objects
String literal: text contained within double quotes
Example of String literals:
"Hello" "Hello world" "The value of x is "
CS201 28/
String Concatenation Operator (+)
Combines String literals with other data types
for printing
Example:
String hello = "Hello"; String there = "there"; String greeting = hello + ' ' + there; System.out.println( greeting );
Output is:
Hello there
CS201 29/
Common Error Trap
String literals must start and end on the same
line. This statement:
System.out.println( "Never pass a water fountain without taking a drink" );
generates these compiler errors:
unclosed string literal ')' expected
Break long Strings into shorter Strings and use the
concatenation operator:
**System.out.println( "Never pass a water fountain"
- " without taking a drink" );**
CS201 30/
Escape Sequences
To include a special character in a String ,
use an escape sequence
Character Escape Sequence Newline \n Tab \t Double quotes " Single quote ' Backslash \ Backspace \b Carriage return \r Form feed \f
See Example 2.3 Literals.java
CS201 37/
Examples: Assignment
int numPlayers = 10; // numPlayers holds 10 numPlayers = 8; // numPlayers now holds 8
int legalAge = 18; int voterAge = legalAge;
The next statement is illegal
int height = weight * 2; // weight is not defined int weight = 20;
and generates the following compiler error:
illegal forward reference
CS201 38/
Arithmetic Operators
modulus (remainder
after division)
/ division
* multiplication
+ addition
Operator Operation
CS201 39/
Example
See Example 2.7 SimpleOperators.java
Page 65
CS201 40/
Operator Precedence
= right - left assignment
addition,
subtraction
+ - left - right
multiplication,
division, modulus
* / % left - right
parenthesis for
explicit grouping
( ) left - right
Order of Operation
evaluation
Operator
CS201 41/
Example
You have 2 quarters, 3 dimes, and 2 nickels.
How many pennies are these coins worth?
int pennies = 2 * 25 + 3 * 10 + 2 * 5; = 50 + 30 + 10 = 90
CS201 42/
Another Example
Translate x into Java:
2y
// incorrect! double result = x / 2 * y;
=> x * y
// correct double result = x / ( 2 * y );
CS201 43/
Integer Division & Modulus
When dividing two integers:
- the quotient is an integer
- the remainder is truncated (discarded)
To get the remainder, use the modulus operator
with the same operands
See Example 2.8 DivisionAndModulus.java
CS201 44/
Division by Zero
Integer division by 0:
Example: int result = 4 / 0;
No compiler error, but at run time, JVM
generates ArithmeticException and program
stops executing
Floating-point division by 0:
- If dividend is not 0, the result is Infinity
- If dividend and divisor are both 0, the result is
NaN (not a number)
See Example 2.9 DivisionByZero.java
CS201 45/
Mixed-Type Arithmetic
When performing calculations with operands of
different data types:
- Lower-precision operands are promoted to higher-
precision data types, then the operation is performed
- Promotion is effective only for expression evaluation;
not a permanent change
- Called "implicit type casting"
Bottom line: any expression involving a floating-
point operand will have a floating-point result.
CS201 46/
Rules of Promotion
Applies the first of these rules that fits:
- If either operand is a double , the other operand is converted to a double.
- If either operand is a float , the other operand is converted to a float.
- If either operand is a long , the other operand is converted to a long.
- If either operand is an int , the other operand is promoted to an int
- If neither operand is a double , float, long, or an int , both operands are promoted to int.
CS201 47/
Explicit Type Casting
Syntax:
(dataType)( expression )
Note: parentheses around expression are optional
if expression consists of 1 variable
Useful for calculating averages
See Example 2.10, MixedDataTypes.java
CS201 48/
Shortcut Operators
++ increment by 1 -- decrement by 1
Example:
count++; // count = count + 1; count--; // count = count - 1;
Postfix version ( var++, var-- ): use value of var
in expression, then increment or decrement.
Prefix version (++var, --var ): increment or
decrement var , then use value in expression
See Example 2.11 ShortcutOperators