Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 3 - Java Basics First Java Program Comments

Similar presentations


Presentation on theme: "Chapter 3 - Java Basics First Java Program Comments"— Presentation transcript:

1 Chapter 3 - Java Basics First Java Program Comments
1 First Java Program Comments Class Name / Source Code Filename main Method Heading Braces System.out.println Compilation and Execution Program Template Identifiers Variables Assignment Statements Initialization Statements 2 3 1. In this chapter I demo these files: Hello.java FriendlyHello.java PrintPO.java PrintInitials.java 2. We'll now discuss Java ... 3. There's a lot to cover in this chapter and we'll go fairly quickly so be prepared to spend time reviewing your lecture notes after class.

2 Chapter 3 - Java Basics Numeric Data Types – int, long
Numeric Data Types – float, double Constants Arithmetic Operators Expression Evaluation Increment and Decrement Operators Compound Assignment Operators Type Casting Character Type - char Escape Sequences Primitive Variables vs. Reference Variables String Basics String Methods: equals, equalsIgnoreCase, length, charAt Input - the Scanner Class

3 First Java Program /***************************************
1 /*************************************** * Hello.java * John Dean * * This program prints a hello message. ***************************************/ public class Hello { public static void main(String[] args) System.out.println("Hello, world!"); } } // end class Hello 2 1. This is the traditional first program for all programming students. It simply prints a hello message. 2. Note the asterisked box at the top of the program. Next slide …

4 Comments Include comments in your programs in order to make them more readable/understandable. Block comment syntax: /* ... */ (Note: The /* and */ can optionally span multiple lines) One line comment syntax: // … Commented text is ignored by the compiler. Style requirement: Include a prologue section at the top of every program. The prologue section consists of: line of *'s filename programmer's name blank line program description 1 2 3 4 1. In the real world, you'll spend a lot of your time looking at and fixing other people's code. And other people will spend a lot of their time looking at fixing your code after you've moved to a different project. Thus, you need to make sure that your code is understandable. That's why I place a big emphasis on style. 2. I show the /* and */ in the previous slide. Note that the /* and */ can both be on the same line or they can span multiple lines. 3. I show the "end class Hello" in the previous slide. Why is that comment helpful? If you've got a long program and you've scrolled to the bottom of it, it's nice to know the name of the class without having to scroll all the way up to the actual class name. [I should not mention the rule about including comments for closing braces because I don't want to mention braces prematurely.] 4. Remember – the purpose of comments is to make the program more understandable to humans, but computers could care less about them! 5. I verify this prologue format on the previous slide. 5

