Presentation is loading. Please wait.

Presentation is loading. Please wait.

Chapter 2 Basic Computation

Similar presentations


Presentation on theme: "Chapter 2 Basic Computation"— Presentation transcript:

1 Chapter 2 Basic Computation
© Bobby Hoggard, Department of Computer Science, East Carolina University / These slides may not be used or duplicated without permission

2 Screen Output System.out =
In Java the screen is represented by the object: System.out The screen object contains the following methods for displaying output: println() – prints what is inside the parentheses, with a line break at the end print() – prints what is inside the parentheses, with no line break Java Program Physical Hardware System.out =

3 Screen Output Source code Program output
System.out.println("Hello"); System.out.println("World"); Hello World Hello World Line-Break Line-Break System.out.println("Hello"); System.out.println("World"); Note: Number of lines of source code have no relationship to the number of lines of output!

4 Screen Output Source code Program output
System.out.println("Hello"); System.out.println("World"); Hello World Line-Break Line-Break Hello World \n System.out.println("Hello\nWorld"); \n Note: The "\n" character in Java represents the "Enter" key

5 Screen Output Source code Program output
Hello World System.out.println("Hello"); System.out.println("World"); \n \n Adds line break at the end of the line System.out.print("Hello\n"); System.out.print("World\n"); but, WE have added line breaks in our output Does NOT add line break at the end of the line Note: The "\n" character in Java represents the "Enter" key

6 Screen Output Source code Program output Hello \n
World System.out.println("Hello"); System.out.println("World"); \n \n System.out.print("Hello\n"); System.out.print("World\n"); System.out.print("Hello\n"); System.out.println("World"); System.out.println("Hello\nWorld");

7 Screen Output Source code Program output
System.out.print("Hello"); System.out.println("World"); HelloWorld \n Does NOT add line break at the end of the line System.out.print("Hello"); Does NOT add line break at the end of the line Note: Number of lines of source code have no relationship to the number of lines of output!

8 Screen Output Source code Program output Add space here
System.out.print("Hello"); System.out.println("World"); HelloWorld \n Add space here System.out.print("Hello "); System.out.println("World"); Hello World \n System.out.print("Hello"); System.out.println(" World"); or add space here Note: Number of lines of source code have no relationship to the number of lines of output!

9 Variables Memory locations that a program can use to store data
Variables must be declared before they can be used – variable declaration To declare a variable, the programmer must: Choose a name to represent the memory location – variable name State the type of data that will be stored in the variable – data type After declaration, to use the variable, you only need to type it's name – not it's data type You cannot re-declare a variable, or change it's data type later

10 Variable Declaration Examples
data type variable name int n1; int n1; ... double n1; int n1; ... int n1; ... System.out.print(int n1); Variable Redeclaration States that n1 should hold integers, but later states it should hold something else Variable Redeclaration States that n1 should hold integers, but later tries to declare n1 again Variable Redeclaration Just use the variable name; no need to try to specify it's data type again

11 Assignment Statements
Assignment Operator Assignment statements use the assignment operator to store a value into a variable It works by taking the "stuff" on the right side of the operator, and places it into the variable on the left side of the operator ; Variable Stuff to store in variable Note: A single variable name ALWAYS appears on the left side of an assignment operator

12 What Can You Store? x 1 1 x 1 3 y x 3 3 LITERALS
int x; LITERALS (simple, unchanging values) x 1 1 x = 1; CALCULATED ANSWERS x calculate: 1+2 answer is 3 1 3 x = 1 + 2; VALUE FROM ANOTHER VARIABLE y x int y; y = x; 3 3 retrieve value from x store into y

13 What Can You Store? x 3 4 x 4 39 retrieve value of x value of x is 3
int x = 3; Scanner kbd = new Scanner(System.in); CALCULATIONS INVOLVING VARIABLES retrieve value of x value of x is 3 calculate 3 + 1 answer is 4 store 4 back into x x 3 4 x = x + 1; VALUES RETRIEVED FROM A METHOD retrieve value from keyboard assume user enters 39 x 4 39 x = kbd.nextInt(); Note: Assume the keyboard has been properly declared and initialized in all future examples!

