Data Types and Control Statements
I Career Craft
info@icareercraft.com
Data Types
Built-in Data Types
Java primitives (whole numbers) byte short int long Java primitives (real numbers) float double
Built-in Data Types
Java primitives (text) char (character, use single quotes: b) String * Java primitives (True/False) boolean
* String is not a primitive
Variable Declarations
Simple form <datatype> Example int total; Optional initialization at declaration <data type> <identifier> = <init value>; Example int total = 0;
<identifier>;
Examples
int counter; int numStudents = 583; float gpa; double batAvg = .406; char gender; char gender = f; boolean isSafe; boolean isEmpty = true; String personName; String streetName = North Avenue;
Primitive Type Facts
Type boolean Size Min 1bit false* Max true* Default false
char byte
short int long float double void
2 1
2 4 8 4 8
'\u0000' (null) -128
-32,768
-2,147,483,648
-9,223,372,036,854,775,808
127
32,767
2,147,483,647
9,223,372,036,854,775,807
(byte) 0
(short) 0 0 0L 0.0F 0.0D
Approx Approx
3.4E+38 with 7 significant digits 1.7E+308 with 15 significant digits
* Not truly min and max.
Note: Size is in Bytes
Conditionals & Iteration
Decision Statements
if statement omitting else branch: if (condition) statement1;
if statement omitting else branch: if (condition) { statements; } // if
Decision Statements
if statement - single statement bodies: if (condition) statement1; else statement2; if statement - multiple statement blocks: if (condition) { statements; } else { statements; } // if
Multiple Selections via switch
1. Use if construct for single selection. 2. Use if/else construct for double selection. 3. Use switch construct for multiple selection. Notes about switch:
Useful when making a selection among multiple values of the same variable.
Not useful when selecting among values of different variables.
Switch syntax
switch (<variable>) { case <value>: // whatever code you want break; // usually need this case <value>: // whatever code you want break; // usually need this default: // whatever code you want break; // optional }
Multiple Selections via switch
Note the "optional" default case at the end of the switch statement. It is technically optional only in terms of syntax.
switch (number) { case 1: System.out.println ("One"); break; case 2: System.out.println ("Two"); break; case 3: System.out.println ("Three"); break; default: System.out.println("Not 1, 2, or 3"); break; // Needed??? } // switch
This might work without the default case, but would be poor technique
For safety and good programming practice, always include a 'default' case.
How many days?
if (month == 4 || month == 6 || month == 9 || month == 11) numdays = 30; else if (month = 2) { numdays = 28; if (leap) numdays = 29; } else numdays = 31;
Switch
switch (month) { case 4: case 6: case 9: case 11: numdays = 30; break; case 2: numdays = 28; if(leap) numdays = 29; break; default: /* Good idea? */ numdays = 31; }
Java Iteration Constructs: "While Loops"
Java example:
<get first value> while (condition) { <process value> <get next value> }
Note: Check is made before entering loop thus it is possible that loop may not execute
Java Iteration Constructs: "Do While Loops"
Java example: do { statement 1; ... statement N; } while (condition);
Test Last Loop: Body of loop is guaranteed to be executed at least once. Useful when termination condition is developed inside loop.
Java Iteration Constructs: For Loop
Java syntax: for (<initialization>; <continue if>;<increment>)
Java example: int count; for (count = 1; count <= 50; count ++) { <loop-body> }
Secret!
A for Loop can always be converted to a while loop i = 0; while (i < 10) { System.out.println(i); i++; } for(i = 0; i < 10; i++) { System.out.println(i); }
This will help you understand the sequence of operations of a for loop
Operators
Operators based on the number of operators:
Unary Operators
Binary Operators
Ternary Operators
Arithmetic Operators
Sign Unary Operators + Increment and Decrement Operators ++ - Basic Arithmetic Operators + * / %
Relational Operators
Greater than (>) Less than (<) Greater than or equal to (>=) Less than or equal to (<=) Equal to (==) Not equal to (!=)
Logical Operators
Bitwise Operators Short-circuit operators
Bitwise Logical Operators
AND (&) OR (|) XOR (^)
Bitwise Inversion (~)`
Short-Circuit Logical Operators
Short-circuit Logical AND (&&) Short-circuit Logical OR OR (||) Boolean Inversion-NOT (!)
Assignment Operators
= += -= *= /= %= &= |= ^=
Advanced Operators
Shortcut if-else statement (?:) Dot operator (.) Cast operator (<type>) new
instanceof
Equality
Equality of primitives (==) Equality of references (==) Equality of object (equals)
Arrays
A problem with simple variables
One variable holds one value
The value may change over time, but at any given time, a variable holds a single value
If you want to keep track of many values, you need many variables All of these variables need to have names What if you need to keep track of hundreds or thousands of values?
Multiple values
An array lets you associate one name with a fixed (but possibly large) number of values All values must have the same type
The values are distinguished by a numerical index between 0 and array size minus 1
0 1 2 3 4 5 6 7 8 9
myArray 12 43
83 14 -57 109 12
Indexing into arrays
To reference a single array element, use array-name [ index ] Indexed elements can be used just like simple variables You can access their values You can modify their values An array index is sometimes called a subscript 0 1 2 3 4 5 6 7 8 9
myArray 12 43 myArray[0]
83 14 -57 109 12 myArray[5]
myArray[9]
Using array elements
0 1 2 3 4 5 6 7 8 9
myArray 12 43
83 14 -57 109 12
Examples: x = myArray[1]; // sets x to 43 myArray[4] = 99; // replaces 14 with 99 m = 5; y = myArray[m]; // sets y to -57 z = myArray[myArray[9]];// sets z to 109
Array values
An array may hold any type of value
All values in an array must be the same type For example, you can have: An array of integers An array of Strings An array of Person An array of arrays of Strings An array of Object
Two ways to declare arrays
You can declare more than one variable in the same declaration: int a[ ], b, c[ ], d; // notice position of brackets a and c are int arrays b and d are just ints Another syntax: int [ ] a, b, c, d; // notice position of brackets a, b, c and d are int arrays When the brackets come before the first variable, they apply to all variables in the list
Different ways of Creating the array
int myarray [ ]= {1,2,3}; int myarray [ ]= new int[3]; myarray[0]=1; myarray[1]=2; myarray[2]=3; Only Values Only size of array
int myarray [ ]= new int[] {1,2,3};
No size, only values
How to retrieve the values
To retrieve the values from an array for (int i=0; i < myarray.length; i++) { System.out.println(Value is: + myarray[i]); } Here length indicates the size of an array
Arrays of objects
Suppose you declare and define an array of objects:
Person[ ] people = new Person[20];
There is nothing wrong with this array, but
it has 20 references to Persons in it all of these references are initially null you have not yet defined 20 Persons For example, people[12].name will give you a nullPointerException
Arrays of arrays
The elements of an array can be arrays Once again, there is a special syntax Declaration: int[ ][ ] table; (or int table[ ][ ];) Definition: table = new int[10][15]; Combined: int[ ][ ] table = new int[10][15]; The first index (10) is usually called the row index; the second index (15) is the column index An array like this is called a two-dimensional array
Different ways of creating array of arrays
int[ ][ ] table = { {1, 2}, {3, 6}, {7, 8} }; int[ ][ ] table = new int[3][2]; Int[ ][ ] table = new int[ ][ ] { {1, 2}, {3, 6}, {7, 8} };
0 1
1 3 2 7
2
6 8
For example, table[1][1] contains 6 table[2][1] contains 8, and table[1][2] is array out of bounds To retrieve the values: for (int i = 0; i < 3; i++) { for (int j = 0; j < 2; j++) { System.out.println ( table[i][j] ); } }
Size of these arrays
0
0 1
2 1 3 6 2 7 8
int[ ][ ] table = new int[3][2]; The length of this array is the number of rows: table.length is 3 Each row contains an array To get the number of columns, pick a row and ask for its length: table[0].length is 2 But remember, rows may not all be the same length