Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer Outline Distinguish the syntactical parts of a program • Tokens: special symbols, literals, identifiers, • Output with System.out.println • An executable program as a Java class with a main method Introduce two of Java's primitive types: int and double Preview: A Complete Java program import java.util.Scanner; // Read number from user and then display its squared value public class ReadItAndSquareIt { public static void main(String[] args) { double x; double result = 0.0; Scanner keyboard = new Scanner(System.in); // 1. Input System.out.print("Enter a number: "); x = keyboard.nextDouble(); // 2. Process result = x * x; // 3. Output System.out.println(x + " squared = " + result); } } Programs have 4 types of tokens The Java source code consists of 1) 2) 3) 4) special symbols + < = >= && || identifiers customerName totalBill n reserved identifiers int while if void literals 123 "A String" true These tokens build bigger things like variables, expressions, statements, methods, and classes. Also, comments exist for humans to read // Document your code if it is unreadable :-( Overloaded Symbols Some special symbols are operators and have different things in different contexts • with two integers, + sums integers 2 + 5 evaluates to the integer 7 • with two floating point literals, + sums to floating point (types make a difference) 2.0 + 5.0 evaluates to 7.0 • with two strings, + concatenates "2" + "5" evaluates to the new string "25" Identifiers An identifier is a collection of certain characters that could mean a variety of things There are some identifiers that are Java defines: sqrt String Integer System in out We can make up our own new identifiers test1 lastName dailyNumber MAXIMUM $A_1 Valid identifiers Identifiers have from 1 to many characters: 'a'..'z', 'A'..'Z', '0'..'9', '_', $ • 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 Which letters represent valid identifiers? a) abc b) m/h c) main d) $$$ e) 25or6to4 f) 1_time i) a_1 j) student Number k) String Reserved Identifiers (keywords) A keyword is an identifier with a pre-defined meaning that can't be changed it's reserved double int Other Java reserved identifiers not a complete list boolean break case catch char class default do double else extends float for new if private import public instanceOfreturn int void long while Literals -- Java has 6 Floating-point literals 1.234 -12.5 1.2 3. .4 1e10 0.1e-5 String literals "characters between double quotes" "'10" "_" Integer literals (Integer.MIN_VALUE and Integer.MIN_VALUE) -1 0 1 -2147483648 2147483647 Boolean literals (there are only two) true false Null (there is only this one value) null Character literals 'A' 'b' '\n' '1' ' ' Comments • Provide internal documentation to explain program • Provide external documentation with javadoc • Helps programmers understand code--including their own // on one line, or • There are three type of comments /* between slash star and star slash you can mash lines down real far, or */ /** * javadoc comments for external documentation * @return The square root of x */ public static double sqrt(double x) General Forms The book uses general forms to introduce parts of the Java programming language General forms provide information to create syntactically correct programs • Anything in yellow boldface must be written exactly as shown (println for example) • Anything in italic represents something that must be supplied by the user • The italicized portions are defined elsewhere Output Statements A statement, made up of tokens, is code that causes something to happen while the program runs General Forms for three output statements System.out.print( expression ); System.out.println(); System.out.println( expression ); Example Java code that writes text to the console System.out.print("hello world."); System.out.println(); // print a blank line System.out.println("Add new line after this"); General Form: A Java program // This Java code must be in a file named class-name.java public class class-name { public static void main(String[] args) { statement(s) } } // Example Program stored in the file HelloWorld.java import java.util.Scanner; public class HelloWorld { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.print("Enter your name: "); String myName = keyboard.next(); // keyboard input System.out.println("Hi Rick"); System.out.println("This is " + myName); } } Primitive Numeric Types Type: A set of values with associated operations Java has many types, a few for storing numbers • Stores integers in int variables • Store floating-point numbers in double variables A few operations for numeric types • Assignment Store a new value into a variable • Arithmetic +, -, * (multiplication), / • Methods Math.sqrt(4.0) See class Math for others Math.max(3, -9) Variables to store numbers To declare and give initial value: type identifier = initial-value; Examples int creditsA = 4; double gradeA = 3.67; String name = "Chris"; int hours = 10; boolean ready = hours >= 8; Assignment We change the values of variables with assignment operations of this general form variable-name = expression; Examples: double x; int j; // Undefined variables // can not be evaluated j = 1; x = j + 0.23; Memory before and after The primitive variables x and j are undefined at first Variable Name Initial Value j ? Assigned Value 1 ? means undefined x ? 1.23 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 Assignment double bill; What is value for bill now? _________ bill = 10.00; bill = bill + (0.06 * bill); What is value for bill now? ________ Which letters represent valid assignments given these 3 variable initializations? String s = "abc"; int n = 0; double x = 0.0; a) b) c) d) s n x s = = = = n; x; n; 1; e) f) g) h) n x s n = = = = 1.0; 999; "abc" + 1; 1 + 1.5; 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: 5 / 9 * (fahrenheit - 32); For the previous expression, Which are the operators?_____ Which are the operands?_____ Arithmetic Expressions Arithmetic expressions take many forms or or or or or or a numeric variable a numeric constant expression + expression expression - expression expression * expression expression / expression (expression ) double x = 1.2; 100 or 99.5 1.0 + x 2.5 - x 2*x x / 2.0 (1 + 2.0) Precedence of Arithmetic Operators Expressions with more than one operator require some sort of precedence rules: * - / + evaluated in a left to right order evaluated in a left to right order in the absence of parentheses Evaluate 2.0 + 4.0 - 6.0 * 8.0 / 6.0 Use (parentheses) for readability or to intentionally alter an expression: double C, F; F = 212.0; C = 5.0 / 9.0 * (F - 32); What is the current value of C ____? Math functions Java’s Math class provides a collection of mathematical and trigonometric functions returns 4.0 Math.min(-3, -9) returns -0 Math.max(-3.0, -9.0) returns -3.0 Math.abs(4 - 8) returns 4 Math.floor(1.9) returns 1.0 Math.pow(-2.0, 4.0) returns 16.0 Math.sqrt(16.0) int Arithmetic variables are similar to double, except they can only store whole numbers (integers) int int anInt = 0; int another = 123; int noCanDo = 1.99; // ERROR Division with integers is also different • Performs quotient remainder whole numbers only anInt = 9 / 2; // anInt = 4, not 4.5 anInt = anInt / 5; What is anInt now? ___ What is anInt now? ___ anInt = 5 / 2; The integer % operation The Java % operator returns the remainder anInt = 9 % 2; // anInt ___1___ anInt = 101 % 2; What is anInt now? ___ anInt = 5 % 11; What is anInt now? ___ anInt = 361 % 60; What is anInt now? ___ int quarter; quarter = 79 % 50 / 25; What is quarter? ___ quarter = 57 % 50 / 25; What is quarter now? ___ Integer Division, watch out … int celcius, fahrenheit; fahrenheit = 212; celcius = 5 / 9 * (fahrenheit - 32); What is the current value of celcius _____?