Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

25
Java Fundamentals Java Fundamentals Asserting Java Asserting Java Chapter 2: Introduction to Computer Science Chapter 2: Introduction to Computer Science ©Rick Mercer ©Rick Mercer

Transcript of Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Page 1: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Java FundamentalsJava Fundamentals

Asserting JavaAsserting JavaChapter 2: Introduction to Computer ScienceChapter 2: Introduction to Computer Science©Rick Mercer©Rick Mercer

Page 2: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

OutlineOutline

Distinguish the syntactical parts of a programDistinguish the syntactical parts of a program• Tokens: special symbols, literals, identifiers, Tokens: special symbols, literals, identifiers,

• Output with System.out.printlnOutput with System.out.println

• An executable program as a Java class with a An executable program as a Java class with a

mainmain method method

Introduce two of Java's primitive types: Introduce two of Java's primitive types: intint and and doubledouble

Page 3: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Preview: A Complete Java program Preview: A Complete Java program import java.util.Scanner;

// Read number from user and then display its squared valuepublic 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); }}

Page 4: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Programs have 4 types of tokensPrograms have 4 types of tokens

The Java source code consists ofThe Java source code consists of1)1) special symbols special symbols + < = >= && || + < = >= && ||

2)2) identifiers identifiers customerName totalBill ncustomerName totalBill n

3)3) reserved identifiers reserved identifiers int while if voidint while if void

4)4) literals literals 123 "A String" true 123 "A String" true

These tokens build bigger things like variables, These tokens build bigger things like variables, expressions, statements, methods, and classes.expressions, statements, methods, and classes.

Also, comments exist for humans to readAlso, comments exist for humans to read // Document your code if it is unreadable :-(// Document your code if it is unreadable :-(

Page 5: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Overloaded SymbolsOverloaded Symbols

Some special symbols are operators and have Some special symbols are operators and have different things in different contextsdifferent things in different contexts• with two integers, + sums integerswith two integers, + sums integers

2 + 5 2 + 5 evaluates to the integer 7evaluates to the integer 7

• with two floating point literals, + sums to floating with two floating point literals, + sums to floating point (types make a difference)point (types make a difference)

2.0 + 5.0 2.0 + 5.0 evaluates to 7.0evaluates to 7.0

• with two strings, + concatenateswith two strings, + concatenates "2" + "5" "2" + "5" evaluates to the new string evaluates to the new string "25""25"

Page 6: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

IdentifiersIdentifiers

An An identifieridentifier is a collection of certain characters is a collection of certain characters that could mean a variety of thingsthat could mean a variety of things

There are some identifiers that are Java defines: There are some identifiers that are Java defines:

sqrt String Integer System in outsqrt String Integer System in out

We can make up our own new identifiers We can make up our own new identifiers

test1 lastName dailyNumber MAXIMUM $A_1test1 lastName dailyNumber MAXIMUM $A_1

Page 7: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Valid identifiersValid identifiers

Identifiers have from 1 to many characters: Identifiers have from 1 to many characters: 'a'..'z', 'A'..'Z', '0'..'9', '_', $'a'..'z', 'A'..'Z', '0'..'9', '_', $

• Identifiers start with letter Identifiers start with letter a1a1 is legal, is legal, 1a1a is not is not • can also start with underscore or dollar sign: can also start with underscore or dollar sign: _ $_ $

• Java is case sensitive. Java is case sensitive. AA and and aa are different are different

Which letters represent valid identifiers?Which letters represent valid identifiers? a)a) abc abc d)d) $$$ $$$ i)i) a_1 a_1 b)b) m/h m/h e)e) 25or6to4 25or6to4 j)j) student Number student Number c)c) main main f)f) 1_time 1_time k)k) String String

Page 8: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Reserved Identifiers (keywords)Reserved Identifiers (keywords)

A A keyword keyword is an identifier with a pre-defined is an identifier with a pre-defined meaning that can't be changed meaning that can't be changed it's reservedit's reserved

doubledouble intint

Other Java reserved identifiers Other Java reserved identifiers not a complete listnot a complete list booleanboolean defaultdefault forfor newnew breakbreak dodo ifif privateprivate casecase doubledouble importimport publicpublic catchcatch elseelse instanceOfinstanceOf returnreturn charchar extendsextends intint voidvoid classclass floatfloat longlong whilewhile

Page 9: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Literals -- Java has 6Literals -- Java has 6

Floating-point literalsFloating-point literals1.234 -12.5 1.2 3. .4 1e10 0.1e-51.234 -12.5 1.2 3. .4 1e10 0.1e-5

String literals String literals "characters between double quotes" "'10" "_""characters between double quotes" "'10" "_"

