24
Variables and Data Types An introduction to working with variables in Java In computer programming, a variable is a location of memory that is associated with a name (or identifier) and contains some information (or value). The term variable is used because the contents of the memory location typically can be changed. In Java, a variable holds a value that is either a primitive data type or a reference type. Java has eight primitive data types: byte, short, int, long – these types represent integers (whole numbers) float, double - these represent floating point numbers (numbers with fractional parts) char – this type represents characters (any keystroke on keyboard) boolean – this represents true/false and is used for logic In addition, Java provides special support for character strings. Strings are objects, not one of the primitive data types. It can be tempting to think of them as such, but there are some important differences. In this booklet (and indeed the course), we will mainly work with int (whole numbers), double (real numbers), boolean (true/false), char (single characters), and String (text strings) variables. Reference types include objects, arrays, classes, and interfaces. Whereas a primitive variable holds exactly one value, a reference variable holds a Claremont College 2016, based on Rosny College 2009 Page 1 of 24

Identifiers - Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Embed Size (px)

Citation preview

Page 1: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Variables and Data TypesAn introduction to working with variables in Java

In computer programming, a variable is a location of memory that is associated with a name (or identifier) and contains some information (or value). The term variable is used because the contents of the memory location typically can be changed.

In Java, a variable holds a value that is either a primitive data type or a reference type.

Java has eight primitive data types:

byte, short, int, long – these types represent integers (whole numbers) float, double - these represent floating point numbers (numbers with fractional parts) char – this type represents characters (any keystroke on keyboard) boolean – this represents true/false and is used for logic

In addition, Java provides special support for character strings. Strings are objects, not one of the primitive data types. It can be tempting to think of them as such, but there are some important differences.

In this booklet (and indeed the course), we will mainly work with int (whole numbers), double (real numbers), boolean (true/false), char (single characters), and String (text strings) variables.

Reference types include objects, arrays, classes, and interfaces. Whereas a primitive variable holds exactly one value, a reference variable holds a pointer (or reference) to a location in memory that many contain multiple values and/or methods.

Claremont College 2016, based on Rosny College 2009 Page 1 of 16

Page 2: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

IdentifiersIdentifiers are the names of variables, constants, classes, objects, labels or methods. Once an identifier is created, it represents the same object in any other place it is used in the same code block.

Rules for creating identifiers in Java:

Identifiers can contain letters, numbers, underscore (_), or the dollar sign ($) Identifiers may only begin with a letter (or an underscore or a dollar sign, but this isn’t

recommended) Identifiers are case-sensitive Identifiers cannot be keywords.

Conventions for creating variable names:

Objects, methods, and variables have the first letter as lower case, e.g. ball, move, score Classes have the first letter as upper case, e.g. Alien Identifiers made up of multiple words have the first letter of each word capitalised, e.g. isVisible,

payAmount, moveShip Use uppercase with underscores for named constants, e.g. PI, INTEREST_RATE Choose identifiers that are closely related to the values they hold.

Here is a list of legal variable names:

myVariablemyvariableMY_VARIABLEtally_3littlePigsHotJava2Final_Total$

These are not legal variable names:

8HelloWorld // cannot start with a digitProfit&loss // & is not legal charactersHot Java // blank space is not a legal character27845 // a literal number cannot be used as an identifierTime-out // Java would try to perform a subtraction operation here!

Claremont College 2016, based on Rosny College 2009 Page 2 of 16

Page 3: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

How to create a variable: Declare and initialise To create a variable, it must first be declared and initialised.

Declaration involves specifying the variable name and the type of information that will be held in it.

When a variable is declared it is given a starting value. This is called initialisation. It will either be a value specified at the time of declaration or a default value. See the previous table for a list of the defaults for each data type.

For example…

int total; // create an integer variable called totalint subTotal, grandTotal; // multiple variables of the same type can be declared // at the same timeint meaningOfLife = 42; // a variable can be assigned a value when declared

When you use a variable you are accessing the value stored in that location in memory. To place a value into a variable you use the assignment operator ( = ).

The syntax for an assignment statement is as follows,

<variable name> = <expression>;

