1.21k likes | 1.44k Views
Chapter 3 More Java Fundamentals. Sect 1 - More About Data Types and Variables Sect 2 - Order of Operations and Expression Evaluation Sect 3 - Method Signatures and User-Defined Methods Sect 4 - Problematic Order of Input Statements Sect 5 - Program Comments
E N D
Chapter 3More Java Fundamentals Sect 1 - More About Data Types and Variables Sect 2 - Order of Operations and Expression Evaluation Sect 3 - Method Signatures and User-Defined Methods Sect 4 - Problematic Order of Input Statements Sect 5 - Program Comments Sect 6 - More about Java Errors Sect 7 - Drawing and Painting in Java Go Go Go Go Go Go Go
Chapter 3 Section 1More About Data Types Primitive & Object Data Types Declaring Variables and other User-Defined Symbols Java Keywords Constants Constructing String and Other Objects The String length() method 2
3.1 Primitive & Object Data Types There are two categories of data types: 1.Primitive data types, specifically: int (integers) double (floating-point) char (characters) boolean (true or false) 2. Objects, for instance: String - characters, words, or sentences Scanner - can read from the keyboard or files Color - a color with red, green, & blue components JPanel - a canvas that can display painted or other items JApplet - a window that contains panels or other GUI items 3
3.1 Primitive & Object Data Types The Java syntax (rules) for manipulating primitive data types differs for objects: Primitive data types are combined in expressions with operators. Primitives are NOT constructed!You never construct a primitive!!! Objects are constructedand sent messages or objects call methods. 4
3.1 Declaring and Initializing Variables • Several variables can be declared in a single declaration as in • int x, y, z; but we don’t usually do this unless because it may not be evident that all three are int variables. • As you have found out, variables can be declared and initialized in one line of code: • int limit = 1000; • double q = 1.41; • String name = “Bill Jones”; • Note: Here we are initializing them but not constructing them. 5
3.1 Int & Double Primitive Data Types When you use primitive data types, you simply declare variables of those types and either initialize them with a literal value or give them a value from a method … int x = 15; int y = reader.nextInt(); int area = calculateArea(x, y); double num1 = 32.47; double num2 = reader.nextDouble(); double percent = getPercentage(num1, num2); 6
3.1 Six Numeric Data Types There are actually six numeric data types in Java but we will use only two. The six types and there storage amounts are: byte (an 8 bit integer) short (a 16 bit integer) int (a 32 bit integer) long (a 64 bit integer) float (a 32 bit floating-point) double(a 64 bit floating-point) Each uses a different number of bytes for storage and each has a different range of values. We will use only int and double in this class and those are the only two you need to know for the AP Exam. For more on these data types go to this link: Java’s Primitive Data Types 7
3.1 Int and Double Storage Requirements These are the only two storage requirements you need to be familiar with. Remember that 1 byte has 8 bits. int data takes 4 bytes which is equal to 32 bits. double data takes 8 bytes which is equal to 64 bits. This confirms the information on the previous slide. 8
3.1 Arithmetic Overflow Arithmetic overflowcan happen if you assign a value to a variable that is outside of the range of values that the data type can represent. For example if you are adding two int data type values, if their sum exceeds 2,147,483,647 then Java will wrap around to the lower limit (-2,147,483, 648) and proceed upwards toward zero to complete the addition, which will give you an incorrect value. Integer.MIN_VALUE and Integer.MAX_VALUE are constants that can be used in a program to access the limits of the int data type directly and provide protection for the program. They are constants of the Integer class. Integer.MIN_VALUE is equal to -2,147,483,648 Integer.MAX_VALUE is equal to 2,147,483,647 9
3.1 Java’s Scientific Notation of doubles Floating-point numbers (doubles) in Java will sometimes be displayed in scientific notation in the console output window. The number following the E is the exponent of the base 10. Numbers are displayed this way only when the number is very large or very small. 7.638E12 equivalent to 7.638 x 1012 4.259613E-8 equivalent to 4.259613 x 10-8 10
3.1 Char & Boolean Primitive Data Types Again, when you use primitive data types, you simply declare variable of those types and either initialize them with a literal value or give them a value from a method. Here are two primitive data types we haven’t discussed yet … char and boolean. A char is a single character that can be either an alphabetical letter, numeric digit, or a symbol from the keyboard.A boolean is either true or false with no double quotes around those values. charletter = ‘A’; char firstLetter = firstLetterOfName(studentName); booleandone = false; boolean eligible = checkEligibility(studentName); 11
3.1 Conceptualizing Variables variable radius 42.7 36.4 A variable is a named location in memory. Changing a variable’s value is equivalent to replacing or overwriting the value in that memory location. Here the variable radius has 42.7 stored in it, but it is overwritten with a new value, 36.4. These two lines of code do this: double radius = 42.7; radius = 36.4; Once a variable has been declared in a program of a certain type (like int), it cannot be changed to another data type (like double) later on in the code. Think about that. The reason is simple. Java cannot re-allocate a smaller or larger amount of memory “on the fly” for a variable. 12
3.1 Declaring Variables Before using a variable for the first time, you must declare its type. Here are several variable declaration statements that you are now familiar with: int age; double celsius; boolean done; String name; Scanner reader; The type appears on the left and the variable’s name on the right. <data type> <variable name> ; 13
3.1 Choosing Names in Java • Variable, method and program names are what we call user-defined symbols. • These names must begin with an alphabetical letter, the underscore character or the dollar symbol … followed by a sequence of letters and/or integer digits. No other symbols can be included, except for the underscore and dollar sign symbols. • So names can only include: • alphabetical letters: A .. Z • alphabetical letters: a .. z • numeric digits: 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. • the symbols: _ and $ 14
3.1 Java Keywords One additional rule about creating variable names is you cannot use Java keywords (also called reserved words) for variable names. These have special meaning in Java. These are words like print, println, class, public, and static, true, and false. You cannot use the name of any class that you know exists like Scanner for a variable name. However, you could use scanner (lower case). Also, it is important to note that keywords are case sensitive and areusually all lower caseso don’t try to capitalize any letters. For instance, always use import not Import or IMPORT. 15
3.1 Java Reserved Words Chart Some of Java’s most common reserved words. 16
3.1 Valid Variables with Meaningful Names It is very important to wisely choose meaningful variables names that increase a program’s readability and maintainability. Sometimes it requires more typing but consider the following variables for a program that might be read by someone other than the programmer that wrote the code: radius rather than r taxableIncome rather than ti Examples of valid and invalid variable names: Valid Names: surfaceArea3 or _$_$$$ (valid but not good) Invalid Names: 3rdPayment pay.rate public cool@#%&stuff can’t use these symbols can’t start with number can’t use a reserved word can’t use a dot 17
3.1 Naming Conventions By convention, when forming a compound variable name, programmers capitalize the first letter of each word except the first letter of the first word. (For example: incomeTax) However, when forming a program’s name each word will begin with a capital letter. (For example: ComputeEmployeePayroll or BestFriends) Constant names are formed using all uppercase letters with all words separated by underscores. (For example: SALES_TAX_RATE) 18
3.1 Variables Declared as Constants If variables are declared using the wordfinal, then the value stored in them cannot be changed or overwritten during the run of a program. We call these variables constants. Names of constants are always written in uppercase. It is a convention that all programmers follow. Here is the declaration of the constant SALES_TAX_RATE: public static final double SALES_TAX_RATE = 7.85; In any class file, if we want a constant to be able to be used anywhere in that file, then we have to include staticand declare it globally outside all methods. If we want the constant to be available to any other class then we also include public. 19
3.1 Constant Declaration Examples Here are some other constant variable declaration examples for int and String: public static final int MAXIMUM_GRADE = 100; public static final String DEFAULT_NAME = “John Doe”; Compare the above declarations to the declaration from the previous slide seen below. Note the similar pattern and the differences between int, double, and String constants. public static final double SALES_TAX_RATE = 7.85; 20
3.1 Constant Declaration Challenge Write the constant variable declaration for the constant that will represent a minimum grade of zero ... ??? 21
3.1 Constant Declaration Answer Write the constant variable declaration for the constant that will represent a minimum grade of zero ... ??? public static final int MAX_GRADE = 100; 22
3.1 Public Constants of a Class Sometimes constants are contained within classes other than the ones programmers are writing. For example, there is an Integer class in Java that can be used, but there is no reason to import it because it is in the java.lang packagethat is automatically imported into every Java program. If you had to import it, then the statement needed would be: import java.lang.Integer; Earlier when we discussed arithmetic overflow we mentioned these two constants: Integer.MIN_VALUE is equal to -2,147,483,648 Integer.MAX_VALUE is equal to 2,147,483,647 23
3.1 String Object Data Types String objects do not need to be constructed. They are automatically constructed. Here are two examples: String name = “Java”; or String word = reader.nextLine(); Notice there is no need to construct the String object first with a line of code like: String name = new String (“Java”); or String word = new String ( ); word = reader.nextLine(); This is a convenience for programmers who use Strings a lot. So they built it into Java to work this way. 24
3.1 The String length() Method Objects of the String class can be sent several different messages. One message we can send to a String object is“tell me your length”. We do this by calling the length() method. The length method will return us the number of characters of the value stored in a String object. Here is an example: String sentence=“Programming in Java is Fun!”; int theLength = sentence.length(); System.out.println(“The number of characters is ” + theLength); This will print … The number of characters is 27 25
3.1 The String length() Method In the lines of code … String sentence = “Programming in Java is Fun!”; int theLength = sentence.length(); We want to find the number of characters in the String variable sentence, so we use sentence to call the method length(). There are four ways we can say this. We can say we are … sending the message “length” to the String variable sentence calling the method length() with the String variable sentence executing the method length() with the String variable sentence invoking the method length() with the String variable sentence (All four ways of saying this mean the same thing!) 26
3.1 Constructing Object Types Objects must be constructed before being used. Instantiatemeans to construct. This is true of Scanner objects, Color objects, JFrame objects and others you will soon find out about. An object is constructed first, then it can be sent messages or then the object can call methods. Scannerreader = newScanner (System.in); // construct int x = reader.nextInt();// send the nextInt() message to reader reader is the Scanner variable that refers to the Scanner object! We can also say reader calls the method nextInt(). 27
3.1 Constructing Object Types You can construct a JPanel object to be referred to by the JPanel variable panel: JPanelpanel = newJPanel(); Then you can send the message setBackground with the parameter Color.pink to the object referred to by panel using: panel.setBackground(Color.pink); You can construct a JPanel object and place a constructed GridLayout object in the JPanel using the following code: JPanelpanel = newJPanel( newGridLayout( ) ); Since no variable refers to the GridLayout object being constructed, we can it an anonymous construction of a GridLayout object. 28
3.1 Important Note About Color Constants You probably remember initially being introduced to the color constants: Color.red Color.blue Color.green and others, where the words red, blue, green, etc. were not Capitalized. With early versions of Java they were not capitalized, however, both declarations exist in the Color class. In other words, you can use Color.RED or Color.red when writing code. Our preference will be to use Color.RED so let’s all follow the standard convention of capitalizing the value. 29
Chapter 3 Section 2Order of Operations and Expression Evaluation Order of Operations Binary and Unary Operators Precedence of Operators and Operations Mixed Mode Arithmetic Expressions Casting Rounding Floating-Point Numbers Escape Sequences More about Concatenation 30
3.2 Order of Operations An arithmetic expression consists of operands and operators combined in a manner just like algebra. The usual rules apply: Multiplication and division are evaluated before addition and subtraction. Operators of equal precedence are evaluated from left to right. Parentheses have the highest precedence and can be used to change the order of evaluation. 31
3.2 Binary & Unary Operators Multiplication must be indicated explicitly using * not implicitly. (In Java, a * bcannot be written as ab like in algebra ) Binary operators are placed between two operands a * b. Other binary operators are +, -, /, and %. a Unary operator is placed before its single operand as in -a. Both + and - are unary operatorsand are the only two that double as both binary and unary. 32
3.2 Precedence of Operators Chart 33 Commonly used operators and their precedence
3.2 Mixed Mode Arithmetic Expressions In Java, you can mix int and double values in expressions. We call these Mixed Mode Expressions. If you do, as seen below, you end up with a result that is a double. For example: double x = 18.2345; int y = 10; double sum = x + y; // sum contains 28.2345 double difference = x - y; // difference contains 8.2345 double product = x * y; // product contains 182.345 double quotient = x / y; // quotient contains 1.82345 34
3.2 Dividing Doubles and Ints Using / In Java, the division operator / calculates the quotient in two different ways. First, if a double is divided by a double, then it calculates the quotient exactly, as in .. 5.0 / 2.0 which yields 2.5 Second, if a double is divided by an int, then it calculates the quotient exactly, as in .. 5.0 / 2 yields 2.5 (this is mixed-mode arithmetic) Third, if an int is divided by an int, then it calculates the quotient and totally drops the remainder even if it is greater than or = to 1/2. 5 / 2 yields 2 (a quotient in which the remainder 1 of the division is simply dropped) 35
3.2 Mixed Mode Assignments Mixed-mode assignments are also allowed in Java, providedthe variable on the left is of the more inclusive type double than the int value on the right. Otherwise, a syntax error occurs. double d; int i; i = 45; // OK, because we assign an int to an int d = 45; // OK, because d is more inclusive than the int value 45, so 45.0 is stored in d. i = 45.0; // Syntax error.Can’t store a double in an int! 36
3.2 Mod Gives the Remainder of Division In Java, The mod operator % yields the remainder obtained when an int is divided by another int. Here are some examples: 9 % 5 yields 4 5 % 4 yields 1 5 % 2 yields 1 8 % 3 yields 2 13 % 7 yields 6 18 % 6 yields 0 Long hand division confirms these results. 37
3.2 Precedence of Evaluating Expressions When evaluating an expression, Java applies operators of higher precedence before those of lower precedence unless overridden by parentheses.It then follows left to right order of operations like algebra. Here are what some expressions yield: 3 + 5 * 3 yields 18 -3 + 5 * 3 yields 12 +3 + 5 * 3 yields 18 (use of unary + is uncommon) 3 + 5 * -3 yields -12 3 + 5 * +3 yields 18 (use of unary – is uncommon) (3 + 5) * 3 yields 24 3 + 5 % 3 yields 5 (3 + 5) % 3 yields 2 38
3.2 Casting to int or double Castinginvolves temporarily converting one data type to another for some purpose involving a calculation. You can cast a single variable or an entire expression. To do this, place the desired data type within parentheses before the variable or expression that will be cast to another data type. int i = (int) 3.14; // 3 is stored in i because (int) truncates the value double d = (double) 5 / 4; // stores 5.0 / 4 = 1.25 in d. 1.25 is stored because only the 5 is cast to a double, since 5 is the first thing after the cast operator (double). double d = (double) (5 / 4); // stores 1.0 in d … why? (see next slide) 39
3.2 Casting to int or double double d = (double) 5 / 4; // stores 5.0 / 4 = 1.25 in d double d = (double) (5 / 4); // stores 1.0 in d … why? Java will first evaluate 5 / 4 as int division that gives 1 since it is in parenthesis. The result of that is the one thing that the cast (double) is applied to. So the expression is essentially (double) 1 that gives 1.0 40
3.2 Rounding Positive Values The cast operator is useful for properly rounding positive floating-point numbers to the nearest integer. In fact, you need to know the following formula for the AP Exam. double p = 45.7; int answer = (int) (p + 0.5); Note the approach is to add 0.5 to the value you want to round, which is stored in x and then cast using (int) which truncates the calculated 46.2 to 46. So with positive numbers,adding 0.5 and casting to int rounds the value up or down properly. 45.7 + 0.5 = 46.2 (int) 46.2 ------> 46 41
3.2 Rounding Positive Values Here is a second example: double p = 45.2; int answer = (int) (p + 0.5); 45.2 + 0.5 = 45.7 (int) 45.7 ------> 45 42
3.2 Rounding Negative Values The cast operator is useful for properly rounding negative floating-point numbers to the nearest integer. In fact, you need to know the following formula for the AP Exam. double n = -22.4; int answer = (int) (n - 0.5) ; Note the approach is to subtract 0.5 from the value you want to round, which is stored in y and then cast using (int) which truncates the calculated -22.9 to -22. So with negative numbers,subtracting 0.5 and casting to int rounds the value up or down properly. -22.4 - 0.5 = -22.9 (int) (-22.9) ------> -22 43
3.2 Rounding Negative Values Here is a second example: double n = -22.8; int answer = (int) (n - 0.5); -22.8 - 0.5 = -23.3 (int) (-23.3) ------> -23 44
3.2 Escape Character & Escape Sequences • The Escape character (\) is used in code to represent characters that cannot be directly typed into a program. They are used when we want to output something to the screen in a special way. • To do this we combine the escape character \ with some other character to form an escape sequence. • Here are 4 different escape sequences: • \n is a new line character • \”is a double quotes character • \\ is a backslash character • \t is a tab character Let’s look at three particular escape sequences of the ones above … 45
3.2 Escape Character & Escape Sequences String literals are delimited (marked) by quotation marks (“…”), which presents a dilemma when quotation marks are supposed to appear inside a string sent to output. Placing a special character before the quotation mark, indicating the quotation mark is to be taken literally and not as a delimiter, solves the problem. This is where we use the escape character … the backslash \. Below, the blue “” double quotes surround the overall String parameter of the System.out.println statement and the red “” double quotespaired with \ indicate the double quotes to be shown in output. System.out.println(“the traffic cop yelled, \”Stop!\””); 46
3.2 Escape Character & Escape Sequences If we need to actually print a backslash, two consecutive backslashes \\ are used to accomplish this as seen in the following example: System.out.println(“C:\\Java\\Ch3.doc”); This will print to the screen …. C:\Java\Ch3.doc Additionally, \n can be used to create a new line. The following three lines of code accomplish exactly the same thing; System.out.println(“Java Rules!”); System.out.print(“Java Rules!\n”); System.out.print(“Java Rules!” + “\n”); 47
3.2 Concatenating Strings and Numbers As you learned in Chapter 2, Strings can be concatenated to numbers. What we didn’t tell you was that when we concatenate everything together the result is a String. What you may not have realized is that the parameter in a System.out.println statement has to be a String. Remember this line where num1 and num2 held integer values: System.out.println(num1 + " plus " + num2 + " is " + sum); This is actually a form of implicit (implied) casting where a number is automatically converted to a string before the concatenation operator is applied. So num1 is converted to a String and then it is joined to the word “plus” and so on. 48
3.2 Concatenating Strings and Numbers You can also concatenate numbers and strings together and store them in a String variable. We just found out that the result of concatenation is a String. String message; int x = 20, y = 35; message= “Bill sold ” + x + “ and Sylvia sold ” + y + “subscriptions.”; The String value “Bill sold 20 and Sylvia sold 35 subscriptions.” is stored in the String variable message. 49
3.2 Precedence of Concatenation • The concatenation operator has the same precedence as addition, which can lead to unexpected results: “number ” + 3 + 4 ---> “number 3” + 4 ---> “number 34” “number ” + (3 + 4) ---> “number ” + 7 ---> “number 7” “number ” + 3 * 4 ---> “number ” + 12 ---> “number 12” 3 + 4 + “ number” ---> 7 + “ number” ---> “7 number” Intermediate Values 50