Download Download Presentation Primitive Types, Strings, and Console I/O

# Primitive Types, Strings, and Console I/O

Download Presentation ## Primitive Types, Strings, and Console I/O

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
##### Presentation Transcript

1. Objectives • become familiar with Java primitive types (numbers, characters, etc.) • learn about assignment statements and expressions • learn about strings • become familiar with classes, methods, and objects • learn about simple keyboard input and screen output

2. Outline • Primitive Types and Expressions • The Class String • Keyboard and Screen I/O • Documentation and Style

3. Variables and Values • Variables store data such as numbers and letters. • Think of them as places to store data. • They are implemented as memory locations. • The data stored by a variable is called its value. • The value is stored in the memory location. • Its value can be changed.

5. Naming and Declaring Variables • Choose names that are helpful such as count or speed, but not c or s. • When you declare a variable, you provide its name and type. int numberOfBaskets, eggsPerBasket; • A variable’s type determines what kinds of values it can hold (int, double, char,etc.). • A variable must be declared before it is used.

6. Syntax and Examples • syntax type variable_1, variable_2, …; • examples int styleChoice, numberOfChecks; double balance, interestRate; char jointOrIndividual;

7. Types in Java • A class type • a class of objects and has both data and methods. • “Think Whirled Peas”is a value of class type String • A primitive type • simple, nondecomposable values such as an individual number or individual character. • int, double, and char are primitive types.

8. Naming Conventions • Class types • begin with an uppercase letter (e.g. String). • Primitive types • begin with a lowercase letter (e.g. int). • Variables of both class and primitive types • begin with a lowercase letters (e.g. myName, myBalance). • Multiword names are “punctuated” using uppercase letters.

9. Where to Declare Variables • Declare a variable • just before it is used or • at the beginning of the section of your program that is enclosed in {}. public static void main(String[] args) { /* declare variables here */ … }

10. Java Identifiers • An identifier • a name, such as the name of a variable. • Identifiers may contain only • letters • digits (0 through 9) • the underscore character (_) • and the dollar sign symbol (\$) which has a special meaning • but the first character cannot be a digit.

11. Java Identifiers, cont. • identifiers may not contain any spaces, dots (.), asterisks (*), or other characters: 7-11 netscape.com util.*(not allowed) • Identifiers can be arbitrarily long. • Since Java is case sensitive, stuff, Stuff,andSTUFFare different identifiers.

12. Keywords or Reserved Words • Words such as if are called keywords or reserved words and have special, predefined meanings. • Keywords cannot be used as identifiers. • See Appendix 1 for a complete list of Java keywords. • other keywords: int, public, class • Appendix 1

13. Primitive Types • four integer types (byte, short, int, and long) • int is most common • two floating-point types (float and double) • double is more common • one character type (char) • one boolean type (boolean)

14. Primitive Types, cont.

15. Examples of Primitive Values • integer types 0 -1 365 12000 • floating-point types 0.99 -22.8 3.14159 5.0 • character type `a` `A` `#` ` ` • boolean type true false

16. Assignment Statements • An assignment statement is used to assign a value to a variable. answer = 42; • The “equal sign” is called the assignment operator. • We say, “The variable named answer is assigned a value of 42,” or more simply, “answer is assigned 42.”

17. Assignment Statements, cont. • Syntax variable = expression ; whereexpressioncan be • another variable, • a literal or constant (such as a number), • or something more complicated which combines variables and literals using operators (such as+and -)

18. Assignment Examples amount = 3.99; firstInitial = ‘W’; score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; (last line looks weird in mathematics, why?)

19. Assignment Evaluation • The expression on the right-hand side of the assignment operator (=) is evaluated first. • The result is used to set the value of the variable on the left-hand side of the assignment operator. score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2;

20. Specialized Assignment Operators • Assignment operators can be combined with arithmetic operators (including -, *,/, and %, discussed later). amount = amount + 5; can be written as amount += 5; yielding the same results.