where expression can be anything that gives a value of the same type as the variable.

total = 25; // a valuetotal = moreTotals; // another variable of the same typetotal = (34 + 25 * 12) // a more complex expression

Global and local variablesVariables can be considered global or local depending on where they are declared within a class.

A global variable is one that is declared immediately after the main class definition, and this means that all the methods of the class can use it.

A local variable is one that has been declared within a particular method is only available inside that method.

ConstantsSome variables do not change their value during a program and can be thought of as constants e.g. PI.

It makes for more readable code if you use these variable names instead of the value in the code. Also it allows for values. e.g. interest rate to be set in only one place in a program and for this to be easily altered if rates change.

In Java, the keyword final can used when declaring a variable to stop the value from accidentally being altered. For example:

final double PI = 3.14159;double r = 20;

areaOfCircle = PI * r * r;

There is a convention in Java for the names of constants to be in all capitals with underscores, e.g. PI, INTEREST_RATE.

Claremont College 2016, based on Rosny College 2009 Page 3 of 16

Page 4: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Primitive data typesEach Java data type is strictly defined in terms of the values it can store. In other languages such as C, variations in the manner in which numbers are stored on machines can lead to problems in porting code (e.g. one machine uses 16-bit integers, another uses 32-bit integers which gives variation in the maximum value that can be stored).

Here’s a summary the eight primitive data types in Java, with their size, range, and default values…

Type Size Range Default Valueboolean 1 bit True or false only falsechar 16-bit Unicode characters Alphanumerical characters

e.g. the characters on the keyboard0 (‘\u0000’)

byte 8-bit 2’s complement integer -128 to 127 0short 16-bit 2’s complement integer -32768 to 32767 0int 32-bit 2’s complement integer -2,147,483,648 to +2,147,483,647 0long 64-bit 2’s complement integer -9,223,372,036,854,775,808 to

+9,223,372,036,854,775,8070

float 32-bit single precision floating point number (using IEEE 754 standards)

+/ - about 1039 0

double 64-bit double precision floating point number (using IEEE 754 standards)

+/- about 10317 0

BooleanBoolean is simplest data type in Java. There are only two possible values: true and false. Other languages, such as C++ and Pascal, may use 0 to represent false and 1 to represent true.

Boolean variables are mostly used to see what state an object is in.

boolean myBooleanTest, finished;

myBooleanTest = 6 > 7; // would evaluate to false

if (finished == true) // could be used to test if a piece of code was completedg.drawString(“It’s finished”,20,20);

Note: When used in an if statement, it’s not necessary to compare the boolean variable to true or false, because it already is true or false!

For example, the previous example could be written more compactly as…

if (finished)g.drawString(“It’s finished”,20,20);

Characters (char)The char type is used to store a single character (i.e. letter, digit, punctuation, or a control character like backspace).

The available characters are those defined by the International Standards Organisation (ISO) Unicode character set (most other languages use the ASCII set which is a subset of Unicode). Unicode also includes characters from other languages/alphabets as well as English.

Each character has a corresponding literal representation (e.g. 'A' is represented by the binary code for 6510 which is 010000012).

We can assign character values directly using character literals like 'A'. Note that you must use single quotes, not double quotes. For example:

char myChar = ‘f’; // myChar has been assigned the value of the letter ‘f’

Claremont College 2016, based on Rosny College 2009 Page 4 of 16

Page 5: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