14 What Can't You Do? Use an undeclared variable anywhere in your program
int x; Use an undeclared variable anywhere in your program z = 1; Error: z cannot be resolved to a variable Declare all variables before attempting to use them int z; z = 1; Use an uninitialized variable int z; x = z + 2; Error: The local variable z may not have been initialized A variable must have a value before you attempt to READ it's value int z = 3; x = z + 2;

15 Printing Variable Values
Source code Program output int x = 5; System.out.println("x"); x System.out.println(x); 5 System.out.print("x = "); System.out.println(x); x = 5 System.out.println("x = " + x); x = 5 Note: Literal data inside double quotes (") is called a String

16 print/println ONLY prints Strings
expression HOW TO "Calculate" int x = 5; System.out.println("x = " + x); retrieve the value of x System.out.println("x = " + 5); convert int 5 to a String System.out.println("x = " + "5"); Strings must be concatenated System.out.println("x = 5"); print String to the screen: x = 5 Note: Concatenate means to join together

17 "+" for Addition int int add
System.out.println(1 + 2); int int add System.out.println(1 + 2); calculate 1 + 2 System.out.println(3); int 3 must be converted to String System.out.println("3"); Print String to the screen: 3 Note: + performs addition if there is a number on both sides of the operator

18 "+" for Concatenation String String concatenation
System.out.println("1" + "2"); String String concatenation System.out.println("1" + "2"); concatenate the Strings System.out.println("12"); Print String to the screen: 12 Note: + performs concatenation if there is a String involved

19 "+" With Mixed Types System.out.println( " is the answer"); Prints: 3 is the answer System.out.println( " is the answer"); + is applied left to right System.out.println((1 + 2) + " is the answer"); add 1 + 2 System.out.println(3 + " is the answer"); convert int 3 to String System.out.println("3" + " is the answer"); concatenate the Strings System.out.println("3 is the answer "); Print String to the screen: 3 is the answer Note: + performs addition ONLY if there is a number on both sides of the operator

20 What Does This Print? System.out.println("The answer is " + 1 + 2);
Prints: The answer is 12 System.out.println("The answer is " ); + is applied left to right System.out.println(("The answer is " + 1) + 2); convert int 1 to String System.out.println(("The answer is " + "1") + 2); concatenate the Strings System.out.println("The answer is 1" + 2); convert int 2 to String System.out.println("The answer is 1" + "2"); concatenate the Strings System.out.println("The answer is 12"); Print String to the screen: The answer is 12

21 Variable Names Note: Variable names SHOULD start with a lowercase letter Programmers are free to choose whatever names they like for their variables The only rules for variable naming are as follows: NO KEYWORDS Variable names cannot be the same as a Java defined keyword int class; int cLass; START WITH A LETTER OR UNDERSCORE Variable names must start with an alphabetic letter or the underscore (_) int 3pay; int pay3; USE ONLY LETTERS, NUMBERS, OR UNDERSCORES After the 1st character, variable names can only contain letters, numbers and underscore (_) characters int pay rate; int pay_rate; int payRate;

22 Primitive Data Types byte short int long float double char boolean
CHARACTERS REAL WHOLE TRUE / FALSE NUMERIC TYPES Note: Primitives hold a single value / Objects CAN hold multiple values

23 Whole Number Data Types
Space Required For Storage Range * int 4 bytes - 2,147,483,648 to +2,147,483,647 short 2 bytes - 32,768 to +32,767 byte 1 byte - 128 to +127 - 9,223,372,036,854,775,808 to long 8 bytes +9,223,372,036,854,775,808 Note: Whole numbers are stored in 2's compliment notation * int is the default whole number data type

24 Real Number Data Types ± 1.79769313486231570 x 10 to * double 8 bytes
Space Required For Storage Range x 10 +308 to * double 8 bytes x 10 - 324 x 10 +38 to float 4 bytes x 10 - 45 Note: These variable values are stored in floating point notation * double is the default real number data type

25 Other Data Types char 2 bytes Unicode values from 0 to 65,535 boolean
Space Required For Storage Range char 2 bytes Unicode values from 0 to 65,535 boolean 1 byte The values: false or true

26 Data Type Literals Single character (char) literals are surrounded by single quotes ( ' ) Multiple character ( String ) literals are surrounded by double quotes ( " ) Numbers are not surrounded by any special characters char letter = 'A'; char letter = "A"; String name1 = 'Andy'; String name2 = 'A'; String name = "Andy"; int num1 = "39"; int num2 = '39'; int num = 39;

27 Test Your Knowledge Source code Program output int x = 5;
System.out.println( x ); 5 System.out.println( "x" ); x System.out.println( 'x' ); x x = 1 + 2; System.out.println( x ); 3 x = "1 + 2"; Type mismatch: cannot convert from String to int System.out.println( '1' + '2' ); 99

28 Why Not Concatenation? char 2 bytes Unicode values from 0 to 65,535
System.out.println( '1' + '2' ); 99 char char Note: + performs concatenation if there is a String involved char 2 bytes Unicode values from 0 to 65,535 Note: char values are actually stored in memory as numbers (a Unicode value)

29 Type Compatibilities Is 1 equivalent to "1" ? Is 1 equivalent to '1' ?
Strings are objects ints are primitives int String Although, both are primitives, and both are numbers, the character '1' is not stored in memory as the number 1 Is equivalent to '1' ? int char The Unicode value for the character '1' is the number 49 Is equivalent to '1' ?

30 asciitable.com The ASCII table is a smaller subset of the larger Unicode table (and easier to read for our purposes)

31 '1' is equivalent to the number 49
System.out.println( '1' + '2' ); substitute values System.out.println( ); add System.out.println( 99 ); convert to String System.out.println( "99" ); Prints: 99

32 We have already established that '1' + '2' equals the number 99
System.out.println( '1' + '2' ); Prints: 99 char ch = '1' + '2'; System.out.println( ch ); Prints: c We have already established that '1' + '2' equals the number 99 The number 99 is equivalent to the character 'c'

33 char ch = '1' + '2'; System.out.println( ch ); int num = '1' + '2'; System.out.println( num ); Prints: c Prints: 99 ch and num are both holding the same value in memory (which is 99) BUT… character, you expect to see a character If you ask Java to print a integer, you expect to see an integer If you ask Java to print an

34 Thinking Outside the Box!
Example: Print the string "ABCD" to the screen Obvious answer Not so obvious answer System.out.println( "ABCD" ); char ch = 'A'; System.out.print( ch ); ch = ch + 1; System.out.print( ch ); ch = ch + 1; System.out.print( ch ); ch = ch + 1; System.out.println( ch );

35 char ch = 'A'; System.out.print( ch ); ch = ch + 1; System.out.println( ch ); store 65 into ch print 'A' ch = ; print 'B' ch = ; print 'C' ch = ; print 'D'; ch = 65 ch = 66 ch = 67 ch = 68 Prints: ABCD \n

36 Review of Data Types Is 5 equivalent to 5.0 ? int 5
Primitive: 2's compliment 8.6 double Primitive: Floating point 'x' Primitive: Unicode char String "x" Object (containing multiple Unicode chars) Is equivalent to ? 2's compliment Floating point

37 Automatic Type Conversion
Java will automatically convert from a small data type to a larger data type byte short int long float double Automatic Conversion No Automatic Conversion

38 Automatic Type Conversion
double x; x = ; double x; x = 5.0; double x; x = 5; Auto type convert: double = int Type match: double = double Type match: double = double double 5.0 int 5 x = 5.0;

39 When Auto Type Conversion Doesn't Work
int y; y = 5; int y; y = 5.0; Type match: int = int Type Mismatch: int = double int 5 double 5.0 Note: Auto conversion does not work when going from a large type to a smaller type

40 (desiredType) valueToConvert
Type Casting Type casting allows us to change primitive data type into another primitive type Syntax: (desiredType) valueToConvert int y; y = (int)5.0; int 5 double 5.0

41 double-to-int Type Casting
When converting from floating point data types to whole number data types, the decimal places are simply truncated – NOT rounded. int y; y = 5.1; int y; y = (int)5.1; int y; y = (int)5.9; Type Mismatch: int = double Type match: int = ( int  double ) Type match: int = ( int  double ) y y 5 5

42 Type Compatibilities Source code Program output
int x = 'B'; char y = 65; System.out.println( x ); 66 System.out.println( y ); A y = 'A'; System.out.println( y ); A System.out.println( (int)y ); 65 System.out.println( (char)x ); B

43 Java Math Operators + - * / % num + num a * b a . b
* / % add subtract multiply divide modulus num + num returns the remainder from a division a * b concatenate a . b String + num num + String String + String a ( b )

44 Java Math & Data Types 2 + 3 = 5 2 + 3.1 = 5.1
Math involving two of the same data type, produces an answer with the same data type = int int int Math involving mixed data types, produces an answer which is the larger of the two data types = int double double Automatic Conversion byte short int long float double

45 Java Math & Data Types 7 / 3 = 2.333 7 / 3 = 2
Math involving two of the same data type, produces an answer with the same data type / = int int double / = int int int

46 Java Math & Data Types 7 / 3 = 2 7 / 3.0 = 2.333
Math involving two of the same data type, produces an answer with the same data type / = int int int Math involving mixed data types, produces an answer which is the larger of the two data types / = int double double

47 Java Math & Data Types 7 / 3.0 = 2.333 7.0 / 3 = 2.333
/ = / = / =

48 Java Math & Data Types 7 / 3 = 2 7 3 2 r1 6 1 7 % 3 = 1
The "/" operator produces the quotient from long division / = 7 3 2 r1 6 1 The "%" operator produces the remainder from long division % =

49 amount of money to change
Division Example We need to give change for $0.13. We only have nickels and pennies available. How many nickels and how many pennies do we give? / = 2.6 2.6 nickels ?? pennies amount of money to change value of nickel Do integer division, and get the quotient and remainder 13 / = 2 2 nickels 13 % = 3 3 pennies

50 Test Your Knowledge What value will be stored in x? x = 2.0 1 2 3 4
int a = 7; int b = 3; double x; x = a / b; double = int / int 2 x = 2; double = int x = 2.0 3 x = (double)2; double = double 4 x = 2.0; double = double

51 Produce a double with Type Casting
x = a / 3.0; x = 2.333 int a = 7; int b = 3; double x; double = int / double x = a / b; x = 2.0 double = int / double x = a / (double)b; x = 2.333 double = int / double x = (double)a / b; x = 2.333 double = double / int

52 Test Your Knowledge What value will be stored in x? x = 2.0
int a = 7; int b = 3; double x; x = (double)(a / b); x = (double)(a / b); manual type casting double = (double)(int/int) x = / 3; x = 2.0 automatic type casting double = int / int

53 Operators & Commands Operators – produce a mathematical value that can be used in a larger equation Commands – cause some type of change in the program (usually change a variable's value) x = ; command operator store 3 into x add 1 and 2 to produce 3 but also an operator produces the same value stored in the variable

54 Operator Examples int x, y; x = 3 + ( y = 7 ) + 1; Precedence: () + =
11; the 11 is discarded

55 ERROR: y is uninitialized
Operator Examples int x, y; x = y = ; Precedence: () + = ERROR: y is uninitialized Compiler error: program will not compile

56 Operator Examples int x = 1; x = 2 + x + (x = 5) + 1; x = 5
13 the 13 is discarded

57 Operator Examples int x, y, z; x = 7; y = 7; z = 7; x = y = z = 7;

58 Increment/Decrement Operators/Commands
Used to change a variable's value by adding 1, or subtracting one, from a variable. int x = 1; Increment Decrement x++; Postfix x--; ++x; Prefix --x;

59 Prefix vs. Postfix The difference is WHEN the increment takes place
int x = 1; Postfix Prefix x++; ++x; perform calculations with OLD value Get value of x Add one to x Add one to x Get value of x perform calculations with NEW value

60 Operator Examples int x, y; x = 5; y = 2 + ++x; x = 6 y = 2 + x++;

61 Operator Examples int x, y; x = 5; y = 2 + x++ + 1 + x; x = 6
Postfix: use OLD value, then increment y = x; y = x; y = ; Remember: x changed values on line 1 y = 14;

62 Shortcut Operators Perform a math operation AND change a variable's value SHORTCUT OPERATOR EQUIVALENT OPERATION x += 7; x = x + 7; x -= 2; x = x - 2; x *= 3; x = x * 3; x /= 5; x = x / 5; x %= 4; x = x % 4;

63 Shortcut Operator Examples
DESIRED EQUATION EQUIVALENT OPERATION x = x + (y * 3); x += (y * 3); x += y * 3; x = x x; x += ++x;

64 Equivalent Examples GOAL: Add 1 to x x = x + 1; x++; ++x; x += 1;


Download ppt "Chapter 2 Basic Computation"

Similar presentations


Ads by Google