5 Class Name / Source Code Filename
All Java programs must be enclosed in a class. Think of a class as the name of the program. The name of the Java program's file must match the name of the Java program's class (except that the filename has a .java extension added to it). Proper style dictates that class names start with an uppercase first letter. Since Java is case-sensitive, that means the filename should also start with an uppercase first letter. Case-sensitive means that the Java compiler does distinguish between lowercase and uppercase letters. 1 2 3 4 1. What's the name of the class in the program slide? Hello 2. What is a file? A file is a group of related data. For example: After entering your program on the computer, you'll save it as a program file. Then if you need to modify that program later on, you load the saved program file and edit it. 3. What should the filename be for our Hello program? Hello.java I show Hello.java in the prologue section. [4. I'm trying to keep things simple for now, so it's OK to use this filename/class name rule as is. However, the truth is that if you have a more complex program that has more than one class in it, then the filename doesn't have to match the class name.] 5. I verify that the Hello program's class name and filename start with an uppercase H by looking at the previous slide and then showing the filename on the PC. [6. Flanagan, p. 16 & p. 251: In one file, you can have multiple classes where none of them is public and none of them uses the filename for its class name. Rules - Maximum 1 public class per file. The public class (if there is a public class) must use the filename for its name. For a class to be the program's starting point, it must be public and must contain a main method.] 5 6

6 main Method Heading Memorize (and always use) public class prior to your class name. For example: public class Hello Inside your class, you must include one or more methods. A method is a group of instructions that solves one task. Later on, we'll have larger programs and they'll require multiple methods because they'll solve multiple tasks. But for now, we'll work with small programs that need only one method - the main method. Memorize (and always use) this main method heading: public static void main(String[] args) When a program starts, the computer looks for the main method and begins execution with the first statement after the main method heading. 1 2 1. You don't have to thoroughly understand the public access modifier yet, but in general terms, public means that the qualified entity can be accessed from anywhere. You want users, other than just yourself, to be able to run your program, so you need the class to be public. 2. I show the main heading in the previous program slide. 3. For next lecture's quiz, I'll ask you to write the main heading. Remind me! You don't have to thoroughly understand PSVMSA yet, but you already sort of know what public means: public means that something is accessible by everyone. 4. What's a good way to remember "public static void main" = PSVMSA? [5. Use the args parameter to access command line argument values. A command line argument value is a value that's entered as an argument when you initiate the execution of the program. For example, you could initiate this Welcome program by tacking on a person's name as a command line argument. Then maybe inside main you'd want to access the name and print it as part of the welcome message. For example, the message might say - "Welcome to Java programming, Bob!" To access a command line argument inside main, you need to use standard array syntax. How would you access the first command line argument? args[0] ] 3 4 5

7 Braces Use braces ({ }) to group things together.
For example, in the Hello World program, the top and bottom braces group the contents of the entire class, and the interior braces group the contents of the main method. Proper style dictates: Place an opening brace on a line by itself in the same column as the first character of the previous line. Place a closing brace on a line by itself in the same column as the opening brace. 1 1. See the hello world example. 2. See the hello world example. 2

8 System.out.println To generate output, use System.out.println().
For example, to print the hello message, we did this: System.out.println("Hello, world!"); Note: Put the printed item inside the parentheses. Surround strings with quotes. Put a semicolon at the end of a System.out.println statement. What's the significance of the ln in println? 1 2 1. Note all 3 items in the example. 2. It signifies that a newline will be printed at the end of the line. 3. Memorize System.out.println()! For next lecture's quiz, I'll ask you to write this command. Remind me! 4. When I write programs on paper, I abbreviate it to Sop. Remembering "Sop" helps me to remember "System.out.println.“ For now, don't worry about the details of why it's split into 3 parts (S.o.p) - just use it! 5. The SOP commands display output using an old-fashioned text-based format. In industry, you’d use SOP primarily for debug messages or for programs that are intended for internal use only. For programs that you’re trying to sell, you’d want a more polished look, and that means using GUI components. The book covers GUI components in chapters 16 and 17. 3 4 5

9 Compilation and Execution
1 2 To create a Java program that can be run on a computer, submit your Java source code to a compiler. We say that the compiler compiles the source code. In compiling the source code, the compiler generates a bytecode program that can be run by the computer's JVM (Java Virtual Machine). Java source code filename = <class-name> + .java Java bytecode filename = <class-name> + .class 3 4 5 1. We've now covered all the syntax in the hello program. I go back and skim the program and verify that all the syntax has been covered. After entering a program, you need to compile it before you can run it. Let's now cover compilation…. 2. This first bullet is complete review from Chapter 1 … 3. Remember what a class name is? I go back to the hello world program and show the Hello classname. Remember that proper style dictates that classnames use an uppercase first letter? 4. I go to Windows Explorer and show the Hello.java file and no Hello.class file. 5. I compile the hello world program and show the students the resulting Hello.class file. I run the hello program.

10 Identifiers Identifier = the technical term for a name in a programming language Identifier examples – class name identifier: Hello method name identifier: main variable name identifier: height Identifier naming rules: Must consist entirely of letters, digits, dollar signs ($), and/or underscore (_) characters. The first character must not be a digit. If these rules are broken, your program won't compile. 1 2 3 1. Hello was the class name in our hello world program. 2. manin was the method name in our hello world program. 3. We’ll cover Java variables coming up.

11 Identifiers Identifier naming conventions (style rules):
If these rules are broken, it won't affect your program's ability to compile, but your program will be harder to understand and you'll lose style points on your homework. Use letters and digits only, not $'s or _'s. All letters must be lowercase except the first letter in the second, third, etc. words. For example: firstName, x, daysInMonth Names must be descriptive. 1. Beginning programmers have a tendency to use names like x, y, and num. Normally, those are bad variable names. However, if the problem description says to read in a number and the number doesn't represent anything special, then x or num is OK. 2. See p. 7 in my Java Coding Style Guidelines document now. There's a section entitled Naming Conventions. It contains these naming conventions plus additional details. You are responsible for reading and using the entire style guidelines document. Note that you may not understand much of the document yet, since you don't know much Java, but you should still skim it now so that you know where to look things up in the future. 1 2

12 Style: comments must be aligned.
Variables A variable can hold only one type of data. For example, an integer variable can hold only integers, a string variable can hold only strings, etc. How does the computer know which type of data a particular variable can hold? Before a variable is used, its type must be declared in a declaration statement. Declaration statement syntax: <type> <list of variables separated by commas>; Example declarations: String firstName; // student's first name String lastName; // student's last name int studentId; int row, col; 1 1. Algorithm pseudocode is easier in that it doesn't require a lot of details like variable declarations. Get used to the idea of Java requiring lots of details like variable declarations, class heading, main method heading, etc. 2. Note that the declaration statements do follow the syntax pattern – note the semicolon in all four statements and the comma in the fourth statement. 3. What does int stand for? Integer! I'll discus individual data types in detail on subsequent slides. 4. As mentioned in the style guidelines, I normally require that you declare only one variable per line so you can have one comment per variable. Note the comments. 5. The only time it's OK to declare multiple variables on one line is when the variables are intimately related (such as with row and col). The only time it's OK to omit a variable declaration comment is for 1) variables that are standard (all programmers know what row and col mean), or 2) variables that are so well named that a comment would be useless (such as with studentId). 6. Note that comments must be aligned (they must start in the same column). 2 6 Style: comments must be aligned.

13 Assignment Statements
Java uses the single equal sign (=) for assignment statements. In the below code fragment, the first assignment statement assigns the value into the variable salary. int salary; String bonusMessage; salary = 50000; bonusMessage = "Bonus = $" + (.02 * salary); Note the + operator in the second assignment statement. If a + operator appears between a string and something else (e.g., a number or another string), then the + operator performs string concatenation. That means that the JVM appends the item at the right of the + to the item at the left of the +, forming a new string. Commas are not allowed in numbers. 1 2 3 string concatenation 1. I read the no-commas-in-numbers callout. I insert a comma in the in the example code and say "That would generate a compile error." 2. In the code fragment, the mathematical expression, .02 * salary, is evaluated first since it's inside parentheses. The JVM then appends the result, 1000, to “Bonus = $”, forming the new string “Bonus = $1000”. 3. Although the parentheses are not required by the compiler, we prefer to include them here because they help improve the code's readability. They improve readability because they make it clear that the math operation (0.2 * salary) is separate from the string concatenation operation.

14 Tracing Trace this code fragment:
int salary; String bonusMessage; salary = 50000; bonusMessage = "Bonus = $" + (.02 * salary); System.out.println(bonusMessage); salary bonusMessage output When you trace a declaration statement, write a ? in the declared variable's column, indicating that the variable exists, but it doesn't have a value yet. 1 2 1. I read the bottom bullet item. 2. I write on the board: salary bonusMessage output ? ? Bonus = $1000 Bonus = $1000

15 Program Template 1 In this chapter's slides, all of the code fragment examples can be converted to complete programs by plugging them into the <method-body> in this program template: /**************************************************** * Test.java * <author> * * <description> *****************************************************/ public class Test { public static void main(String[] args) <method-body> } } // end class Test 1. I know that students like to see complete program examples. 2. I go to the previous slide and show the assignment statements and explain how they could be inserted in the program template. If you insert the assignment statements in the program template, you could then enter the program on a computer and run it to verify that your trace is correct. 3. When we get to later chapters, I’ll show more complicated code and I’ll put the code inside complete programs. But for now, I'll just provide code that we'll pretend is inside of this program template. 2 3

16 Initialization Statements
When you assign a value to a variable as part of the variable's declaration. Initialization statement syntax: <type> <variable> = <value>; Example initializations: int totalScore = 0; // sum of all bowling scores int maxScore = 300; // maximum score in one game 1. As I said previously, proper style dictates one comment per line. 1

17 Initialization Statements
Example initializations (repeated from previous slide): int totalScore = 0; // sum of all bowling scores int maxScore = 300; // maximum score in one game Here's an alternative way to do the same thing using declaration and assignment statements (instead of using initialization statements): int totalScore; // sum of all bowling scores int maxScore // maximum score in one game totalScore = 0; maxScore = 300; It's OK to use either technique and you'll see it done both ways in the real world.

18 Numeric Data Types – int, long
1 Variables that hold whole numbers (e.g., 1000, -22) should normally be declared with one of these integer data types – int, long. Range of values that can be stored in an int variable:  -2 billion to +2 billion Range of values that can be stored in a long variable:  -9x1018 to +9x1018 Example integer variable declarations: int studentId; long satelliteDistanceTraveled; Recommendation: Use smaller types for variables that will never need to hold large values. 2 1. As you know, when you declare a variable, you have to specify the variable's type. I've already mentioned two Java data types – int and String. I'll now discuss numeric types in more detail. 2. What is a whole number? A number with no fractional component; i.e., no decimal point. 3. Student id numbers are always going to be less than 2 billion, so use an int. 4. The satelliteDistanceTraveled variable should be able to hold very large values. 5. If you attempt to store a really big number (a number over 2 billion) in an int variable, you'll get an "integer number too large" error when you compile your program. So to be safe, why shouldn't you just always declare your integer variables as type long rather than type int? An int takes up less storage in memory. And using less storage means your computer will run faster because there's more free space. So in the interest of speed/efficiency, use an int rather than a long for a variable that holds values less than 2 billion. However, if you're not sure whether a variable will hold values greater than 2 billion, play it safe and use a long. 3 4 5

19 Numeric Data Types – float, double
Variables that hold decimal numbers (e.g., , ) should be declared with one of these floating-point data types – float, double. Example code: float gpa; double bankAccountBalance; The double type stores numbers using 64 bits whereas the float type stores numbers using only 32 bits. That means that double variables are better than float variables in terms of being able to store bigger numbers and numbers with more significant digits. 1 2 1. Why are decimal numbers called floating point numbers? Because they can be written with scientific notation by shifting/floating the decimal point! What is the scientific notation form for ? I write this on the board and show the arrow hopping from the original decimal point position to the new decimal point position:  * 103 2. What's the origin of the name double? double variables use twice as many bits to store their data as float variables … 3. It should make sense that with more bits, a double number can hold a bigger decimal number. 4. With more bits, a double number can hold more significant digits. What are significant digits? Rough definition - the number of digits in a number, excluding any zeros at the left and any zeros at the right. 5. So in the example code, how many significant digits would you need for the gpa variable's value? Normally, transcripts show gpa's with only 2 or 3 significant digits. For example: 2.8, 3.41 Since a gpa variable doesn't need many significant digits, it's OK to use a float type for it. 6. How many significant digits would you need for the bankAccountBalance variable's value? It depends on the bank account, but here's a reasonable bank account value: 52,466.99 That's 7 significant digits and a float only handles up to 6 significant digits. That's why I used double for the bankAccountBalance variable. 3 6

20 Numeric Data Types – float, double
Recommendation: You should normally declare your floating point variables with the double type rather than the float type. In particular, don't use float variables when there are calculations involving money or scientific measurements. Those types of calculations require considerable accuracy and float variables are not very accurate. Range of values that can be stored in a float variable:  -3.4*1038 to +3.4*1038 Range of values that can be stored in a double variable:  -3.4*10308 to +3.4*10308 You can rely on 15 significant digits for a double variable, but only 6 significant digits for a float variable. 1 1. You don't need to memorize these next bullet items. Use them as a reference in case you need to look them up later on. 2. Float variables can hold big numbers; double variables can hold really big numbers. 3. Six significant digits is not all that many! 2 3

21 Assignments Between Numeric Data Types
1 Assigning an integer value into a floating-point variable works just fine. Note this example: double bankAccountBalance = 1000; On the other hand, assigning a floating-point value into an integer variable is like putting a large object into a small box. By default, that's illegal. For example, this generates an error: int temperature = 26.7; This statement also generates an error: int count = 0.0; 2 1. We've talked about assigning integer values into integer variables and floating-point values into floating-point variables, but we haven't talked about assignments where the types are different. 2. Assigning an integer value into a floating-point variable is like putting a small object into a large box. The int type only goes up to approximately 2 billion. It's easy to fit 2 billion into a double "box" because a double goes all the way up to 1.8 x 3. The 26.7 is a floating-point value and, as such, it cannot be assigned into the temperature int variable. That should make sense when you realize that it's impossible to store .7, the fractional portion of 26.7, in an int. After all, int variables don't store fractions; they only store whole numbers. 4. The rule says that it's illegal to assign a floating-point value into an integer variable. 0.0 is a floating-point value. It doesn't matter that the fractional portion of 0.0 is insignificant (it's .0); 0.0 is still a floating-point value and it's always illegal to assign a floating-point value into an integer variable. 3 4

22 Constants A constant is a fixed value. Examples:
1 A constant is a fixed value. Examples: 8, -45, : integer constants -34.6, .009, 8. : floating point constants "Hello, Bob", "hi" : string constants The default type for an integer constant is int (not long). The default type for a floating point constant is double (not float). 2 3 1. We've used numeric and string values in our examples, but I haven't given you the formal name for them…. 2. For a constant to be a floating-point constant, it must contain a decimal point, but numbers to the right of the decimal point are optional. Thus, 8. and 8.0 represent the same floating-point constant. 3. So in the example, 8 is an int. This is probably what you would have assumed since int sounds like integer, so I probably didn't even need to mention it. But the default for floating point constants is non-obvious…. 4. You'd think that the default would be the type with the more obvious name (like int is the default type for integers), but that's not the case. Lots of people forget this rule and it's the cause of many bugs. I'll give you an example of why you need to know it on the next slide…. 4

23 Constants This example code generates compile errors. Where and why?
float gpa = 2.30; float mpg; mpg = 28.6; Possible Solutions: Always use double variables instead of float variables. or To explicitly force a floating point constant to be float, use an f or F suffix. For example: float gpa = 2.30f; mpg = 28.6F; 1 2 1. The 2.30 and 28.6 are double values. They each have 64 bits and they can't squeeze into the 32-bit gpa and mpg variables so there's a compile-time error! 2. This is an acceptable solution, because as I said in the last slide, double is preferable to float for most occasions.

24 Constants Constants can be split into two categories: hard-coded constants and named constants. The constants we've covered so far can be referred to as hard-coded constants. A hard-coded constant is an explicitly specified value. For example, in this assignment statement, is a hard-coded constant: propagationDelay = cableLength / ; A named constant is a constant that has a name associated with it. For example, in this code fragment, SPEED_OF_LIGHT is a named constant: final double SPEED_OF_LIGHT = ; // in m/s ... propagationDelay = cableLength / SPEED_OF_LIGHT; division operator 1 1. The statement calculates the amount of time it takes an electrical signal to travel a certain distance in a cable. Does anyone know what represents? The speed of light in meters per second. 2. As you should be able to discern from this code fragment, a named constant is really a variable. Note how SPEED_OF_LIGHT is declared to be a double variable and it's initialized to the value How is the SPEED_OF_LIGHT initialization different from initializations that you've seen in the past? The word final appears at the left! 2

25 Named Constants The reserved word final is a modifier – it modifies SPEED_OF_LIGHT so that its value is fixed or "final." All named constants use the final modifier. The final modifier tells the compiler to generate an error if your program ever tries to change the final variable's value at a later time. Standard coding conventions suggest that you capitalize all characters in a named constant and use an underscore to separate the words in a multiple-word named constant. 1. I go to the previous slide and show that SPEED_OF_LIGHT does follow these coding conventions. 2. The rationale for the uppercase is that uppercase makes things stand out. And you want named constants to stand out because they represent special values. 1 2

26 Named Constants There are two main benefits of using named constants:
Using named constants leads to code that is more understandable. If a programmer ever needs to change a named constant's value, the change is easy – find the named constant initialization at the top of the method and change the initialization value. That implements the change automatically everywhere within the method. 1 1. We say that such code is self-documenting because the code itself explains the meaning, without needing a comment. 2. If you use a hard-coded constant in multiple places in your method and you decide later that you need to change the constant's value, you have to change the hard-coded constant throughout your method, wherever it appears. If you forget to change one of the occurrences of the hard-coded constant, your program won't work properly. If you use a named constant, it's much easier to update! 2

27 Arithmetic Operators Java's +, -, and * arithmetic operators perform addition, subtraction, and multiplication in the normal fashion. Java performs division differently depending on whether the numbers/operands being divided are integers or floating-point numbers. When the Java Virtual Machine (JVM) performs division on floating-point numbers, it performs "calculator division." We call it "calculator division" because Java's floating-point division works the same as division performed by a standard calculator. For example, if you divide 7.0 by 2.0 on your calculator, you get 3.5. Likewise, this code fragment prints 3.5: System.out.println(7.0 / 2.0); 1 1. Let's first discuss division with floating-point numbers.

28 Floating-Point Division
1 This next line says that 7.0 / 2.0 "evaluates to" 3.5: 7.0 / 2.0  3.5 This next line asks you to determine what 5 / 4. evaluates to: 5 / 4.  ? 5 is an int and 4. is a double. This is an example of a mixed expression. A mixed expression is an expression that contains operands with different data types. double values are considered to be more complex than int values because double values contain a fractional component. Whenever there's a mixed expression, the JVM temporarily promotes the less-complex operand's type so that it matches the more-complex operand's type, and then the JVM applies the operator. In the 5 / 4. expression, the 5 gets promoted to a double and then floating-point division is performed. The expression evaluates to 1.25. 1. In explaining arithmetic operators, we'll need to evaluate lots of expressions. To simplify that discussion, we'll use the => symbol to indicate "evaluates to."

29 Integer Division There are two ways to perform division on integers:
The / operator performs "grade school" division and generates the quotient. For example: 7 / 2  ? The % operator (called the modulus operator) performs "grade school" division and generates the remainder. For example: 7 % 2  ? 8 % 12  ? 1 1. 1. I do this division on the board and circle the resulting quotient of 3. 2. I do this division on the board and circle the resulting remainder of 1. 3. I do this division on the board and circle the resulting remainder of 8. 2 3

30 Expression Evaluation Practice
Given these initializations: int a = 5, b = 2; double c = 3.0; Use Chapter 3's operator precedence table to evaluate the following expressions: (c + a / b) / 10 * 5 (0 % a) + c + (0 / a) 1 2 1. I read the operator precedence table from the book. What does it mean if an operator is in a higher group than another operator? You should perform that operation first! Thus, multiplication and division should be performed before addition and subtraction. 2. On homework and on tests, show your work like this ... (c + a / b) / 10 * 5 => ( / 2) / 10 * 5 => ( ) / 10 * 5 => 5.0 / 10 * 5 => // Same precedence, so do the left one first .5 * 5 => // Mixed types convert to higher type 2.5 3. (0 % a) + c + (0 / a) => (0 % 5) (0 / 5) => (I show the grade school division.) => 3.0 3

31 Increment and Decrement Operators
1 Use the increment operator (++) operator to increment a variable by 1. Use the decrement operator (--) to decrement a variable by 1. Here's how they work: x++;  x = x + 1; x--;  x = x - 1; Proper style dictates that the increment and decrement operators should be used instead of statements like this. 2 1. Since incrementing and decrementing a variable by 1 is so common, there are special operators for that functionality. 2. The  means that the two things are equivalent.

32 Compound Assignment Operators
The compound assignment operators are: +=, -=, *=, /=, %= The variable is assigned an updated version of the variable's original value. Here's how they work: x += 3;  x = x + 3; x -= 4;  x = x - 4; Proper style dictates that compound assignment operators should be used instead of statements like this 1 Repeat the variable on both sides of the "=" 2 1. This probably won't make much sense until after you look at the examples.… 2. Note how in both examples, the variable is repeated on both sides of the "=". And the arithmetic operator goes immediately to the right of the repeated variable.

33 Tracing Practice Trace this code fragment: int a = 5, b = 2;
double c = 3.0; a += b; b++; c--; c *= a; System.out.println("a + b + c = " + (a + b + c)); 1 1. a b c output a + b + c = 24.0 14.0

34 Type Casting In writing a program, you'll sometimes need to convert a value to a different data type. The cast operator performs such conversions. Here's the syntax: (<type>) expression Suppose you've got a variable named interest that stores a bank account's interest as a double. You'd like to extract the dollars portion of the interest and store it in an int variable named interestInDollars. To do that, use the int cast operator like this: interestInDollars = (int) interest; cast operator 1 1. As shown, a cast operator consists of a data type inside parentheses. You should place a cast operator at the left of the value that you'd like to convert. 2. The int cast operator returns the whole number portion of the casted value, truncating the fractional portion. Thus, if interest contains the value 56.96, after the assignment, interestInDollars contains the value 56. Note that the cast operation does not change the value of interest. After the assignment, interest still contains 2

35 Parentheses are necessary here.
Type Casting If you ever need to cast more than just a single value or variable (i.e., you need to cast an expression), then make sure to put parentheses around the entire thing that you want casted. Note this example: double interestRate; double balance; int interestInDollars; ... interestInDollars = (int) (balance * interestRate); 1 Parentheses are necessary here. 1. In the interestInDollars assignment, balance * rate is the formula for calculating interest. This code fragment performs basically the same operation as the previous one-line code fragment. It extracts the dollars portion of the interest and stores it in an int variable named interestInDollars. The difference is that the interest this time is in the form of an expression, balance * rate, rather than in the form of a simple variable, interest. Since we need the cast operator to apply to the entire expression, we need to put parentheses around balance * rate. 2. In the above code fragment, what would happen if there were no parentheses around balance * rate? The cast would then apply only to the first thing at its right, balance, rather than the entire expression. That should make sense when you look at the operator precedence table. The operator precedence table shows that the cast operator has very high precedence. So without the parentheses, the cast operator would execute prior to the multiplication operator and the cast would thus apply only to balance. 2

36 Character Type - char A char variable holds a single character.
1 A char variable holds a single character. A char constant is surrounded by single quotes. Example char constants: 'B', '1', ':' Example code fragment: char first, middle, last; first = 'J'; middle = 'S'; last = 'D'; System.out.println("Hello, " + first + middle + last + '!'); What does this code fragment print? 2 3 1. So far, we've examined four of Java's data types – int, long, float, and double. Now let's examine one of Java's other data types – char. 2. The requirement of single quotes surrounding a char constant parallels the requirement of double quotes surrounding a string constant. The parallel syntax should make sense when you realize that strings and characters are intimately related – a string is a group of characters. 3. How many char constants do you see in the code fragment? 4 4. Hello, JSD! 4

37 Escape Sequences 1 Escape sequences are char constants for hard-to-print characters such as the enter character and the tab character. An escape sequence is comprised of a backslash (\) and another character. Common escape sequences: \n newline – go to first column in next line \t move the cursor to the next tab stop \\ print a backslash \" print a double quote \' print a single quote Provide a one-line print statement that prints these tabbed column headings followed by two blank lines: ID NAME Note that you can embed escape sequences inside strings the same way that you would embed any characters inside a string. For example, provide an improved one-line print statement for the above heading. Why is it called an "escape" sequence? 2 3 1. Usually, it's easy to write code to print a message. You just use SOP and put the message inside quotation marks. But some characters are hard to print ... 2. Why do you need a special escape sequence to print a backslash? Because if you attempt to print a backslash with just a standard backslash, the compiler will interpret the backslash as the beginning of an escape sequence. 3. Why do you need special escape sequences to print double and single quotes? Because if you attempt to print the quote marks with just standard quotes, the compiler will interpret the quotes as the beginning or end of a string or the beginning or end of a character. 4. System.out.println('\t' + "ID" + '\t' + "NAME" + '\n' + '\n'); 5. System.out.println("\tID\tNAME\n\n"); 6. Because the backslash forces an "escape" from the usual meaning of the specified character. With the backslash t, the "t" no longer represents the usual "t" character. 4 5 6

38 Primitive Variables vs. Reference Variables
There are two basic types of variables in Java – primitive variables and reference variables. Primitive variables hold only one piece of data. Primitive variables are declared with a primitive type and those types include: int, long (integer types) float, double (floating point types) char (character type) Reference variables are more complex - they can hold a group of related data. Reference variables are declared with a reference type and here are some example reference types: String, Calendar, programmer-defined classes 1. A string is a group of what type of data? A string is a group of characters. 2. The Calendar reference type allows you to store date information such as month, day, and year (don't worry about the details for now). We'll discuss programmer-defined classes later – don't worry about them for now. 3. Note that the String and Calendar reference types have uppercase first letters while the primitive types have all lowercase letters. 1 2 3 Reference types start with an uppercase first letter.

39 String Basics Example code for basic string manipulations:
1 Example code for basic string manipulations: String s1; String s2 = "and I say hello"; s1 = "goodbye"; s1 = "You say " + s1; s1 += ", " + s2 + '.'; System.out.println(s1); Trace the above code. declaration initialization 2 assignment concatenation, then assignment 3 4 concatenation, then compound assignment 5 1. Let's now focus on String reference variables. Some of this slide's material should look familiar since we've already covered strings a little bit. 2. What's an initialization? When you declare a variable and assign it a value all in one line. 3. The "+" sign causes the right string (s1) to be concatenated onto the end of the left string ("You say "). 4. Note the double quotes around the comma space and the single quotes around the period. The double quotes around the comma space are necessary because there is more than one character. Since the period is only one character, it's OK to use single quotes or double quotes. 5. I write on the board: s s2 goodbye and I say hello You say goodbye You say goodbye, and I say hello. output

40 String Methods String's charAt method:
1 String's charAt method: Returns the character in the given string at the specified position. The positions of the characters within a string are numbered starting with position zero. What's the output from this example code? String animal = "cow"; System.out.println("Last character: " + animal.charAt(2)); 1. We'll discuss methods in detail in Chapter 5. For now, just know that a method is a group of instructions that accomplishes one task. What's the method that you write yourself for every one of your programs? The main method! 2. Note the syntax for the method call – reference variable, dot, method name, parentheses. 3. What's the output? w 4. If you call charAt with an argument that's negative or with an argument that's equal to or greater than the string's length, your code will compile OK, but you’ll get an error message when you run it. 2 To use a method, include the reference variable, the dot, the method name, and the parentheses. 3 4

41 String Methods String's length method:
Returns the number of characters in the string. What's the output from this code fragment? String s = "hi"; System.out.println(s.length()); 1 2 3 1. Once again, note the syntax for the method call - variable, dot, method name, parentheses. 2. But this time, the parentheses are empty. You may be thinking "With no argument, why bother with the parentheses?“ In calling a method, you always need parentheses, even if they're empty. Without the parentheses, the compiler won't know that the method call is a method call. 3. What's the output? 2

42 String Methods To compare strings for equality, use the equals method. Use equalsIgnoreCase for case-insensitive equality. Trace this program: public class Test { public static void main(String[] args) String animal1 = "Horse"; String animal2 = "Fly"; String newCreature; newCreature = animal1 + animal2; System.out.println(newCreature.equals("HorseFly")); System.out.println(newCreature.equals("horsefly")); System.out.println(newCreature.equalsIgnoreCase("horsefly")); } // end main } // end class Test 1 2 1. Case-sensitive equality means you ignore the case (lower or upper) when comparing the strings. For example, John (with an uppercase J) and john (with a lowercase j) are considered equal when equalsIgnoreCase is used. 2. I coax them to write this: animal1 animal2 newCreature output Horse Fly HorseFly true false true

43 Input – the Scanner Class
1 Sun provides a pre-written class named Scanner, which allows you to get input from a user. To tell the compiler you want to use the Scanner class, insert the following import statement at the very beginning of your program (right after your prologue section and above the main method): import java.util.Scanner; At the beginning of your main method, insert this initialization statement: Scanner stdIn = new Scanner(System.in); After declaring stdIn as shown above, you can read and store a line of input by calling the nextLine method like this: <variable> = stdIn.nextLine(); 1. Up to this point, all our Java programs and code fragments have displayed information, but they haven't processed user input. With no input, our programs have been rather limited. In this section, we'll discuss how to get input from a user. With input, we'll be able to write programs that are much more flexible and useful. 2. This statement declares and initializes the reference variable, stdIn. Don't worry about the meaning of new Scanner(System.in). The meaning will become clear in Chapter 6, when we cover object-oriented programming details. For now, all you really need to know is that stdIn is a Scanner reference variable and it allows you to read input. 3. Let’s look at a program example on the next slide…. 2 3

44 Input – the Scanner Class
1 /********************************************************* * FriendlyHello.java * Dean & Dean * * This program displays a personalized Hello greeting. *********************************************************/ import java.util.Scanner; public class FriendlyHello { public static void main(String[] args) Scanner stdIn = new Scanner(System.in); String name; System.out.print("Enter your name: "); name = stdIn.nextLine(); System.out.println("Hello " + name + "!"); } // end main } // end class FriendlyHello These two statements create a keyboard-input connection. 1. I read the prologue and note the import, stdIn initialization, and nextLine lines. 2. Note the "Enter your name: " print statement. It uses a System.out.print statement rather than a System.out.println statement. Remember what the "ln" in println stands for? Newline! The System.out.println statement prints a message and then a newline character. So the cursor ends up on the next line. On the other hand, the System.out.print statement prints a message and that's it. The cursor ends up on the same line as the printed message (just to the right of the last printed character). So why did we bother to use a print statement instead of a println statement for the "Enter your name: " prompt? Because users are used to entering input just to the right of a prompt message. If we used println, then the user would have to enter input on the next line. 3. Note the colon and blank space at the end of the prompt. Once again, the rationale is that that's what users are used to. 4. I demo the FriendlyHello.java program. This gets a line of input. Use the print method (no “ln”) for most prompts. 2 3 4

45 Input – the Scanner Class
In addition to the nextLine method, the Scanner class contains quite a few other methods that get different forms of input. Here are some of those methods: nextInt() Skip leading whitespace until an int value is found. Return the int value. nextLong() Skip leading whitespace until a long value is found. Return the long value. nextFloat() Skip leading whitespace until a float value is found. Return the float value. nextDouble() Skip leading whitespace until a double value is found. Return the double value. next() Skip leading whitespace until a token is found. Return the token as a String value. 1 1. What is "leading whitespace"? I go to the next slide, read the first bullet item, and return here. 2. The next() method looks for a token. What is a "token"? I go to the second bullet item on the next slide and proceed normally. 2

46 Input – the Scanner Class
What is whitespace? Whitespace refers to all characters that appear as blanks on a display screen or printer. This includes the space character, the tab character, and the newline character. The newline character is generated with the enter key. Leading whitespace refers to whitespace characters that are at the left side of the input. What is a token? A token is a sequence of non-whitespace characters. What happens if the user provides invalid input for one of Scanner’s method calls? The JVM prints an error message and stops the program. For example, 45g and 45.0 are invalid inputs if nextInt() is called. 1 2 1. Think of a token as a word since the next method is usually used for reading in a single word. But more formally, … 2. I write the following on the board, and ask how many total tokens are in these 2 lines: Cows are cool! So are hedgehogs. There are 6 tokens. 3. Now for some complete programs that use this stuff…. 3

47 Input – the Scanner Class
Here's a program that uses Scanner’s nextDouble and nextInt methods: import java.util.Scanner; public class PrintPO { public static void main(String[] args) Scanner stdIn = new Scanner(System.in); double price; // price of purchase item int qty; // number of items purchased System.out.print("Price of purchase item: "); price = stdIn.nextDouble(); System.out.print("Quantity: "); qty = stdIn.nextInt(); System.out.println("Total purchase order = $" + price * qty); } // end main } // end class PrintPO 1. I show the nextDouble and nextInt method calls. 2. I load PrintPO.java and demo it. I enter valid values and watch the output. I then enter an invalid value and watch the crash. In Chapter 15, you'll learn how to avoid such crashes by using exception handling. 1 2

48 Input – the Scanner Class
Here's a program that uses Scanner’s next method: import java.util.Scanner; public class PrintInitials { public static void main(String[] args) Scanner stdIn = new Scanner(System.in); String first; // first name String last; // last name System.out.print( "Enter first and last name separated by a space: "); first = stdIn.next(); last = stdIn.next(); System.out.println("Your initials are " + first.charAt(0) + last.charAt(0) + "."); } // end main } // end class PrintInitials I show the next() method calls. 2. I show the charAt(0) calls. 3. I load PrintInitials.java and demo it. Note how it’s legal to input both words on the same line or on different lines (next skips leading whitespace). 1 2 3

49 Chapter 3 - Quiz Questions
Provide Java code for the main method heading. As always, be precise. Provide Java code for a print statement that prints "Hello world!" As always, be precise. 1. public static void main(String[] args) 2. System.out.println(“Hello world!”);


Download ppt "Chapter 3 - Java Basics First Java Program Comments"

Similar presentations


Ads by Google