390 likes | 574 Views
Objectives. By the end of this lecture, students should be able to: explain the concepts of variables, operators, expressions, keywords give examples of operators and keywords give examples of variables of types int, double, char and boolean
E N D
Objectives • By the end of this lecture, students should be able to: • explain the concepts of variables, operators, expressions, keywords • give examples of operators and keywords • give examples of variables of types int, double, char and boolean • understand promotion and use casting where necessary • understand the difference between variables that hold basic data and variables that hold objects • Reading: Savitch, Section 1.2
Example Algorithm (Interest) • calculate interest • input: balance, interest rate • output: interest • interest = balance * interest rate variables 1000 5.0 50 balance interest interestRate
Variables A variable is a name for a value or an object. A variable can have an assigned value or be unassigned (not yet assigned). In a computer program the value of a variable is effectively stored in a particuar memory location and the variable itself is a name for this location.
Variables (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ...
Data Types in Java • Data is of different types. The type of a variable tells Java what can be done with it, and how much memory needs to be put aside for it. • When we declare a variable in Java, we need to specify: • the type of the value we want to put in there, and • the name we will use for that variable. • int age; • A Declaration like this effectively allocates the memory space required to store a value of this type.
A Computer Program (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ...
A Computer Program (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ... interestRate
A Computer Program (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ... interestRate balance
A Computer Program (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ... interestRate balance interest
A Computer Program (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ... 5 interestRate balance interest
A Computer Program (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ... 5 interestRate 1000 balance interest
A Computer Program (in Java) • ... • int interestRate; • int balance; • int interest; • interestRate = 5; • balance = 1000; • interest = balance * interestRate / 100; • ... 5 interestRate 1000 balance 50 interest
Type int • An int is a whole number (e.g. 21). You can do arithmetic with an int. • int age = 21; • addition + • subtraction - • multiplication * • division / • modulus % • Note that a declaration can also contain the an initialization (initial assignment) 21 age • int age = 15; • age + 3 • 2 * age - 4 • age / 2 • age % 10
Initialising a Variable • If a variable is not initialised in the declaration, Java gives it a default value (e.g. 0 for int). • Generally, you should never rely on automatic initalization, but give an initial value to a variable when you define it. • Relying on automatic initalization is dangerous and therefore bad style. • Most other programming languages do not initialize automatically, and an unitialized variable has a random value.
0 10 anAge anAge The Assignment Operator • In Java, the assignment operator is =. • This causes a value to be put in a memory location. • It is read as “becomes” or "takes on the value of ". • int anAge = 0; • allocates a memory location big enough for an integer, calls it anAge, and puts 0 in it. • anAge = 10; • puts 10 into an existing memory location called anAge.
Whole Number Types The whole number types are stored with one bit for the sign. The pattern for the number 13 stored as an int would be 00000000000000000000000000001101 byte -128 to 127 (8 bits) short -32,768 to 32,767 (16 bits) int -2,147,483,648 to 2,147,483,647 (32 bits) long -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (64 bits)
Type double • The type called double is used to store a real number , i.e. a number with a decimal point. It is stored in a different format from an int. • You can do arithmetic on a double. • double price = 3.95; 3.95 price addition + subtraction - multiplication * division/ modulus % price * 0.10 price / 2 price + price * 0.1
Floating Point Number Types The number types with a decimal point are stored with a sign bit, a mantissa and an exponent, in a base 2 system. (In the decimal system, 257.3 could be expressed as 2.573 * 10 where the sign is positive, the mantissa is 2.573 and the exponent is 2.) float -3.4e38 to +3.4e38 double -1.7e308 to +1.7e308 Most built-in methods for mathematics use the double type to be on the safe side. Generally, real-valued numbers cannot be expressed exactly by a computer. Therefore, precise comparisons of real-valued numbers are always dangerous. 2
Overflow and Underflow Java int i=256; System.out.println("i="+i); i=i*i; System.out.println("i*i="+i); i=i*i; System.out.println("i^4="+i); i=256 i*i=65536 i^4=0 This is called an overflow. “i” has exceeded the representational range of an integer.
Overflow and Underflow In the same way you can get an underflow when the variable cannot represent the true result with sufficient precision. The Java code double d=1/1e99; System.out.println("1/d="+d); d=d*d; System.out.println("1/(d*d)="+d); d=d*d; System.out.println("1/(d^4)="+d); 1/d=1.0E-99 1/(d*d)=1.0000000000000001E-198 1/(d^4)=0.0 This is called an underflow. “d” has exceeded the precision of a double.
Limits of Number Types The language contains the smallest and largest number each type can represent as constants. Note: For Integer, the MIN_VALUE is the smallest (negative) integer, but for Float and Double the MIN_VALUE is the smallest positive Value, ie. the precision that is available. Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE, Float.MIN_VALUE, Float.MAX_VALUE, Double, MIN_VALUE, Double.MAX_VALUE, etc… The name of the constant is the type name with the initial letter capitalized followed by a dot and MIN_VALUE or MAX_VALUE.
Type char A char is a character, i.e. a bit pattern you can produce by pressing a key (or a combination of keys) on a keyboard. Examples are 'a''A' '3''?''!' char response = 'Y'; You cannot add '3' and '2' and get '5'. 'Y' response
The char Type A character may be represented as a bit pattern in several different ways, depending on the code that is used. The best known code is ASCII (American Standard Code for Information Interchange) which uses patterns of 8 bits. Java uses Unicode, which adds an extra 8 bits to the ASCII sequences, to represent up to 65, 536 different characters. ASCII is a subset of Unicode A character literal is shown in single quotes, e.g. 'a'. Some special characters are represented by an escape sequence, using the escape character\, e.g. '\t' tab character '\n' newline character (the Enter key).
Type boolean • A boolean variable can have a value of only true or false. This can be stored as one bit • A Person object may or may not represent a student. We could have an attribute of Person called isStudent which would be either true or false for a particular Person instance. • boolean isStudent = true; true isStudent
The boolean Type The boolean type needs only 1 bit for storage because it uses 0 to represent false and 1 for true (or vice versa -- it doesn't matter which). A boolean variable can be assigned the result of any boolean expression, e.g. boolean inRange = (number >= 1 && number <= 6);
Incompatible Types Java is a strongly typed language. This means that every variable has a fixed type, and Java makes sure that you don't put a value of the wrong kind into it. int number = 2.3; will produce a syntax error. So will long bigNumber = 0; int number = bigNumber; float answer = Math.pow(2.3, 4.9); Possible loss of precision
Integer Division The operator / performs an integer division. The answer is an integer. Any remainder will be discarded. If you want to know what the remainder is, the operator % (called modulus) will give it to you. int number1 = 13, number2 = 5; number1 / number2returns 2 number1 % number 2returns 3
Casting (Explicit Conversion) Sometimes we need a value to be converted to a different type, e.g. when a library method returns a value that is a different type from what we want, or when we want a double answer from an integer division. We can specify a conversion, or cast the value into the new type: int dieRoll = (int)(Math.random() * 6) + 1; float answer = (float)Math.pow(2.3, 4.9); double kilometerage = (double) kilometres / litres; A cast creates a temporary storage area. It does not change the type of the initial value.
Type Coercion A “safe” typecast is sometimes performed automatically in Java, if there is no danger of loss of information (based on the types, not the values). Such an automatic typecast is called a coercion. It does not change the type of any existing variable. double cannot be promoted to anything float can be promoted to double long can be promoted to float or double int can be promoted to long, float or double char can be promoted to int, long, float or double short can be promoted to int, long, float or double byte can be promoted to short, int, long, float or double boolean cannot be promoted to anything int x = 0; float y = x; performs a coercion
Strings • int, char, double, boolean etc. are examples of primitive data types. These are built-in to Java and are the basis of other types. • A string is a collection of characters (e.g. "Sally"). A String object has this collection of chars in its attribute area. • e.g. String name = "Sally"; • A String value is always written in double quotes. You can have an empty String, shown as "". • !!! String is not a primitive data type. • !!! It is a class. • Even though this is not just a minor issue, we will ignore this for now and pretend it is a datatype. Java contains a lot of built-in String operations that we will introduce later. A simple example is string concatenation: • String title = “When Harry met “+name;
Type Checking • Java will not allow a value of the wrong type to be put into a variable. • If we write, for example, • int aNumber = "3"; • BlueJ will give the error message • incompatible types -found java.lang.String but expected int • String aName = 77; • produces the error message • incompatible types - found int but expected java.lang.String.
Expressions An expression returns a value. The value replaces the expression in the code. We evaluate the expression to get its value. The value can be assigned to a variable, or passed to a method as an argument, or used in another expression. An expression has a type, and in an assignment the left-hand side and right-hand side types must be identical. int aNumber = 0; aNumber aNumber = aNumber + 1; aNumber * 10 / 2 - 1; The simplest thing you might want to do with a value is print it out: System.out.println(aNumber/2);
Precedence Rules for Evaluating Expressions Highest precedence Parentheses (brackets) Unary operators + - ! Binary arithmetic operators * / % Binary arithmetic operators + - Relational operators < > <= >= Relational operators == != Logical operator && Logical operator || Lowest precedence
Constants Sometimes a class or a method wants a variable to have a value that cannot be changed. This is called a constant. In order to make sure that the value cannot be changed, the variable is declared as final. final int NUMBER_OF_PLACES = 10; final String HEADING = "Monash"; final double PI = 3.142;
Calculating the Area of a Circle ... final double PI = 3.142; double radius = 2.5; System.out.println("Radius of circle is " + radius + " metres"); System.out.println("Area is " + PI * radius * radius + " square metres"); ... Which type will the expression PI * radius * radius produce?
Built-in Mathematics You will want to use more complex mathematical operations, such as square root, logarithms etc. These are built-in, but you need a special syntax to use them. ... double a = Math.sqrt(10); double b = Math.log(5); ... The explanation for this syntax is that these operations are pre-defined static methods in the “service” class Math. We will encounter these concepts in the next week.
Numerical Errors Mathematically, the value of some expressions is not well-defined. Computing such an expression usually returns some special (non-numeric) value. ... double x = 1/0; System.out.println(x); x = Math.log(0); System.out.println(x); x = Math.sqrt(-1); System.out.println(x); ... This will print the values “infinity”, “-infinity” and “NaN” . We see that Java takes the limit value, where it can and produces “NaN” (not a number) where this is not defined.
Inifinity and NaN • The non-numerical values inifinity and NaN propagate through • expressions. For example, • inifinity + infinity = infinity • 3.5 / NaN = NaN • etc. • The details of this are, however, complicated. For now it is safest • to think of Infinity and NaN results as results that are not • allowed. You can test for these values: ... double x = 1/0.0; boolean a = Double.isInfinite(x); System.out.println(a); x = Math.log(0); a = Double.isInfinite(x); System.out.println(a); x = Math.sqrt(-1); a = Double.isNaN(x); System.out.println(a); ...