21. Simple Screen Output System.out.println(“The count is “ + count); • outputs the Sting literal “The count is “ followed by the current value of the variable count. • + means concatenation if one argument is a string (an example of which of the three properties of OO languages?)

22. Simple Input • Sometimes the data needed for a computation are obtained from the user at run time. • Keyboard input requires import java.util.* at the beginning of the file.

23. Simple Input, cont. • Data can be entered from the keyboard using Scanner keyboard = new Scanner(System.in); followed, for example, by eggsPerBasket = keyboard.nextInt(); which reads oneintvalue from the keyboard and assigns it toeggsPerBasket.

24. Simple Input, cont. • class EggBasket2

25. Number Constants • Literal expressions such as 2, 3.7, or ’y’ are called constants. • Integer constants can be preceded by a + or - sign, but cannot contain commas. • Floating-point constants can be written • with digits after a decimal point or • using e notation.

26. e Notation • e notation is also called scientific notation or floating-point notation. • examples • 865000000.0 can be written as 8.65e8 • 0.000483can be written as4.83e-4 • The number in front of the e does not need to contain a decimal point, eg. 4e-4

27. Assignment Compatibilities • Java is said to be strongly typed. • You can’t, for example, assign a floating point value to a variable declared to store an integer. • Sometimes conversions between numbers are possible. doubleVariable = 7; doubleVariable = intVariable ; is possible even if doubleVariable is of type double, for example.

28. Assignment Compatibilities, cont. • A value of one type can be assigned to a variable of any type further to the right byte --> short --> int --> long --> float --> double but not to a variable of any type further to the left. • You can assign a value of type char to a variable of type int.

29. Type Casting • A type cast createsavalue in a new type from the original type. • For example, double distance; distance = 9.0; int points; points = (int)distance; (illegal without(int))

30. Type Casting, cont. • The value of (int)distanceis 9, but the value of distance, both before and after the cast, is 9.0. • The type of distance does NOT change and remains float. • Any nonzero value to the right of the decimal point is truncated, rather than rounded.

31. Characters as Integers • Characters are actually stored as integers according to a special code • each printable character (letter, number, punctuation mark, space, and tab) is assigned a different integer code • the codes are different for upper and lower case • for example 97 may be the integer value for ‘a’ and 65 for ‘A’ • ASCII and Unicode are common character codes

32. Unicode Character Set • Most programming languages use the ASCII character set. • Java uses the Unicode character set which includes the ASCII character set (Appendix 3) • The Unicode character set includes characters from many different alphabets other than English (but you probably won’t use them).

33. ASCII/Unicode

34. Casting acharto anint • Casting a char value to int produces the ASCII/Unicode value • For example, what would the following display? char answer = ’y’; System.out.println(answer); System.out.println((int)answer); • >y>121>

35. Initializing Variables • A variable that has been declared, but no yet given a value is said to be uninitialized. • Uninitialized class variables have the value null. • Uninitialized primitive variables may have a default value. • It’s good practice not to rely on a default value, which could be arbitrary.

36. Initializing Variables, cont. • To protect against an uninitialized variable (and to keep the compiler happy), assign a value at the time the variable is declared. • Examples: int count = 0; char grade = ’A’; // default is an A

37. Initializing Variables, cont. • syntax type variable_1 = expression_1, variable_2 = expression_2, …;

38. Binary Representation • Assume an 8-bit type • 5 as an integer • 00000101 • ‘5’ as a character • 00110101 (53 decimal, ASCII) • 5.0 as a floating point number • How? • What about 5.5?

39. Binary Real Numbers • 5.5 • 101.1 • 5.25 • 101.01 • 5.125 • 101.001 • 5.75 • 101.11

40. 8 bits only • 5.5 • 101.1 -> 000101 10 • 5.25 • 101.01 -> 000101 01 • 5.125 • 101.001 -> ?? • With only 2 places after the point, the precision is .25 • What if the point is allowed to move around?

