Presentation on theme: "Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can."— Presentation transcript:
1 Data Types in JavaData is the information that a program has to work with.Data is of different types. The type of a piece of data tells Java what can be done with it, and how much memory needs to be put aside for it.When we create a variable in Java, we need to specify:the type of the value we want to put in there, andthe name we will use for that variable.We have seen that when we enter the name of a Person object, we need to put it in quotes, but when we enter the age, we don't.This is because they are of different types.Draw a picture of a box representing a variable. Remind students that a variable is really a memory location that is put aside to hold a certain value. We give a name to that location and we never need to know where it actually is. We can put values in there and find out what values are in there whenever we like, by using the name of the variable.For an object, a variable is a place in memory where the state of the object is stored.
2 Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in itdata typevariable nameint total;int count, temp, result;Multiple variables can be created in one declarationint count=1, temp=0, result;Variables can also be given initial values
3 final int MIN_HEIGHT = 69; ConstantsA constant is an identifier that is similar to a variable except that it holds one value for its entire existenceThe compiler will issue an error if you try to change a constantIn Java, we use the final modifier to declare a constantfinal int MIN_HEIGHT = 69;Constants:give names to otherwise unclear literal valuesfacilitate changes to the codeprevent inadvertent errors
4 Numeric Primitive Data The difference between the various numeric primitive types is their size, and therefore the values they can store:TypebyteshortintlongfloatdoubleStorage8 bits16 bits32 bits64 bitsMin Value-128-32,768-2,147,483,648< -9 x 1018+/- 3.4 x 1038 with 7 significant digits+/- 1.7 x with 15 significant digitsMax Value12732,7672,147,483,647> 9 x 1018
5 Type int (byte, short, & long) An int is a whole number (e.g. 21). You can do arithmetic with an int.int age = 21;addition +subtraction -multiplication *division /modulus %21ageint age = 15;age + 32 * age - 4age / 2age % 10Explain the last 3 lines here. The first one creates a variable of type int and calls it age. The next two are expressions that use whatever value is stored in that variable.Talk about the symbols used for arithmetic, and what modulus means.An int is not an object. It doesn't have attributes and behaviour. It just has a single value. It can be one of the attributes of an object.On the overhead, show that you cannot do arithmetic with a String that looks like it might be an int, e.g. "2" Don't go into too much detail about variables and types, as we will do more on that in week 3.
6 Type double (float)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.95price * 0.1 might be working out a 10% discount, or the 10% GST. The final price of an item might be the last expression, i.e. the original price plus 10% of that.priceaddition +subtraction -multiplication *division /price * 0.10price / 2price + price * 0.1
7 Type boolean A boolean value represents a true or false condition A boolean can also be used to represent any two states, such as a light bulb being on or offThe reserved words true and false are the only valid values for a boolean typeboolean done = false;
8 Type charA 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 do arithmetic on a char.A String is a collection of chars.'Y'responseExplain the difference between "2", '2' and 2 briefly, and what you can do with each of these.
9 Type String A String is a collection of characters (e.g. "Sally"). String name = "Sally";A String value is always written in double quotes. You can have an empty String, shown as "".A String has many methods including:change itself to upper/lower casetell you how long it is (how many characters)give you the character at a specified positionthe string concatenation operator +SallynameTalk about what a character is. This was not mentioned in week 1's lecture but should be covered in CSE1200.Point out the line that creates a String with an initial value of "Sally".String is actually a class in Java. A String object has attributes including the collection of characters in it, and certain behaviours in its public interface. There are more than what are listed here.Open the editor window in BlueJ and show the part of the code for the Person class that defines the attributes. Don't worry about the rest of it.
10 result = total + count / max - offset; Operator PrecedenceOperators can be combined into complex expressionsresult = total + count / max - offset;Operators have a well-defined precedence which determines the order in which they are evaluatedMultiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenationArithmetic operators with the same precedence are evaluated from left to rightParentheses can always be used to force the evaluation order
11 Operator PrecedenceWhat is the order of evaluation in the following expressions?a + b + c + d + ea + b * c - d / e12343142a / (b + c) - d % e2143a / (b * (c + (d - e)))4321
12 Assignment RevisitedThe assignment operator has a lower precedence than the arithmetic operatorsFirst the expression on the right handside of the = operator is evaluatedanswer = sum / 4 + MAX * lowest;4132Then the result is stored in thevariable on the left hand side
13 Assignment RevisitedThe right and left hand sides of an assignment statement can contain the same variableFirst, one is added to theoriginal value of countcount = count + 1;Then the result is stored back into count(overwriting the original value)
14 Data ConversionsSometimes it is convenient to convert data from one type to anotherFor example, we may want to treat an integer as a floating point value during a computationConversions must be handled carefully to avoid losing informationWidening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int)Narrowing conversions can lose information because they tend to go from a large data type to a smaller one (such as an int to a short)
15 Data Conversions In Java, data conversions can occur in three ways: assignment conversionarithmetic promotioncastingAssignment conversion occurs when a value of one type is assigned to a variable of anotherOnly widening conversions can happen via assignmentArithmetic promotion happens automatically when operators in expressions convert their operands
16 result = (float) total / count; Data ConversionsCasting is the most powerful, and dangerous, technique for conversionBoth widening and narrowing conversions can be accomplished by explicitly casting a valueTo cast, the type is put in parentheses in front of the value being convertedFor example, if total and count are integers, but we want a floating point result when dividing them, we can cast total:result = (float) total / count;