Integer literals Integer literals ((Integer.Integer.MIN_VALUEMIN_VALUE and and Integer.Integer.MIN_VALUEMIN_VALUE)) -1 0 1 -2147483648 2147483647-1 0 1 -2147483648 2147483647

Boolean literals (there are only two)Boolean literals (there are only two) true falsetrue false

Null (there is only this one value)Null (there is only this one value) nullnull

Character literals Character literals 'A' 'b' '\n' '1' ' ''A' 'b' '\n' '1' ' '

Page 10: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

CommentsComments • Provide internal documentation to explain program Provide internal documentation to explain program • Provide external documentation with javadocProvide external documentation with javadoc• Helps programmers understand code--including Helps programmers understand code--including

their owntheir own• There are three type of commentsThere 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)

Page 11: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

General FormsGeneral Forms

The book uses general forms to introduce parts of The book uses general forms to introduce parts of the Java programming languagethe Java programming language

General forms provide information to create General forms provide information to create syntactically correct programs syntactically correct programs • Anything in yellow boldface must be written exactly Anything in yellow boldface must be written exactly

as shown (as shown (println println for example) for example)

• Anything inAnything in italic italic represents something that must be represents something that must be supplied by the user supplied by the user • The italicized portions are defined elsewhereThe italicized portions are defined elsewhere

Page 12: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Output StatementsOutput Statements

A statement, made up of tokens, is code that causes A statement, made up of tokens, is code that causes something to happen while the program runssomething to happen while the program runs

General Forms for three output statementsGeneral Forms for three output statements System.out.print( System.out.print( expression expression );); System.out.println(); System.out.println(); System.out.println( System.out.println( expression expression ););

Example Java code that writes text to the consoleExample Java code that writes text to the console System.out.print("hello world.");System.out.print("hello world."); System.out.println(); System.out.println(); // print a blank line// print a blank line System.out.println("Add new line after this");System.out.println("Add new line after this");

Page 13: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

General Form: A Java programGeneral Form: A Java program//// This Java code must be in a file named class-nameThis Java code must be in a file named class-name.java.javapublic class public class class-nameclass-name { { public static void main(String[] public static void main(String[] argsargs) { ) { 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); } }

Page 14: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Primitive Numeric TypesPrimitive Numeric Types

TypeType: A set of values with associated operations: A set of values with associated operations

Java has many types, a few for storing numbersJava has many types, a few for storing numbers• Stores integers in Stores integers in intint variables variables

• Store floating-point numbers in Store floating-point numbers in doubledouble variables variables

A few operations for numeric typesA few operations for numeric types• AssignmentAssignment Store a new value into a variableStore a new value into a variable

• ArithmeticArithmetic +, -, * (multiplication), / +, -, * (multiplication), /

• MethodsMethods Math.sqrt(4.0) Math.max(3, -9)Math.sqrt(4.0) Math.max(3, -9)

See See class Math for others for others

Page 15: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Variables to store numbersVariables to store numbers

To declare and give initial value:To declare and give initial value:

type identifiertype identifier = = initial-valueinitial-value;;

ExamplesExamples 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;

Page 16: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

AssignmentAssignment

We change the values of variables with assignment We change the values of variables with assignment operations of this general formoperations of this general form

variable-namevariable-name == expressionexpression;; Examples:Examples: double x; double x; // Undefined variables// Undefined variables int j; int j; // can not be evaluated// can not be evaluated

j = 1; j = 1; x = j + 0.23;x = j + 0.23;

Page 17: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Memory before and afterMemory before and after

The primitive variables The primitive variables xx and and jj are undefined at first are undefined at first

Variable Variable Initial Initial AssignedAssigned NameName ValueValue ValueValue

jj ? ? 1 1

xx ? ? 1.23 1.23 The expression to the right of The expression to the right of == must be a value that must be a value that

the variable can store the variable can store assignment compatibleassignment compatible

x = "oooooh nooooo, you can't do that"; x = "oooooh nooooo, you can't do that"; // <-Error// <-Error j = x; j = x; // <-Error, can't assign a float to an int// <-Error, can't assign a float to an int

?? means undefined

Page 18: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Assignment Assignment

double bill;double bill;

What is value for What is value for billbill now? _________ now? _________ bill = 10.00;bill = 10.00; bill = bill + (0.06 * bill); bill = bill + (0.06 * bill);

What is value for bill now? ________What is value for bill now? ________

Which letters represent valid assignments given these 3 Which letters represent valid assignments given these 3 variable initializations?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;a) s = n; e) n = 1.0;b) n = x; f) x = 999;b) n = x; f) x = 999;c) x = n; g) s = "abc" + 1;c) x = n; g) s = "abc" + 1;d) s = 1; h) n = 1 + 1.5;d) s = 1; h) n = 1 + 1.5;