41. Floating-point Numbers • Decimal • 54.3 • 5.43 x 101 [scientific notation] • Binary • 101.001 • 10.1001 x 21 [more correctly: 10.1001 x 101] • 1.01001 x 22 [more correctly: 1.01001 x 1010] • What can we say about the most significant bit?

42. Floating-point Numbers • General form: sign 1.mantissa x 2exponent • the most significant digit is right before the dot • Always 1 [no need to represent it] • (more details are not discussed here: mantissa has no sign, but sign is embedded in exponent…) • 1.01001 x 22 • Sign: positive (0) • Mantissa: 01001 • Exponent: 10 (decimal 2) • [IEEE standard: “biased exponent” • exponent + 2numBits-1 - 1 • Example: 2 + 22-1 – 1 = 3 => 11 in binary]

43. Java Floating-point Numbers • Sign: • 1 bit [0 is positive] • Mantissa: • 23 bits in float • 52 bits in double • Exponent: • 8 bits in float • 11 bits in double

44. Imprecision in Floating-Point Numbers • Floating-point numbers often are only approximations since they are stored with a finite number of bits. • Hence 1.0/3.0 is slightly less than 1/3. • 1.0/3.0 + 1.0/3.0 + 1.0/3.0 could be less than 1. • www.cs.fit.edu/~pkc/classes/cse1001/FloatEquality.java

45. Arithmetic Operations • Arithmetic expressions can be formed using the +, -, *, and /operators • together with variables or numbers referred to as operands. • When both operands are of the same type • the result is of that type. • When one of the operands is a floating-point type and the other is an integer • the result is a floating point type.

46. Arithmetic Operations, cont. • Example If hoursWorked is an int to which the value 40 has been assigned, and payRate is a double to which 8.25 has been assigned hoursWorked * payRate is a double with a value of 500.0.

47. Arithmetic Operations, cont. • Expressions with two or more operators can be viewed as a series of steps, each involving only two operands. • The result of one step produces one of the operands to be used in the next step. • example balance + (balance * rate)

48. Operators with integer and floating point numbers • if at least one of the operands is a floating-point type and the rest are integers • the result will be a floating point type. • The result is the rightmost type from the following list that occurs in the expression. byte --> short --> int --> long --> float --> double

49. The Division Operator • The division operator (/) behaves as expected • if one of the operands is a floating-point type. • When both operands are integer types • the result is truncated, not rounded. • Hence, 99/100 has a value of 0. • called integer division or integer divide
{"ft_lang_label":"__label__en","ft_lang_prob":0.819124,"math_prob":0.9653779,"size":11414,"snap":"2022-40-2023-06","text_gpt3_token_len":2742,"char_repetition_ratio":0.12778264,"word_repetition_ratio":0.030487806,"special_character_ratio":0.27028212,"punctuation_ratio":0.14068441,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9707795,"pos_list":[0,1,2,3,4,5,6,7,8],"im_url_duplicate_count":[null,null,null,null,null,1,null,null,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2023-01-28T06:32:51Z\",\"WARC-Record-ID\":\"<urn:uuid:e12585fe-3214-4f3e-8dcd-6130ca178763>\",\"Content-Length\":\"108037\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:ed717a8b-0b0c-479b-a98c-ebd6a94ebdf9>\",\"WARC-Concurrent-To\":\"<urn:uuid:e8f6a50b-72dc-44ae-867f-8f08d616a460>\",\"WARC-IP-Address\":\"44.233.25.47\",\"WARC-Target-URI\":\"https://www.slideserve.com/owen/primitive-types-strings-and-console-i\",\"WARC-Payload-Digest\":\"sha1:2W4JGWBKHKVTW36DMR2C66QP7XKQVXWY\",\"WARC-Block-Digest\":\"sha1:PARO5XKYXQNVLWTNRD6MM5Y5J4RCMNE3\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2023/CC-MAIN-2023-06/CC-MAIN-2023-06_segments_1674764499524.28_warc_CC-MAIN-20230128054815-20230128084815-00065.warc.gz\"}"}