Download presentation
Presentation is loading. Please wait.
Published byBertram McCormick Modified over 9 years ago
1
Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer
2
Outline Distinguish the syntactical parts of a program Tokens: special symbols, literals, identifiers, Tokens: special symbols, literals, identifiers, Output with System.out.println Output with System.out.println An executable program as a Java class with a main method An executable program as a Java class with a main method Introduce two of Java's primitive types: int and double
3
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); }
4
Programs have 4 types of tokens The Java source code consists of 1)special symbols + = && || 2)identifiers customerName totalBill n 3)reserved identifiers int while if void 4)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 :-( // Document your code if it is unreadable :-(
5
Overloaded Symbols Some special symbols are operators and have different things in different contexts with two integers, + sums integers with two integers, + sums integers 2 + 5 evaluates to the integer 7 2 + 5 evaluates to the integer 7 with two floating point literals, + sums to floating point (types make a difference) with two floating point literals, + sums to floating point (types make a difference) 2.0 + 5.0 evaluates to 7.0 2.0 + 5.0 evaluates to 7.0 with two strings, + concatenates with two strings, + concatenates "2" + "5" evaluates to the new string "25" "2" + "5" evaluates to the new string "25"
6
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 sqrt String Integer System in out We can make up our own new identifiers test1 lastName dailyNumber MAXIMUM $A_1 test1 lastName dailyNumber MAXIMUM $A_1
7
Valid identifiers 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 Identifiers start with letter a1 is legal, 1a is not can also start with underscore or dollar sign: _ $ can also start with underscore or dollar sign: _ $ Java is case sensitive. A and a are different Java is case sensitive. A and a are different Which letters represent valid identifiers? a) abcd) $$$i) a_1 a) abcd) $$$i) a_1 b) m/he) 25or6to4j) student Number b) m/he) 25or6to4j) student Number c) mainf) 1_timek) String c) mainf) 1_timek) String
8
Reserved Identifiers (keywords) A keyword is an identifier with a pre-defined meaning that can't be changed it's reserved doubleint double int Other Java reserved identifiers not a complete list booleandefaultfor new booleandefaultfor new breakdoif private breakdoif private casedoubleimport public casedoubleimport public catchelseinstanceOfreturn catchelseinstanceOfreturn charextendsint void charextendsint void classfloatlong while classfloatlong while
9
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 -1 0 1 -2147483648 2147483647 Boolean literals (there are only two) true false true false Null (there is only this one value) null null Character literals 'A' 'b' '\n' '1' ' ' 'A' 'b' '\n' '1' ' '
10
Comments Provide internal documentation to explain program Provide internal documentation to explain program Provide external documentation with javadoc Provide external documentation with javadoc Helps programmers understand code--including their own Helps programmers understand code--including their own There are three type of comments There are three type of comments // on one line, or /* 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)
11
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 yellow boldface must be written exactly as shown ( println for example) Anything in italic represents something that must be supplied by the user Anything in italic represents something that must be supplied by the user The italicized portions are defined elsewhere The italicized portions are defined elsewhere
12
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 ); 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.print("hello world."); System.out.println(); // print a blank line System.out.println(); // print a blank line System.out.println("Add new line after this"); System.out.println("Add new line after this");
13
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 ) { public static void main(String[] args ) { statement(s) 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); }
14
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 Stores integers in int variables Store floating-point numbers in double variables Store floating-point numbers in double variables A few operations for numeric types Assignment Store a new value into a variable Assignment Store a new value into a variable Arithmetic +, -, * (multiplication), / Arithmetic +, -, * (multiplication), / Methods Math.sqrt(4.0) Math.max(3, -9) Methods Math.sqrt(4.0) Math.max(3, -9) See class Math for others class Mathclass Math
15
Variables to store numbers To declare and give initial value: type identifier = initial-value ; type identifier = initial-value ; Examples int creditsA = 4; int creditsA = 4; double gradeA = 3.67; double gradeA = 3.67; String name = "Chris"; String name = "Chris"; int hours = 10; int hours = 10; boolean ready = hours >= 8; boolean ready = hours >= 8;
16
Assignment We change the values of variables with assignment operations of this general form variable-name = expression ; Examples: double x; // Undefined variables double x; // Undefined variables int j; // can not be evaluated int j; // can not be evaluated j = 1; j = 1; x = j + 0.23; x = j + 0.23;
17
Memory before and after The primitive variables x and j are undefined at first Variable Initial Assigned Variable Initial Assigned Name ValueValue Name ValueValue j ? 1 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 x = "oooooh nooooo, you can't do that"; // <-Error j = x; // <-Error, can't assign a float to an int j = x; // <-Error, can't assign a float to an int ? ? means undefined
18
Assignment double bill; double bill; What is value for bill now? _________ bill = 10.00; bill = 10.00; bill = bill + (0.06 * bill); bill = bill + (0.06 * bill); What is value for bill now? ________ Which letters represent valid assignments given these 3 variable initializations? String s = "abc"; String s = "abc"; int n = 0; int n = 0; double x = 0.0; double x = 0.0; a) s = n; e) n = 1.0; b) n = x; f) x = 999; c) x = n; g) s = "abc" + 1; d) s = 1; h) n = 1 + 1.5;
19
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; grossPay = payRate * hoursWorked; Another example expression: 5 / 9 * (fahrenheit - 32); 5 / 9 * (fahrenheit - 32); For the previous expression, Which are the operators?_____ Which are the operands?_____
20
Arithmetic Expressions a numeric variable double x = 1.2; a numeric variable double x = 1.2; or a numeric constant 100 or 99.5 or expression + expression 1.0 + x or expression - expression 2.5 - x or expression * expression2 * x or expression / expression x / 2.0 or (expression ) (1 + 2.0) Arithmetic expressions take many forms
21
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 - + evaluated in a left to right order in the absence of parentheses - + evaluated in a left to right order in the absence of parentheses Evaluate 2.0 + 4.0 - 6.0 * 8.0 / 6.0 Evaluate 2.0 + 4.0 - 6.0 * 8.0 / 6.0 Use (parentheses) for readability or to intentionally alter an expression: double C, F; double C, F; F = 212.0; F = 212.0; C = 5.0 / 9.0 * (F - 32); C = 5.0 / 9.0 * (F - 32); What is the current value of C ____? What is the current value of C ____?
22
Math functions Java’s Math class provides a collection of mathematical and trigonometric functions Math.sqrt(16.0) 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
23
int Arithmetic int variables are similar to double, except they can only store whole numbers (integers) int anInt = 0; int anInt = 0; int another = 123; int another = 123; int noCanDo = 1.99; // ERROR int noCanDo = 1.99; // ERROR Division with integers is also different Performs quotient remainder whole numbers only Performs quotient remainder whole numbers only anInt = 9 / 2; // anInt = 4, not 4.5 anInt = 9 / 2; // anInt = 4, not 4.5 anInt = anInt / 5; What is anInt now? ___ anInt = anInt / 5; What is anInt now? ___ anInt = 5 / 2; What is anInt now? ___ anInt = 5 / 2; What is anInt now? ___
24
The integer % operation The Java % operator returns the remainder anInt = 9 % 2;// anInt ___ 1 ___ anInt = 9 % 2;// anInt ___ 1 ___ anInt = 101 % 2; What is anInt now? ___ anInt = 101 % 2; What is anInt now? ___ anInt = 5 % 11; What is anInt now? ___ anInt = 5 % 11; What is anInt now? ___ anInt = 361 % 60; What is anInt now? ___ anInt = 361 % 60; What is anInt now? ___ int quarter; int quarter; quarter = 79 % 50 / 25; What is quarter? ___ quarter = 79 % 50 / 25; What is quarter? ___ quarter = 57 % 50 / 25; What is quarter now? ___ quarter = 57 % 50 / 25; What is quarter now? ___
25
Integer Division, watch out … What is the current value of celcius _____? What is the current value of celcius _____? int celcius, fahrenheit; fahrenheit = 212; celcius = 5 / 9 * (fahrenheit - 32);
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.