Escolar Documentos
Profissional Documentos
Cultura Documentos
Reference:
You may find it useful to look at the Java tutorial, taken from the Sun Java website, on
the intranet – browse to Computers, Course Materials and look under the heading for
this course.
1 Overview
This handout covers variables, data types and operators in Java.
2 Structure of a Class
As we have already seen, all Java code is written inside classes. The structure of a
class is as shown below.
The class definition is the first part of the code that appears. This consists of the
access modifier for the class (public or private), the class keyword and the name of
the class. By convention, class names begin with an upper case letter, and any new
words in the name begin with an upper case letter. For example, to define a Circle
class:
Inside the class, the code can be divided into fields, constructors and methods.
The fields are the data members of the class. The data members can be class variables
or instance variables.
The constructors are special methods that are called when an object is instantiated
from the class. There can be more than one constructor for a class – as long as each
constructor has a different parameter list. For example, in a Circle class, the radius for
a new object could be passed to the constructor, or if no radius is passed, a default
value could be assigned for the radius. In fact, this also applies to methods. This
feature of Java is called method overloading and is something that is not possible in
C++.
The methods implement the behaviour of the objects belonging to the class.
Generally, methods return information about the state of an object or they change the
state of an object. These are sometimes called accessor and mutator methods.
The order of these parts of a class is generally not important, but placing the fields
and then the constructors at the beginning does make the class readable and easy to
Page 1 of 16
8966470.doc FBE – Computer Science Dept
get around for programmers. Of course, comment blocks should also be used to
document the code.
//constructors
public Circle ()
{ radius = 1.0;}
//methods
public double calcArea()
{
return Math.PI * radius * radius;
}
3 Variables
3.1 Declaration
Remember that a variable is like a storage location to store a data value and that a
variable can take different values at different times during the execution of a program.
Page 2 of 16
8966470.doc FBE – Computer Science Dept
A variable declaration is used to give a variable a name and a data type – the format
is to put the type followed by the name i.e.
type name
A variable must be initialised before it is used (the compiler will not allow an
uninitialised variable to be used). Initialisation simply means assigning some initial
value to a variable e.g.
int i ;
i = 0;
to initalise an integer variable to the value 0.
However, declaration and initialisation are often combined into one statement e.g.
int i = 0;
Some data types have default values that are used for initialisation if a variable is not
explicitly initialised in code. For example, the integer data type has a default value of
0.
3.2 Scope
A variable also has scope. Scope refers to the parts of the code in which the variable
name can be used without prefixing it with the class or object name. The scope is
determined by where in the class definition a variable is declared.
Generally, Java variables have either class scope or local scope.
Class and instance variables are declared at the class level – not within methods. But
they can be used within methods in the class, without prefixing with the class or
instance name.
Variables that are declared within a method or within a block of code have local or
lexical scope, that is, they can be used only within the enclosing block of statements
or method. For example, in the following block of code, the variable i is out of scope
in the line that begins 'System.out.println' because it was declared within the block of
statements following the if statement, so its scope is that block. Thus the last line will
not compile:
if (...) {
int i = 17;
...
}
System.out.println("The value of i = " + i);
// error
Page 3 of 16
8966470.doc FBE – Computer Science Dept
Local variables do not have the public or private modifiers in front of them. The
lifetime of a local variable is only the time of the method execution – they are created
when a method is called and destroyed when the method finishes.
To summarise:
• Class variables are used to store data that is common to all objects of the class.
• Instance variables are used to store data that persists through the lifetime of an
object.
• Local variables are often used as temporary storage locations while a method
or constructor completes its task.
3.3 Constants
In Java, a variable declaration can begin with the final keyword. This means that once
an initial value is specified for the variable, that value is never allowed to change.
This is the equivalent of a constant in C++ or other languages.
For example, to declare a constant for the value of the maximum number of students
allowed on a course:
The variable can be initialised after the declaration – but if the declaration includes
the final modifier, the initial value is the last value that can be assigned.
final int MAX_STUDENTS;
MAX_STUDENTS = 100;
Note that the convention in Java programming is to use all uppercase letters for
constant names, so that they stand out in the code. Underscores are used to separate
the words if there is more than one word in the constant's name.
4 Data Types
Every variable must have a data type – the data type determines the values that a
variable can contain and also what operations can be performed on it.
Java has two types of data type – primitive and reference.
A variable of reference type has as its value an address, or a pointer to the values or
set of values that the variable represents. Classes, interfaces and arrays are reference
types. We will talk more about these later in the course.
The primitive types can be divided into numeric and non-numeric types.
Page 4 of 16
8966470.doc FBE – Computer Science Dept
Numeric types can further be divided into integer and real number (or floating-point)
types. Integer types hold whole numbers, positive and negative. Real number types
can hold decimal values e.g. 1.234, -6.754.
The boolean type has only two possible values, representing the two Boolean states –
true and false. Java reserves the words true and false for these values.
Comparison operators (e.g. >, <, = =) all return boolean type values.
Unlike C/C++, boolean values in Java cannot be converted to or from other data types
e.g. 0 and 1 cannot be converted to true and false.
The character type, called char in Java, represents any Unicode character. The char
type takes up 16 bits (2 bytes) in memory and holds only a single character.
Java provides some built-in classes, such as String and StringBuffer, for working with
strings of char values.
variable
int myInt = 5; // to assign the value 5 to an integer variable
The declarations above also show how a value can be assigned to a variable as part of
the variable declaration e.g. the myChar variable is initially given the value of 'A'.
For the char type, there are escape sequences for special characters e.g. \b for a
backspace, \n for a newline, \t for a tab, \\ for a backslash, \', \".
Page 5 of 16
8966470.doc FBE – Computer Science Dept
But you can specify that the number is a float by putting an 'f' or 'F' after the
number (e.g. 34.543f).
A literal character value is any single Unicode character between single quote marks.
The two boolean literals are simply true and false.
Java has wrapper classes for each of the integer types – these are Byte, Short, Integer
and Long. These classes define MIN_VALUE and MAX_VALUE constants that
describe the range of each type. They also have useful static methods that can be used
to convert strings to integer values e.g. Integer.parseInt() to convert a string to an
integer. The exercise below demos these wrapper classes.
The primitive types have default values – so if a variable is not explicitly initialised, it
is automatically initialised to its corresponding default value. These are 0 for int, 0.0
for floating-point values, and an empty string for char.
Exercise: try copying or typing the code below into a new .java file named
MaxVariablesDemo.java. Compile and run it – it will list the min and max values for
the number types and demonstrates the use of the primitive data types.
/**
* Taken from the Sun Java Tutorial - demo to show the primitive
data types.
* Uses the wrapper classes to get the min and max values for
each
*/ number type.
public class MaxVariablesDemo {
public static void main(String args[]) {
// integers
byte largestByte = Byte.MAX_VALUE;
short largestShort = Short.MAX_VALUE;
int largestInteger = Integer.MAX_VALUE;
long largestLong = Long.MAX_VALUE;
// real numbers
float largestFloat = Float.MAX_VALUE;
double largestDouble = Double.MAX_VALUE;
largestByte);
System.out.println("The largest short value is " +
largestShort);
System.out.println("The largest integer value is " +
largestInteger);
System.out.println("The largest long value is " +
largestLong);
System.out.println("The largest float value is " +
largestFloat);
Page 6 of 16
8966470.doc FBE – Computer Science Dept
largestDouble);
if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is
upper case.");
} else {
System.out.println("The character " + aChar + " is
lower case.");
}
System.out.println("The value of aBoolean is " +
aBoolean);
}
}
Figure 1 – exercise to demonstrate use of the primitive data types
Customer myCustomer1;
However, to assign a reference to the variable, the new keyword must be used – new
creates a new object from the specified class. The class name is followed by
parentheses in which any arguments required by the class constructor are passed e.g.
Customer myCustomer1;
MyCustomer1 = new Customer();
Arrays
An array is also a reference type, a structure that can hold multiple values – but all the
values must be of the same type. That type can be a primitive data type or an object
type, or it can be other arrays.
In Java, an array is actually an object – but one that has specialised syntax and
behaviour.
An array is declared by specifying the data type of the values it will hold, followed by
[] to indicate that it is an array. For example:
Page 7 of 16
8966470.doc FBE – Computer Science Dept
type
Customer[] arrayOfCustomers; //array of objects of the class
Customer
The C++ syntax for declaring a variable of array type is also supported by Java i.e.
Byte arrayOfBytes[]; //array of values of type byte
In the above examples, we can say that byte[] and Customer[] are types.
After an array has been declared, it must be created. Because an array is actually an
object in Java, the new keyword must be used to create the array (new is used to
create any object). The size of the array i.e. how many elements it can hold must be
specified. For example, to declare an array called 'arrayOfBytes' that will hold 1024
bytes and to create it:
byte[] arrayOfBytes = new byte[1024];
To declare an array of 50 strings:
String[] lines = new String[50];
When the array is created in this way, each of the values in the array is initialised to
the corresponding default value for the data type of the value (the default value for an
object type is null, meaning the object has an empty reference).
In Java, arrays have a 0-based index, that is, the first element is at index 0. The
elements are accessed by the array name followed by the index in square brackets.
For example, to declare an array named 'responses', with two elements whose values
are 'Yes' and 'No':
The size, or length, of an array can be accessed in code by reading the value of the
length property of the array object e.g.
int sizeOfResponsesArray = responses.length;
2
Throwing an exception is part of the runtime error handling of Java. We will look at how to properly
handle exceptions later in the course.
Page 8 of 16
8966470.doc FBE – Computer Science Dept
This is commonly used to loop through all the values in an array e.g.
initialised somewhere
int totalValue else the sum of the array elements
= 0; //store
for (int i = 0; i < valuesArray.length; i++)
totalValue += values[i];
The above example creates an array of values and then uses a for loop to iterate
through the values and add them up. As the index for the array is 0-based, the last
element is at the index [array.length-1].
The for syntax includes the initialisation, test and update steps for the loop – initialise
the counter to 0, loop until i reaches the size of the array, increment i by 1 for each
iteration.
The null literal can be used to indicate that an object that is of a reference data type
does not yet exist i.e. to initialise an object to be empty or null. For example:
to be null
Literal values can also be used to specify the values of an array, as in the String array
example given above:
String[] responses = new String[2];
responses[0] = "Yes";
responses[1] = "No";
An array can also be initialised by the following syntax, where the array object is
created and the elements initialised in one statement. The element values are separated
by commas.
The new keyword is not used – but the object is implicitly created.
The length of this array is now 4 – again, this is implicit from the specified elements.
The statement above could also be written as:
int[] someNumbers = new int[4];
someNumbers[0] = 1;
someNumbers[1] = 2;
someNumbers[2] = 3;
someNumbers[3] = 4;
In fact, the Java compiler compiles the single statement into Java byte codes that are
equivalent to the above. The implication of this is that if your program needs to
include a large amount of data into an array, it may not be most efficient to include the
data literally in the array, as the examples above do. This is because the compiler has
to create a lot of Java byte codes to initialise the array, and then the interpreter has to
execute all that code.
Page 9 of 16
8966470.doc FBE – Computer Science Dept
It may be more efficient to store the data in an external file and read it into the
program at runtime.
5 Operators
This section covers arithmetic, comparison, conditional and assignment operators.
Java also has a group of operators called shift or bitwise operators – these operate on
the individual bits (1s and 0s) of integer values. We will not cover these at this point.
5.1 Arithmetic
Java supports the standard arithmetic operators for all integer and floating-point
numbers. These are:
+ (addition), - (subtraction), * (multiplication), / (division), % (modulo).
All of these are binary operators i.e. they take two operands and the operator appears
between the two operands (this is called infix notation), as follows:
Operand1 operator operand2
The subtraction operator can also be used as a unary operator – when it is placed in
front of a number e.g. –5. When used in this way, it effectively multiplies the single
operand by –1.
The addition operator can also be used to concatenate two strings. If either one of the
two operands is a string, then the other one is converted to a string and the strings are
concatenated. Try the following code in a main method to see the addition operator
operating on numbers and on strings.
The division operator divides the first operand by the second e.g.
12/4
evaluates to 3. If both operands are integers, the result is an integer and any remainder
is lost. If you want to do division and get the remainder, at least one of the operands
should be typed as a floating-point number – the result will then be a floating-point.
When an integer and a floating-point number are used as operands to any arithmetic
operator, the result is a floating-point number. This is because the integer is implicitly
converted to a floating-point value before the operation takes place.
The table below summarises the data types for the results of arithmetic operations,
based on what the data types of the operands are.
Page 10 of 16
8966470.doc FBE – Computer Science Dept
There are also shortcut arithmetic operators, to easily increment and decrement a
value by 1. These are + + and - -. Where the operator is placed relative to the operand
i.e. before or after it affects the behaviour of the operator.
When the operator is placed before the operand, it increments or decrements the
operand and the operation evaluates to the incremented value of the operand. This is
called a pre-increment operator.
When the operator is placed after the operand, it increments or decrements the
operand but the expression evaluates to the value of the operand before it was
incremented/decremented. This is called a post-increment operator.
Consider the code sample below:
int i,j;
i = 1;
j = ++i; //pre-increment - sets j to 2 and i to 2
i = 1;
j = i++; //post-increment sets j to 1 and i to 2
Page 11 of 16
8966470.doc FBE – Computer Science Dept
Java also has conditional (logical) operators. These can be used to combine multiple
comparison expressions into a single, more complex expression.
The operands for a conditional operator must be boolean and the result is also a
boolean.
Operator Name Usage
&& Conditional AND op1 & op2
Returns true if op1 and op2 are both true – only
evaluates op2 if op1 is true
|| Conditional OR op1 | | op2
returns true if op1 or op2 is true – only evaluates op2 if
op1 is false
! Boolean NOT !op
Returns true if op is false i.e. changes the boolean value
of the operand
& Boolean AND op1 & op2
Like && but always evaluates both operands
| Boolean OR op1 | op2
Like || but always evaluates both operands, even if the
first one is true
^ Boolean XOR op1 ^op2
Exclusive OR – returns true only if exactly one of the
operands is true. Returns false if both are true or both
are false
Note the difference between && and &, and between | | and |.
If the right-hand operand in a && or | | operation carries out some action, such as
reading in some input or updating a value, remember that if the operand is not
evaluated, the action will not be carried out.
For example, suppose there is an object named customer1 which has a method
increaseBalance() which returns a Boolean – true if the increase is successful and
false if it is not. Take a statement that checks for the value of a variable (beingInt)
being greater than a given value AND the increaseBalance() method being
successfully invoked. The statement can be written as follows, using a conditional
AND:
someInt int = 8
depositAmt int;
depositAmt = 100;
….
if (someInt >= 10 && customer1.increaseBalance(depositAmt) )
{
……
}
In this case, the value of someInt is 8, which is less than 10, so the expression
'someInt>=10' is false. This means that the second expression,
customer1.increaseBalance() will not be evaluated. So, the balance will not be
increased. This could be a problem, if it is necessary to ensure that the balance is
increased. In that case, a boolean AND operator (&) should be used – as it will
evaluate both expressions, even if the first one is false.
Page 12 of 16
8966470.doc FBE – Computer Science Dept
5.3 Assignment
The basic assignment operator is = e.g.
There are also several short-hand assignment operators. These are used to perform
some operation on an operand and to assign the result to a variable, all in one go.
For example:
int I;
i = 2;
i = i + 3;
//the following statement is the same as the above two
statements
i += 2;
5.4 Others
instanceof
The instanceof operator is a special operator that is used to check if a given object is
an instance of a particular class. The left operand is the object being tested and the
right operand is the class to check for. It returns true if the object is an instance of the
class and false if not. For example:
are instances
"a string" of the String
instanceof Objectclass
//returns true because Strings are
also
null instances
instanceofof the Object
String superclass
//returns false because null is never an
instance of anything
Other language constructs in Java that are sometimes considered as operators are the
following.
Page 13 of 16
8966470.doc FBE – Computer Science Dept
A method can be accessed using the dot operator, and it is invoked by using the ( )
operator after the method name. Any arguments or parameters to the method are
placed inside the brackets. For example:
converted to int
This is called a widening conversion because the value is being converted to a type
that has a wider range of legal values.
A narrowing conversion occurs when a value is converted to a type that is not wider
than it. Sometimes this type of conversion is not safe e.g. it is safe to convert the
integer value 13 to a byte, but not to convert 13000 to a byte, because the byte type
can only hold numbers between –128 and 127.
Because of this, the Java compiler produces a compile error when the code attempts a
narrowing conversion. This happens even if the actual value being converted would
fit into the narrower range.
For example:
int i = 13;
byte b = i; //not allowed by the compiler because byte is a
The error produced by the compiler for a narrowing conversion includes the message
'possible loss of precision'.
The above are examples of implicit conversion – Java carries out the conversion
automatically, if it is ok to do so. However, a conversion from one type to another can
be forced using a cast. This can be used when a narrowing conversion would occur,
and if the programmer knows that data will not be lost.
Page 14 of 16
8966470.doc FBE – Computer Science Dept
A cast is performed by putting the type to convert to in parentheses before the value to
be converted.
Taking the example above, there the narrowing conversion of the int value to a byte is
not allowed by the compiler, this can be forced using a cast as follows:
int i = 13;
byte b = (byte) i; //force the int value 13 to be converted to
a byte
A cast is often used to convert a floating-point value to an integer – when this occurs,
the fractional part of the floating-point value is truncated to leave an integer.
For example:
int i;
i = (int) 13.456; //forces the double literal to the int value
13
Casting can also be used with reference data types, but there are some restrictions.
As with primitive types, the Java interpreter automatically carries out widening
conversions. Narrowing conversions must be made explicit using a cast.
When converting reference data types, the following rules apply:
• An object can be converted to the type of its superclass, or any ancestor class
in its class hierarchy. This is a widening conversion.
• An object can be converted to the type of its own subclass. This is a narrowing
conversion, so it requires a cast.
• An object cannot be converted to an unrelated type i.e. to a class that the
object is not a subclass or superclass of.
All Java classes automatically inherit from the Object superclass (this gives them
special methods such as toString(), clone() and equals()).
For example, the String class is a subclass of Object. So a string value can be assigned
to a variable of type Object. If assigning the value to a String variable, a cast is
required.
String
String s = (String) o; //a narrowing conversion, so requires a
cast
7 Mathematical Functions
In Java, mathematical functions such as square root and trigonometric functions are
implemented as methods on the Math class (equivalent of the C <math.h> functions).
This class is part of the built-in java.lang package – because it is a built-in class, it
does not have to be imported to use it. The Math class also provides constants for the
mathematical values PI and E.
For example:
double x,y;
x = 9;
y= Math.sqrt(x); //computes the square root of x
Page 15 of 16
8966470.doc FBE – Computer Science Dept
Some useful Math methods and constants are listed in the table below.
Method Description
sin (x) Trigonometry Sin
cos (x) Trigonometry Cos
tan (x) Trigonometry Tan
asin (x) Trigonometry aSin
acos (x) Trigonometry aCos
atan (x) Trigonometry aTan
pow (x, y) Returns x to the power of y (xy)
exp (x) Returns e to the power of x (ex)
Log (x) Returns the natural logarithm of x
sqrt (x) Returns the square root of x
ceil (x) Returns the smallest whole number greater than or equal to x (rounding up)
floor (x) Returns the greatest whole number less than or equal to x (rounding down)
rint (x) Truncated value of x
abs (a) Returns the absolute value of a
max (a,b) Returns the maximum value of a and b
min (a,b) Returns the minimum value of a and b
Constant Value & Description
PI Double, 3.141592653589793 (access using Math.PI)
E Double, 2.718281828459045 (access using Math.E)
Note: x and y are parameters of type double; a and b can be of type int, long, float or
double
Page 16 of 16