Page 19: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Arithmetic ExpressionsArithmetic Expressions

Arithmetic expressions consist of operators Arithmetic expressions consist of operators such assuch as + - / *+ - / * and operands such as and operands such as 4040, , 1.51.5,, payRatepayRate andand hoursWorkedhoursWorked

Example expression used in an assignment:Example expression used in an assignment: grossPay = payRate * hoursWorked;grossPay = payRate * hoursWorked;

Another example expression:Another example expression: 5 / 9 * (fahrenheit - 32);5 / 9 * (fahrenheit - 32);

For the previous expression, For the previous expression, Which are the operators?_____ Which are the operators?_____ Which are the operands?_____ Which are the operands?_____

Page 20: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Arithmetic ExpressionsArithmetic Expressions

a numeric variablea numeric variable double x = 1.2;double x = 1.2;or a numeric constantor a numeric constant 100 or 99.5100 or 99.5or expression + expression or expression + expression 1.0 + x1.0 + xor expression - expression or expression - expression 2.5 - x2.5 - xor expression * expressionor expression * expression 2 * x2 * xor expression / expressionor expression / expression x / 2.0x / 2.0or (expression ) or (expression ) (1 + 2.0)(1 + 2.0)

Arithmetic expressions take many forms

Page 21: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Precedence of Arithmetic OperatorsPrecedence of Arithmetic Operators

Expressions with more than one operator require Expressions with more than one operator require some sort of precedence rules:some sort of precedence rules:

* / * / evaluated in a left to right orderevaluated in a left to right order - +- + evaluated in a left to right order in the absence of parenthesesevaluated in a left to right order in the absence of parentheses EvaluateEvaluate 2.0 + 4.0 - 6.0 * 8.0 / 6.02.0 + 4.0 - 6.0 * 8.0 / 6.0

Use (parentheses) for readability or to intentionally Use (parentheses) for readability or to intentionally alter an expression: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 What is the current value of CC ____? ____?

Page 22: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Math functionsMath functions

Java’s Java’s MathMath class provides a collection of class provides a collection of mathematical and trigonometric functionsmathematical and trigonometric functionsMath.sqrt(16.0) Math.sqrt(16.0) returns returns 4.04.0

Math.min(-3, -9) Math.min(-3, -9) returns returns -0-0

Math.max(-3.0, -9.0) Math.max(-3.0, -9.0) returns returns -3.0-3.0

Math.abs(4 - 8) Math.abs(4 - 8) returns returns 44

Math.floor(1.9) Math.floor(1.9) returns returns 1.01.0

Math.pow(-2.0, 4.0) Math.pow(-2.0, 4.0) returns returns 16.016.0

Page 23: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

int Arithmeticint Arithmetic

intint variables are similar to variables are similar to doubledouble, except they can , except they can only store whole numbers (integers)only store whole numbers (integers)

int anInt = 0;int anInt = 0;

int another = 123;int another = 123;

int noCanDo = 1.99;int noCanDo = 1.99; // ERROR// ERROR

Division with integers is also differentDivision with integers is also different• Performs quotient remainder Performs quotient remainder whole numbers onlywhole numbers only

anInt = 9 / 2;anInt = 9 / 2; // anInt = 4, not 4.5// anInt = 4, not 4.5

anInt = anInt / 5;anInt = anInt / 5; What is What is anInt anInt now? ___now? ___

anInt = 5 / 2;anInt = 5 / 2; What is What is anInt anInt now? ___now? ___

Page 24: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

The integer % operationThe integer % operation

The Java % operator returns the remainderThe Java % operator returns the remainder

anInt = 9 % 2;anInt = 9 % 2; // anInt ___// anInt ___11___ ___

anInt = 101 % 2;anInt = 101 % 2; What is anInt now? ___ What is anInt now? ___

anInt = 5 % 11;anInt = 5 % 11; What is anInt now? ___ What is anInt now? ___

anInt = 361 % 60; anInt = 361 % 60; What is anInt now? ___ What is anInt now? ___

int quarter;int quarter;

quarter = 79 % 50 / 25; quarter = 79 % 50 / 25; What is quarter? ___What is quarter? ___

quarter = 57 % 50 / 25; quarter = 57 % 50 / 25; What is quarter now? ___What is quarter now? ___

Page 25: Java Fundamentals Asserting Java Chapter 2: Introduction to Computer Science ©Rick Mercer.

Integer Division, watch out …Integer Division, watch out …

What is the current value of What is the current value of celciuscelcius _____? _____?

int celcius, fahrenheit;

fahrenheit = 212; celcius = 5 / 9 * (fahrenheit - 32);