We can also read characters in from a textfield (let's call it input) that is displayed in an applet window. For example, we could use getText method to find out the value of the first character typed in the textfield (i.e. position 0)…

char ch;ch = input.getText().charAt(0);

The escape characterTo assign ‘ or “ or \ to a char variable, use the escape character (\) with the desired character. For example:

char1 = ‘\’’ would assign ‘ to char1

Unicode sequencesTo assign a Unicode sequence to a character, use ‘\uxxxx’, where xxxx is digits in hexadecimal and u stands for Unicode. For example:

char1 = ‘\u20AC’ // the character € (for Euro) is assigned to the variable char1

A list of Unicode sequences can be found at www.unicode.org

Integers (whole numbers – byte, short, int, long)In Java, there are four primitive data types for representing integer (whole number) values: byte, short, int, long.

In this course, we will typically use int when working with integers.

Problems can arise if an integer or real is created outside the available range of values. This can be a particular problem with byte and short. For example, with if some operation creates a number outside the range, no overflow or exception is created. Instead a 2’s complement value will result.

For example, for a byte…

127 + 1 => -128127 + 9 => -120127 + 127 => -2

Reals (floating point numbers – float, double)In computer programming, floating-point representations are used to represent real numbers, i.e. numbers that have a fractional part e.g. 23.85, 0.33333…, 178.5, 0.000001, etc.

Integers can also be represented as floating-point numbers, but are displayed with a “.0” in Java. For example, the number 42 would be displayed as “42.0”.

In Java, real numbers are represented using the primitive types float and double.

In this course, we will typically use double when working with reals.

Float and double have similar properties but differ in the range of values and the amount of memory needed to store them. The Java floating-point representations follow the IEEE 754 standards so will always give predictable and consistent results no matter what platform they are running on.

There are also four states that floating-point numbers can have (to conform to the standard):

Positive infinity Negative infinity Zero Not a number

Adding 1 to the maximum number of a floating-point number will give a positive infinity result.

With both float and double, small rounding errors can accumulate so that result may not be 100% accurate.

Claremont College 2016, based on Rosny College 2009 Page 5 of 16

Page 6: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Wrapper classesA wrapper class is a class that encapsulates (or wraps) one of the primitive data types, so that those types can be used to create object instances and methods that can be used by other objects.

For each of the eight primitive data types in Java, there is a corresponding wrapper class.

Primitive type Wrapper classbyte Byteshort Shortint Integerlong Longfloat Floatdouble Doublechar Characterboolean Boolean

In each case, the wrapper class provides a selection of helpful methods for working with primitives, such as converting to and from String objects, converting to various bases (e.g. binary or hexadecimal), or comparing various objects.

For example, the Integer wrapper class contains the toBinaryString() method that returns a string representation of an integer as an unsigned binary number:

int i = 56;String strBinary = Integer.toBinaryString(i); // strBinary is set to “111000”

Character methodsAssume the following variables have been declared for each of the examples below.

char c1 = ‘R’;boolean b;

A selection of Character methods Example

boolean isDigit(char ch)Returns true if, and only if, the character is a digit.

b = Character.isDigit(c1);// b = false

boolean isLetter(char ch)Returns true if, and only if, the character is a letter.

b = Character.isLetter(c1);// b = true

boolean isLetterOrDigit(char ch)Returns true if, and only if, the character is either a letter or a digit.

b = Character. isLetterOrDigit(c1);// b = true

boolean isSpace(char ch)Returns true if, and only if, the character is a space.

b = Character.isSpace(c1);// b = false

boolean isUpperCase(char ch)Returns true if, and only if, the character is upper case.

b = Character.isUpperCase(c1);// b = true

Claremont College 2016, based on Rosny College 2009 Page 6 of 16

Page 7: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

OperatorsOperators are used to change the value of a particular object. So to add two numbers you would use + (the addition operator).

Operators have the same precedence as they would in normal arithmetic.

brackets, division and multiplication addition and subtraction

Operators with the same priority have the same precedence (see table next page). When they occur together unary operators and assignment operators are evaluated right-to-left, and the other operators are evaluated left-to-right.

Note that if an expression has a number of operators:

a + b * c; // b * c is evaluated first and the result added to a.

Brackets can force a different order:

(a + b) * c // a + b is evaluated first and the result multiplied by c.

Examples of basic integer arithmetic operationsThe simplest assignment operator is the =. It should be thought of as “becomes equal to” because the value on the left of the operator becomes equal to the value on the right.

Assignment:

total = 9; //assigns the value 9 to variable total

Sum:

total = 4 + 7; //the variable total is assigned the value 4 + 7total = n + 4; //variable total becomes n + 4 where n is another integer variable.

Product:

prod = n * 4; // variable prod is assigned the value n * 4

Integer division:

quot = n / 4; // integer division truncates the result and does not round up // e.g. 5/4 => 1, 7/4 => 1

Integer remainder or modulus:

rem = n%4; // this gives the remainder after integer division // e.g. 5%4 => 1, 7%4 => 3

Compound assignment operatorsJava has compound assignment operators that provide shortcuts for the some of previous operators.

For example:

total = total + 5; // <variable> = <variable> + <expression>total += 5; // <variable> += <expression>

The full list of these alternative operators is below:

+= add and assign operator-= subtract and assign operator*= multiply and assign operator/= divide and assign operator%= modulus and assign operator

Claremont College 2016, based on Rosny College 2009 Page 7 of 16

Page 8: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Increment and decrement operatorsIn programming you often need to progressively add or subtract 1 to a value. To do this you can use the increment (++) or decrement (--) operators.

For example, the following three lines of code are equivalent to each other:

count = count + 1;count += 1;count++;

Decrement (--) works in the same way but progressively subtracts 1.

Increment and decrement also work for char variables. For example:

char myChar = ‘n’;myChar--; // myChar now contains ‘m’

Operator precedence

Operator Description Level Associativity

[].

()++--

access array elementaccess object member

invoke a methodpost-incrementpost-decrement

1 left to right

++--+-!~

pre-incrementpre-decrement

unary plusunary minuslogical NOTbitwise NOT

2 right to left

()new

castobject creation

3 right to left

* / % multiplicative 4 left to right

+ - +

additivestring concatenation

5 left to right

<< >> >>> shift 6 left to right

< <= > >=instanceof

relationaltype comparison

7 left to right

== != equality 8 left to right

& bitwise AND 9 left to right

^ bitwise XOR 10 left to right

| bitwise OR 11 left to right

&& conditional AND 12 left to right

|| conditional OR 13 left to right

?: conditional 14 right to left

= += -= *= /= %= &= ^= |=<<= >>= >>>=

assignment 15 right to left

Claremont College 2016, based on Rosny College 2009 Page 8 of 16

Page 9: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Mathematical methodsThe class Math contains methods for performing basic numeric operations.

Function Description

abs(int a) Returns the absolute integer value of a

abs(long a) Returns the absolute long value of a

abs(float a) Returns the absolute float value of a

abs(double a) Returns the absolute double value of a

cos(double) Returns the trigonometric cosine of an angle

exp(double a) Returns the exponential number e(2.718...) raised to the power of a

log(double a) Returns the natural logarithm (base e) of a

max(int a, int b) Takes two int values, a and b, and returns the greater of the two

max(long a, long b) Takes two long values, a and b, and returns the greater of the two

max(float a, float b) Takes two float values, a and b, and returns the greater of the two

max(double a, double b) Takes two double values, a and b, and returns the greater of the two

min(int a, int b) Takes two integer values, a and b, and returns the smaller of the two

min(long a, long b) Takes two long values, a and b, and returns the smaller of the two

min(float a, float b) Takes two float values, a and b, and returns the smaller of the two

min(double a, double b) Takes two double values, a and b, and returns the smaller of the two

pow(double a, double b) Returns the number a raised to the power of b

random() Generates a random number between 0.0 and 1.0 eg. (int)(Math.random()*4+2) will give one of the values 2, 3, 4 or 5.

round(float) Rounds off a float value by first adding 0.5 to it and then returning the largest integer that is less than or equal to this new value

round(double) Rounds off a double value by first adding 0.5 to it and then returning the largest integer that is less than or equal to this new value

sin(double) Returns the trigonometric sine of an angle

sqrt(double) Returns the square root of a

tan(double) Returns the trigonometric tangent of an angle

toDegrees(double) Translates radians to degrees

toRadians(double) Translates degrees to radians

Claremont College 2016, based on Rosny College 2009 Page 9 of 16

Page 10: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

String objectsA String is a series of characters (sometimes referred to a “character string” or “text string”) that is treated as a single unit. Strings may include letters, digits and various special characters such as +, -, *, /, and $.

Strings are written as a sequence of characters in double quotation marks such as:

“Claremont College”“61 Link Road”“Claremont, Tasmania”“(03) 6249 6868”

In Java, strings are objects. Although strings are not one of the eight primitive data types, they are used so often that they are treated in a special way that means they are a little easier to work with than other objects.

String objects are immutable, which means that once created, their values cannot be changed. Despite this, the String class has a number of methods that appear to modify strings. What these methods really do, however, is to create and return a new string that contains the result of the operation.

ConcatenationStrings can be concatenated (i.e. joined together) using the + symbol.

String s1 = “Hello”;String s2 = “World!”;g.drawString(s1 + s2,20,20); // Displays “HelloWorld!” at 20,20g.drawString(“s1” + “ Dave!”,20,40); // Displays “Hello Dave!” at 20,40

Concatenation is also used to display any primitive type variables. A string is concatenated to the variable with a + sign so it can be displayed in the Applet window using paint().

int total = 160;g.drawString("Total: " + total,20,60); // Displys “Total: 160” at 20,60

Comparing stringsBecause strings are objects, the comparison operator (==) only tells us whether two strings are the same object, not whether the strings they contain are equal. Instead we need to use a String method, either equals( ) or equalsIgnoreCase( ). For example

if (string1.equals(string2)) <do something>;

if (string1.equalsIgnoreCase(string2)) <do something>;

The String method compareTo() can be also used to check if strings are equal, but can also tell us whether a string precedes or follows another string in alphabetical order. The method compareTo() uses the ASCII code for the characters in the string to compare the strings.

If the resulting number is 0 (zero) then the two strings are the same. If the number is positive (i.e. > 0) then the first string comes later in the alphabet than the second

string. If the number is negative (i.e. < 0) then the first string comes before the second string in the

alphabet.

For example:

String s1 = "horse";String s2 = "cow”; String s3 = "Horse"int result; // In ASCII, 'h' is 104, 'H' is 72 and 'c' is 99

Claremont College 2016, based on Rosny College 2009 Page 10 of 16

Page 11: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

result = s1.compareTo(s2); // result = +5 (ie 104 - 99) butresult = s2.compareTo(s1); // result = -5 (99 - 104)andresult = s1.compareTo(s3); // result = + 32 (104 - 72)

Remember that upper case letters (or capitals) have a lower ASCII value than their lower case letter, so any string starting with a capital will be before any lower case letter.

Extracting substringsThe substring(),startsWith( ), endsWith( ) methods can be used to extract a substring from a string. Remember that the first character in a string is character 0.

For example:

String s3 = "Horse" String s4 = " " s4 = s3.substring(n) // returns the substring from position n onwards s4 = s3.substring(2) // s4 = “rse”s4 = s3.substring(n, m) // returns the substring from position n to position (m – 1)s4 = s3.substring(2,4) // will make s4 = “rs”.(ie from position 2 to 4-1 or 3) s4 = s3.substring(2,2) // would return “” because you can’t start at 2 and end at 1

String string5 = "What are we testing here?";boolean answer;

answer = string5.startsWith("Whi"); // will set answer to falseanswer = string5.endsWith("?"); // will set answer to true

String conversionTo convert data entered into a TextField to a String format use the getText() method. For example:

String name;name = nameTextField.getText( );

Data that is input from the keyboard is in the form of a text string. Java has a range of "parse" methods to convert strings into a variety of types - int, float or double - for processing. Many classes in the Java library give a toString() method to give a String representation of an object.

Remember that the primitive data types (e.g. int, float, double) are not classes so they don’t include any methods. We need to use the corresponding wrapper classes (e.g. Integer, Float, Double) for the primitives to achieve the conversion.

The wrapper classes for Float and Double value give a valueOf() method to convert a String value to a number.

Objects of type String contain an array whose components are of type char. For example, to convert an array of char to and from a String object:

char[ ] ch1 = {‘o’,‘b’,‘j’,‘e’,‘c’,‘t’}; // an array of characters is createdString str1 = new String(ch1); // str1 is the String “object”String str2 = new String(ch1, 1, 4); // str2 is the substring “bjec”char[ ] ch2 = str2.toCharArray( ); // ch2 is an array of characters

// {‘b’,‘j’,‘e’,‘c’}

Using the following variables which have been declared in a class as an example:

int n = 123;String s = "789";TextField textIn;float ff = 12.34f;double dd = 12.56;char ch = 'A';

s = Integer.toString(n); // s is set to "123"s = Float.toString(ff); // s is set to "12.34"s = Double.toString(dd); // s is set to "12.56"n = Integer.parseInt(s); // n is set to the integer 789

Claremont College 2016, based on Rosny College 2009 Page 11 of 16

Page 12: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

// we use a combination of parseInt() and getText() to get a string of digits // that have been entered in a TextField (called here textIn) n = Integer.parseInt(textIn.getText())

Converting real numbers is more complex and requires extra methods.

In this example, the method valueOf() is used to give a Float result and then the floatValue() method to convert the Float wrapper class to a float primitive:

ff = Float.valueOf(s).floatValue();dd = Double.valueOf(s).doubleValue(); // same as above, but for doubles

You will more often use an even more complex statement if you get a real from a TextField.

dd = Double.valueOf(textIn.getText()).doubleValue();

Comparison of char and String

char StringVariable type Primitive type ObjectSpeed of processing Fast Slower than charNotation ‘A’ “A”Creation char charVal = ‘A’ String s = “Hello”To test equality if (charVal = = ‘A’)… if (s.equals(“Hello”))…

Claremont College 2016, based on Rosny College 2009 Page 12 of 16

Page 13: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

String methodsAssume the following variables have been declared for each of examples below.

String s = “Everybody! ”;String s1;char ch;int n;boolean b;

A selection of String methods Example

int length()returns the number of characters in the String.

n = s.length();// n = 11

String toUpperCase()Converts all the characters in the String to upper case.

s1 = s.toUpperCase();// s1 = “EVERYBODY! ”

String toLowerCase()Converts all the characters in the String to lower case.

s1 = s.toLowerCase();// s1 = “everybody! ”

String replace(char oldChar, char NewChar)Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.

s1 = s.replace(‘e’, ’a’);// s1 = “Evarybody! ”

String trim()Removes all spaces and return lines at the start and end of a string

s1 = s.trim();// s1 = “Everybody!”

char charAt(int index)Gives the character at position number n in a string

ch = s.charAt(5);// ch = ‘b’

String substring(int beginIndex)Returns a substring of this string, starting at beginIndex.

s1 = s.substring(5);// s1 = “body! ”

String substring(int beginIndex, int endIndex)Returns a substring of this string, starting at

beginIndex, and finishing at endIndex-1.

s1 = s.substring(0,5);// s1 = “Every”

boolean startsWith(String str)Returns true if, and only if, the String starts with str.

b = s.startsWith(“Every”);// b = true

boolean endsWith(String str) returns true if, and only if, s starts with s1.

b = s.endsWith(“body!”);// b = false

int indexOf(String str)Returns the index within this string of the first occurrence of the specified substring. Returns -1 if the substring isn’t found.

n = s.indexOf(“very”);// n = 1

int indexOf(String str, int fromIndex)Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. Returns -1 if the substring isn’t found.

s.indexOf(“very”,4);// n = -1

boolean isEmpty()Returns true if, and only if, length() is 0.

b = s.isEmpty();// b = false

For details of many, many more String methods, see: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html

Claremont College 2016, based on Rosny College 2009 Page 13 of 16

Page 14: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Type conversionIt is important to understand how types interrelate in a language. For example we need to know what happens if you add a float and an integer value together.

Java is a strongly typed language and at compile time the type of every variable is known. Java performs detailed type checking to help detect programming errors and has restrictions on when values can be converted from one type to another.

For example, consider the following expression that involves variables/values of more than one type (i.e. a mixed type expression):

int num1;float x, y;

x = num1 * y / 3; // this has both integer and float values/variables

This expression cannot be evaluated without converting all of the values in the expression to one type, in this case float (the higher type).

Reasons:

internal representation of values is different need to know what type the result will be the role of the operations may change (e.g. division does different things depending on whether its

operands are integers or floating-point numbers)

In some cases this type conversion is performed automatically by Java (promotion), in other cases the programmer needs to explicitly specify which values are converted and what they are converted to.

PromotionJava has an ordering of types from highest to lowest, as follows:

double float long int char boolean

When a mixed-type expression is evaluated, each value in the expression is automatically 'promoted' (converted) to the highest type involved in the expression.

Note: This has no permanent effect on the variables in the expression - a temporary copy of their value is made, and promoted.

Any type can be promoted to any higher type, with one exception: boolean. Boolean cannot be promoted, and may not be treated as a number in Java (this is different from C/C++).

The fundamental principle of promotion, and the ordering of types, is that no information is lost when we promote a value. eg converting from integer to float:

3 -> 3.0

This may not be the case if we convert from a type to a lower type e.g. converting from float to integer, which truncates the value of 3.7451 to 3

Therefore this type of conversion is not performed automatically, and must be specifically requested by the program.

Claremont College 2016, based on Rosny College 2009 Page 14 of 16

Page 15: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Cast operatorsCast operators are used to force conversion from a higher to a lower type. They consist of the name of the lower type in brackets, placed directly before the value to be converted.

In the following example, Math.random() returns a float value from 0 (inclusive) to 1 (exclusive), that we need to convert into an integer after scaling it to the range 0 (inclusive) to 10 (exclusive)..

secretNumber = 1 + (int) (Math.random()*10); // select a random integer from 1 to 10

This is the most common use of casting, although occasionally you may need to convert an integer to char, or a double to float.

Whenever we do type conversion like this, it’s important to ensure that the value is within the legal range of values for the lower type or an error could occur.

Another example where casting is required would be to average a series of integers, and display the result as a real number (a decimal fraction).

Take a class with the following variables declared:

int number, sum, numValues;double average……number = Integer.valueOf(input.getText()).intValue(); // get numbersum = sum + number; // add number to sumnumValues = numValues + 1; // increase the count of numbers inputaverage = sum / numValues; // calculate the averageshowStatus(Double.toString(average)); // show result in status bar

This will not work correctly. The result displayed will still be an integer. For example, consider that sum = 1719 and numValues = 17, then:

average = sum / numValues; // average is set to 101

If you use the cast operator on one of the integer values you will force a double answer:

average = (double) sum / numValues; // average is set to 101.117645

Contrast this with the following approach that doesn’t work:

average = (double) (sum / numValues); // average is set to 101.0

This doesn’t work because the result is calculated as an integer first, truncated to give an integer result, and then this whole number result is put in the float format! Epic fail!!

Casting between types char and intAnother use for casting is in converting a character to its ASCII value (an integer) or the reverse.

charValue = (char) (65); // charValue = ’A’ (65 is the ASCII/Unicode value of ‘A’)numValue = (int) (‘A’); // numValue = 65

Claremont College 2016, based on Rosny College 2009 Page 15 of 16

Page 16: Identifiers -    Web view27845// a literal number cannot be used as an identifier. ... division and multiplication. ... When a mixed-type expression is evaluated,

Java primitive type conversionsHere is a summary of primitive type conversions in Java, showing which conversions happen automatically, which are possible through explicit casting, and which can’t be performed.

Convert from:

Convert to:

boolean byte short char int long float double

boolean -- X X X X X X X

byte X -- Y C Y Y Y Y

short X C -- C Y Y Y Y

char X C C -- Y Y Y Y

int X C C C -- Y Y* Y

long X C C C C -- Y* Y*

float X C C C C C -- Y

double X C C C C C C --

Where:

X the conversion cannot be performed. Y the conversion is a widening conversion and is performed automatically and implicitly by Java. Y* the conversion is an automatically widening conversion but some of the least significant digits

of the value may be lost e.g. converting an int or long to a float or double. C the conversion is a narrowing conversion and requires an explicit cast

A widening conversion occurs when a value of one type is converted to a wider type - one that is represented with more bits and therefore has a wider range of legal values. eg when assigning an int literal to a double variable or a char literal to an int variable.

A narrowing conversion occurs when a value is converted to a type that is represented with fewer bits. These are not always safe eg converting integer 13000 to a byte, because a byte can only hold numbers between –128 and + 127. The Java Compiler will complain about narrowing conversions.

Claremont College 2016, based on Rosny College 2009 Page 16 of 16