01-JavaFundamentals - 1-1 Data Structures with Java and...

Info iconThis preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: 1-1 Data Structures with Java and JUnit Rick Mercer Chapter 1 Java Fundamentals The Java Class with a main method Types, Expressions, Assignment, I/O 1-2 Example Java Program // Read a number and display its squared value import java.util.Scanner; // In Java 5 only public class ReadItAndSquareIt { public static void main(String args) { double x; double result = 0.0; Scanner keyboard = new Scanner(System.in); System.out.print("Enter a number: "); x = keyboard.nextDouble(); result = x * x; System.out.println(x + " squared = " + result); } } 1-3 Pieces of a Java Program import java.util.Scanner; filename: ReadItAndSquareIt.java imports allow types without qualification Class heading public class ReadItAndSquareIt Method heading The first programs only have this one public static void main(String args) A class has a collection of methods between { and } Variable declaration and initialization examples double x; // Undefined, not garbage double result = 0.0; 1-4 Special Symbols A special symbol is one or two character sequences no spaces = < > () { ; } == . >= Some special symbols mean different things in different contexts. with two integers, + means addition 2 + 5 is the integer 7 "2" + "5" is the string "25" with two strings, + mean concatenation 1-5 Identifiers An identifier is a collection of certain characters that could mean a variety of things There are some existing Java identifiers sqrt String Integer System in out We can make up new identifiers test1 x1 aNumber MAXIMUM A_1 1-6 Valid Identifiers 'a'..'z', 'A'..'Z', '0'..'9', '_', $ Identifiers have from 1 to many characters: Identifiers start with letter a1 is legal, 1a is not can also start with underscore or dollar sign: _ $ Java is case sensitive. A and a are different. abc m/h main double e) f) g) h) $$$ 25or6to4 1_time first-name i) j) k) l) a_1 student Number String ______ Which of these are valid identifiers? a) b) c) d) 1-7 Reserved Identifiers Reserved identifier: An identifier with a pre-defined meaning that can not be changed Java reserved identifiers not a complete list boolean break case catch char class default do double else extends float for if import instanceOf int long new private public return void while 1-8 Literals -- Java has 6 varieties Floating-point literals 1.234 -12.5 0.0 0. .0 1e10 0.1e-5 String literals "between quotes" "another" "_" Integer literals -1 0 1 -2147483648 2147483647 Boolean literals (there are only two) true false The null literal (one value only) null Character literals 'A' 'b' '\n' '1' ' ' 1-9 Comments Example comments there are three kinds // on one line or /* between slash star you can mash lines */ /** javadoc * @return */ and star slash down real far comments for external documentation The square root of x Provides internal documentation to explain program Provides external documentation via javadoc Helps programmers understand code--including their own 1-10 Output General forms for doing output: System.out.print(expression); System.out.println(expression); Where expression may be any literal, variable, or arithmetic expression ... expression is shown to the console Examples (+ means concatenate) System.out.print("Enter test 1: "); System.out.println("Grade: " + courseGrade); System.out.println(1 + 2 + 3); // 6 System.out.println("1"+ 2 + 3); // 123 1-11 Assignment The programmer can set the values of a variable with assignment operations of this form: variable-name = expression ; Examples: double x; int j; // Undefined variables // not garbage or 0 (for now) j = 1; x = j + 0.23; 1-12 Memory before and after Variables x and j are undefined ? at first Variable Assigned Name j x ? ? Value Value 1 1.23 Initial ? means undefined The expression to the right of = must be a value that the variable can store (assignment compatible) x = "oooooh nooooo, you can't do that"; // <-Error j = x; // <-Error, can't assign a float to an int 1-13 Differences from C Declared variables are undefined, not garbage int x; System.out.println(x); // Compile time error Cannot assign doubles to ints int n = 0.99; // Compile time error, not 0 Must use real boolean values if(n = 1) // Compile time error, not true // It should read if(n == 1) 1-14 Input There are many options for reading numbers 1. use the decorator design pattern with classes such as BufferedReader has complex code Must handle exceptions, must parse the strings 2. use the new Java 5 Scanner class Relatively easy to use (less code to write) Can read from complicated files (variety of types) 1-15 The Java Scanner class Need to import java.util.Scanner Construct a Scanner object with new Then you can send messages (call functions) such as nextInt, nextDouble, and nextLine 1-16 Read 3 doubles import java.util.Scanner; public class ThreeNumbers { public static void main(String args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter 3 numbers: "); double x = keyboard.nextDouble(); double y = keyboard.nextDouble(); double z = keyboard.nextDouble(); double average = (x + y + z) / 3.0; System.out.println("Average: " + average); } } 1-17 Arithmetic Expressions Arithmetic expressions consist of operators such as + - / * and operands such as 40, 1.5, payRate, and hoursWorked Example expression used in an assignment: grossPay = payRate * hoursWorked; Another example expression: (40 * payRate) + 1.5 * payRate * (hoursWorked - 40) 1-18 int Arithmetic int variables are similar to double, except they can only store whole numbers (integers) int int int anInt = another NoCanDo 0; = 123; = 1.99; // ERROR Division with integers is also different Perfoms quotient remainder whole numbers only // anInt = 4, not 4.5 anInt = 9 / 2; anInt = anInt / 5; anInt = 5 / 2; What is anInt now? ________ What is anInt now? ________ 1-19 The integer % operation // anInt ___1___ _____ What is anInt now? _____ What is anInt now? The Java % operator returns the remainder anInt = 9 % 2; anInt = 101 % 2; anInt = 5 % 11; anInt = 361 % 60; _____ What is anInt now? int quarter; quarter = 79 % 50 / 25; ______ What is quarter? quarter = 57 % 50 / 25; ______ What is quarter now? 1-20 Precedence of Arithmetic Operators Expressions with more than one operator require some sort of precedence rules: * / % evaluated in a left to right order before - and + + evaluated left to right in the absence of parentheses 1-21 Compilation and Execution 1-22 Errors Categories of errors and warnings are detected during implementation 1. 2. 3. Compiletime errors Exceptions Intent errors You will experience many errors 1-23 Compilation and Execution Report compile time Errors 1-24 A few common compile time errors int myWeight = 0; int sum = 0; double x = 0.0; System.out.print("Hi"); keyboard.readDouble(); Splitting an identifier Misspelling a keyword integer sum = 0; double x = 0.0 int my Weight = 0; Leaving off a semicolon System.out.print("Hi); keyboard.readDouble; Not closing a string constant Forgetting parentheses 1-25 Exceptions Exceptions are errors that occur while the program is running Exceptions are thrown when the program encounters something it could not handle well Example Type in an invalid number during a nextInt message Division by 0 with integers (3.0/0.0 is Infinity) Index out of bounds with strings and arrays Attempt to open a file that is not present 1-26 Intent Errors When the program does what you typed, not what you intended. Imagine this code System.out.print("Enter sum: "); n = keyboard.nextInt(); System.out.print("Enter n: "); sum = keyboard.nextDouble(); average = sum / n; 1-27 Boolean Expressions Boolean expressions evaluate to true or false Will often see relational operators Operator Meaning < > <= >= == != Less than Greater than Less than or equal to Greater than or equal to Equal to Not equal to 1-28 Boolean Expressions Some boolean expressions and their resulting values double x = 4.0; Boolean Expression Value x < 5.0 x > 5.0 x <= 5.0 5.0 == x x != 5.0 true false ? ___________ ? ___________ ? ___________ ...
View Full Document

Ask a homework question - tutors are online