Você está na página 1de 16

8966470.

doc FBE – Computer Science Dept

Mekelle University Faculty of Business & Economics

Computer Science Department

Comp 262: Internet Programming with Java

Handout 3 – Java Language Basics

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:

public class Circle


{

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.

public class Circle


{
//data
private double radius;

//constructors
public Circle ()
{ radius = 1.0;}

public Circle (double r)


{ radius = r; }

//methods
public double calcArea()
{
return Math.PI * radius * radius;
}

public void draw()


{
… …
}

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.

Some Java variable declarations we have already seen include:


int x;
FirstJava myObject = new FirstJava ();

And, from the example above:


int sum = 0;

A variable must be given an explicit name and data type.


The name must be a legal identifier (an identifier is simply a name given to an item
used in a Java program). A legal identifier begins with a letter and can consist of
alpha-numeric characters (letters and digits) and can also include the underscore (_)
and dollar ($) characters. Identifiers are case-sensitive and cannot have spaces in
them.
A convention used in Java programming is that variable names begin with a lowercase
letter while class names begin with an uppercase letter. If a variable or class name has
more than one word in it, the words are joined together and the first letter of each
word after the first will begin with a capital letter. This convention makes code easier
to read and understand and is followed in the examples used in this handout.

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.

In Handout 2, we mentioned static fields or variables, which is another way of saying


'class variable'. Such variables have class scope – because they can be referenced
within the class and its subclasses without prefixing with the class name.
Instance variables are variables that belong to instances (objects) of a class. These
also have class scope, because they must be prefixed with the instance name when
used outside the class or its subclasses.
The difference between static, or class, variables and instance variables is that an
instance variable can take different values for each object while a class variable has
the same value for all objects of that class.

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

The scope of parameters to a method or constructor is the entire method or


constructor, but the parameters cannot be used outside the method or constructor.

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:

final int MAX_STUDENTS = 100;

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.

4.1 Primitive Data Types


A variable of primitive type contains a single value of the appropriate size and format
for its type: a number, a character, or a boolean value. For example, an integer value is
32 bits of data in a format known as two's complement, the value of a char is 16 bits
of data formatted as a Unicode character, and so on.

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.

Type Description Storage Size


Integer types byte Byte-length integer; -128 to 127 8 bits (1 byte)
short Short integer; -32768 to 32767 16 bits (2 bytes)
int Integer; -231 to (231 –1) 32 bits (4 bytes)
long Long integer; -263 to +(263-1) 64 bits (8 bytes)
Real float IEEE 7541 floating point; 32 bits
number/floating- +/- 1.4E-45 to +/- 3.4028235E+38
point types
double IEEE 754 floating point; 64 bits
+/- 4.9E-324 to +/-
1.7976931348623157E+308
Table 1 – Numeric data types in Java
The bigger storage size types take up more memory (i.e. short takes more memory
than byte). So, you should select a data type appropriate to the values that will be held
in a variable e.g. if the values will be in the range –30000 to +30000, use short rather
than int. All Java number values are signed – which means they can be positive or
negative. There is no 'unsigned' keyword as in C/C++.

The other, non-numeric, data types are boolean and character.

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.

Literal primitive values can be used directly in code e.g.


char myChar = 'A'; //to assign the character A to a char

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, \', \".

Generally speaking, a series of digits with no decimal point is typed as an integer. A


long integer can be specified by putting an 'L' or 'l' after the number. 'L' is
preferred as it cannot be confused with the digit '1'.
A series of digits with a decimal point is of type double (e.g. 34.543).
1
The real number types adhere to the IEEE 754-1985 standard – this specifies the format of the
numbers and the behaviour of the arithmetic of the numbers.

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;

// other primitive types


char aChar = 'S';
boolean aBoolean = true;

// display them all


System.out.println("The largest byte value is " +

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

System.out.println("The largest double value is " +

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

4.2 Reference Data Types


Arrays and classes are reference data types in Java.
While a variable that has a primitive data type holds exactly one value, a variable that
has a reference data type is a reference to the value or set of values represented by the
variable.
Classes
When a class is defined, it can then be used as a data type. The variable declaration
for a reference data type is the same as for a primitive data type. For example, if a
program has a class named Customer, a new variable, myCustomer1, to hold an object
of type Customer can be declared like this:

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 = new Customer();


The above line creates a new object from the Customer class; the constructor for the
Customer class in this case does not take any arguments.
This is the same as the following lines – where the object is created by a separate
assignment:

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

byte[] arrayOfBytes; //array of values of type byte


byte[][] arrayOfArrayOfBytes ; //an array of arrays of byte[]

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

However, this syntax can be confusing, so it should be avoided in Java.

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':

String[] responses = new String[2];


responses[0] = "Yes";
responses[1] = "No";
//to read the elements
System.out.println ("The answer should be " + responses[0] + "

or " + responses[1] + "!");


If the size of an array is n, then the highest index for it is (n-1) e.g. an array of size 5
holds 5 elements, with the last one being accessed at index [4].
If the code tries to read an element past the end of the array e.g. to read index [5] in an
array of size 5, the interpreter throws an ArrayIndexOutOfBoundsException2 at
runtime.

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.

int[] valuesArray; //assume this array is created and

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.

Assigning Values to Arrays

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:

char[] password = null; //sets the password array of characters

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.

int[] someNumbers = {1, 2, 3, 4}

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.

System.out.println (3+4); //prints out 7


System.out.println ("The value is: " + 4); //prints out 'The

value is: 4'


System.out.println ("The value is: " + 3 + 4); //prints out

'The value is: 34', because there is at least one string


System.out.println ("The value is: " + (3+4)); //prints out

'The value is 7' – because the parentheses indicate that the

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.

Data Type of Result Data Type of Operands

Page 10 of 16
8966470.doc FBE – Computer Science Dept

long Neither operand is a float or a double (integer arithmetic); at least one


operand is a long.

int Neither operand is a float or a double (integer arithmetic); neither operand is


a long.

double At least one operand is a double.

float At least one operand is a float; neither operand is a double.

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

These operators are useful as shortcuts for incrementing or decrementing number


values e.g. x++, x-- and are commonly used to increment/decrement the counter that
controls a loop e.g. a for loop that loops 10 times:
for (int i=0; i<=10; i++;)
{
……
}

5.2 Comparison and Conditional


The comparison operators in Java are much like those in other languages. These are
summarised in the table below. Comparison operators return a result of data type
boolean i.e. true or false.

Operator Usage Returns true if…


> op1 > op2 op1 is greater than op2
op1 is greater than or equal to
>= op1 >= op2
op2
< op1 < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal

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.

int x = 5; //assigns the value of 5 to the integer variable x

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;

Any of the arithmetic operators can be used in this way i.e.


+=, -=, *=, /=, %=.

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:

person instanceof student //returns true if the object person

belongs to the class Student


"a string" instanceof String //returns true because all strings

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.

Object Member Access (.)


The dot (.) operator is used to access the data and methods of an object. The data
fields and methods of an object are also known as members of the object.
For example:

Person aPerson = new Person();



String theName = new String();
theName = aPerson.name //evaluates to the value of the name

data field of the Person object


Method Invocation ( ( ) )

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:

Person aPerson = new Person();



aPerson.increaseSalary(100); //invokes the method

increaseSalary, passing 100 as the paramter)


Object Creation (new)
As already seen, new is used to create a new object or array. The new keyword is
followed by the class name and a list of arguments to be passed to the object
constructor. The arguments are placed inside brackets. For example, if the constructor
for the Person class takes the name and father's name as arguments:

Person aPerson = new Person("Firstname", "Fathersname");

6 Type Conversions and Casting


Java carries out implicit conversions between number types. For example, if a short
literal value is assigned to an int data type, Java automatically converts the value to
int:
int x = 32767; //32767 is a literal value of type short, but is

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

narrower type (even though 13 is an allowed value for byte)


There is, however, one exception to this rule: an integer literal (an int value) can be
assigned to a byte or a short variable, but only if the literal falls inside the range of the
byte/short variable. So this line would be allowed:
byte b = 13; //allowed because 13 is an integer literal

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.

Object o = " a string"; //a widening conversion


//later in the code, the value of o can be cast back to a

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

//use PI to compute the area of a circle


double radius;
radius = 6;
double circleArea = Math.PI * radius * radius;

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

Notes prepared by: FBE Computer Science Department.

Page 16 of 16

Você também pode gostar