Lecture : Data Types and Expressions in Java
In the previous lecture:
In this lecture:
Java Primitive Data Types
Signed Integer | Floating point | Other types | Size | |
boolean (true or false) | 1 bit | |||
byte | 1 byte | |||
short | char (unicode character) | 2 bytes | ||
int | float | 4 bytes | ||
long | double | 8 bytes |
Type Conversions between Primitive Types
Java's interpretter will allow widening conversions (e.g. from int to double) because no data is lost.
int myInteger = 1; |
Java's interpretter will only allow narrowing conversions (e.g. from double to float) if explicitly told to do so with a cast because in general, data may be lost.
Be sure that either you don't care about the lost precision or in fact you are certain that there is no data being lost (E.g. because the float was initially assigned a value that had no decimal component and was small enough to fit into an integer. Check your reference manual for the maximum and minimum sizes for each data type).
int myInteger = 1; |
Some Common Java Operators
Arithmetic | + |
- |
* |
/ |
% |
++ |
-- |
Relational | > |
>= |
< |
<= |
== |
!= |
|
Logical | && |
|| |
! |
| |
& |
||
Assignment | = |
+= |
-= |
*= |
/= |
%= |
Others | [ ] array access |
new object creation |
. object member access |
? : conditional (ternary) operator |
instanceof type comparison |
( args ) method invocation |
( type ) |
+ string concatenation |
Look up a Java reference manual to determine: (i) the precedence of these operators; (ii) the other operators Java supports.
Conditional statements
if (expression) {... } else if (expression) { ... } else { ... } |
if (x>5) { System.out.println("X is greater than 5"); } else if ((x==5) && (equivalenceTest==true)) { System.out.println("X is exactly 5"); } else { |
switch (integer expression) { |
switch (x) { |
Iteration statements
while (expression) {... } |
x=0; while (x<5) { System.out.println("x=" + x); x++; } |
do { ... } while (expression) |
x=0; do { System.out.println("x=" + x); x++; } while (x<5) |
for (initialise; test; update) { ... } |
for (x=0; x<5; x++) { System.out.println("x=" + x); } |
Look up in a Java reference manual the break and continue statements. You'll need them!
Methods
A method is a named sequence of Java statements that is conveniently bundled together for use and re-use. (Re-using code saves programming time but also... debugging time!)
Methods may return values that are the result of their operation (see the source code comment below on the return statement), or they may change the fields of an object.
Methods may accept parameters that allow them to vary their behaviour in constrained ways that can be selected from outside the method. (Remember the concept of encapsulation?)
Method Java source code | Method signature explanation |
int mySafeIntegerDivisionMethod (int numerator, int denominator) |
|
boolean sheLovesMe(String myName) { if (myName.equals("Mr. Handsome")) { return true; } return false; } |
|
The first line of a method is its signature :
modifiers return-type (parameter-list) [throws-exceptions ]
(For now, don't worry about modifiers or throws-exceptions. We'll cover these later.)
The return-type may be a built-in type (boolean, int, float etc.), an array or a class. If there is no return type for a function its return-type must be written as void.
The parameter list is a comma-separated, bracketed list of the form:
(type parameter-name, type parameter-name ...)
If there are no parameters for a method the parameter list must be written as empty braces:( ) not (void).
To use a method, Java code just needs to call it by name and pass it any parameters it requires. Methods that have return values may be used in assignment statements.
int myResult = 0; int myOtherResult = 0; |
Arrays
Arrays are ordered collections of values of a single type. Arrays are not primitive types, they are aggregates.
Arrays are reference types (like classes). That is, when you declare a variable of "array type", you are actually declaring a reference (i.e. a name) for an object that may exist in memory. This name is not the object itself, only a name for it. This concept is explained further in lecture 2b.
Syntax for array types | Equivalent Syntax |
int[] arrayOfInts; // an array of the int type, int[] is an array type int[][] arrayOfArrayOfInts; // an array of an array of int. int[][] is an array of int[] type |
int arrayOfInts[]; int arrayOfArrayOfInts[][]; |
Whilst the syntax above gives the type names for some array types (i.e. references or names for array objects in memory), to actually make an array object for the name to refer to, you need to use the keyword new.
To access the members of the array use the [square brackets] and the index of the cell in the array.
Java array indices range from ( 0 .. (array.length - 1) ) and must always be of integer type.
int [] arrayOfInts = new int[3]; // make an array of 3 integers and a reference to that array object called "arrayOfInts". // Each integer in the array object is given the default int value of 0. |
for (int i=0; i<arrayOfInts.length; i++) // iterate through all of the cells in the array object { System.out.println("Array cell number " + i + " contains the value " + arrayOfInts[i] + "."); } |
// Now in Java 5.0: the for/in loop will do the iteration through an array or collection for // you, assigning the value of each member of the array to a variable you name in the (braces) before the colon. // Check your reference manual for details. The loop is not suitable for everything! for (int value : arrayOfInts)
{
System.out.println(value);
} |
Multidimensional arrays.
// Make an array of 10 arrays of 10 doubles
double[] twoDimensionalArray = new double[10][10]; |
|
Left is an image of the layout for a two dimensional array (i.e. an array of arrays). Cells are accessed by two indices. For example... // assign a value to the cell labelled in red twoDimensionalArray[5][6] = 77.0; // iterate through all cells in the array for (int i=0; i<10; i++) { for (int j=0; j<10; j++) {twoDimensionalArray[i][j] = i*j; } } |
|
We could also make a two dimensional array like this. double [][] twoDimensionalArray = new double [10][ ]; for (int i=0; i<10; i++) { twoDimensionalArray[i] = new double[10]; } |
|
We can make a three dimensional array like this. double [][][] threeDimensionalArray = new double [10][10][ ]; for (int i=0; i<10; i++) { for (int j=0; j<10; j++) { threeDimensionalArray[i][j] = new double[10]; } } // ...or just like this! double [][][] threeDimensionalArray = new double [10][10][10]; |
Some other things about Java arrays.
int [] arrayOfMagicNumbers = null; // 'null' can be used if you don't want to actually create the array yet. arrayOfMagicNumbers = new int[7]; // You can then make the array later (e.g. when you know how large it needs to be) |
int [] arrayOf8Primes = { 1,2,3,5,7,11,13,17 }; // quick way to make an array "literal" if you know what values // it must hold at the start. Java calulates the array size for you. // You don't need to use the 'new' keyword. |
int [][] twoDimensionalArray = { { 1,2,3 }, {5,7,11} }; // quick way to make 2D array literals |
int [][] triangularArray = { { 1}, {1,2}, {1,2,3}, {1,2,3,4} }; // you don't need to have rectangular arrays in Java! Neat huh?! |