Presentation is loading. Please wait.

Presentation is loading. Please wait.

©Silberschatz, Korth and Sudarshan1 Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and Screen I/O n.

Similar presentations


Presentation on theme: "©Silberschatz, Korth and Sudarshan1 Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and Screen I/O n."— Presentation transcript:

1 ©Silberschatz, Korth and Sudarshan1 Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and Screen I/O n Documentation and Style Reading => Section 1.2

2 ©Silberschatz, Korth and Sudarshan2 Variables and Values n Variables are memory locations that store data such as numbers and letters. n The data stored by a variable is called its value.  The value is stored in the memory location. n A variables value can be changed.

3 ©Silberschatz, Korth and Sudarshan3 Variables and Values public class EggBasket { public static void main (String[] args) { int baskets, eggsPer, totalEggs; baskets = 10; eggsPer = 6; totalEggs = baskets * eggsPer; System.out.println ("If you have"); System.out.print(eggsPer ); System.out.println(" eggs per basket and"); System.out.print(baskets); System.out.println(" baskets, then"); System.out.print("the total number of eggs is “); System.out.println(totalEggs); } Output: If you have 6 eggs per basket and 10 baskets, then the total number of eggs is 60

4 ©Silberschatz, Korth and Sudarshan4 Variables and Values public class EggBasket { public static void main (String[] args) { int baskets, eggsPer, totalEggs; baskets = 10; eggsPer = 6; totalEggs = baskets * eggsPer; System.out.println ("If you have"); System.out.println (eggsPer + " eggs per basket and"); System.out.println (baskets + " baskets, then"); System.out.println ("the total number of eggs is " + totalEggs); } Output: If you have 6 eggs per basket and 10 baskets, then the total number of eggs is 60

5 ©Silberschatz, Korth and Sudarshan5 Variables and Values Variables: baskets eggsPer totalEggs Assigning values: baskets = 10; eggsPer = 6; totalEggs = baskets * eggsPer; n A variable must be declared before it is used. n When you declare a variable, you provide its name and type. int baskets, eggsPer, totalEggs; A variable’s type determines what kinds of values it can hold, e.g., integers, real numbers, characters.

6 ©Silberschatz, Korth and Sudarshan6 Syntax and Examples n Variable declaration syntax: type variable_1, variable_2, … ; Examples: int styleChoice, numberOfChecks; double balance, interestRate; char jointOrIndividual; A variable is declared just before it is used or at the beginning of a “block” enclosed in { }: public static void main(String[] args) { /* declare variables here */ : }

7 ©Silberschatz, Korth and Sudarshan7 Types in Java n In most programming languages, a type implies several things:  A set of values  A (hardware) representation for those values  A set of operations on those values n Example - type int:  Values – integers in the range -2147483648 to 2147483647  Representation – 4 bytes, binary, “two’s complement”  Operations – addition (+), subtraction (-), multiplication (*), division (/), etc. n Two kinds of types:  Primitive types  Class types

8 ©Silberschatz, Korth and Sudarshan8 Types in Java n A primitive type:  values are “simple,” non-decomposable values such as an individual number or individual character  int, double, char n A class type:  values are “complex” objects  a class of objects has both data and methods  “ BIG bad John. ” is a value of class type String  ‘ November 10, 1989 ’ is a value of class type date (non-Java)

9 ©Silberschatz, Korth and Sudarshan9 Java Identifiers n An identifier is a name given to something in a program:  a variable, method, class, etc.  created by the programmer, generally n Identifiers may contain only:  letters  digits (0 through 9)  the underscore character (_)  and the dollar sign symbol ($) which has a special meaning  the first character cannot be a digit.

10 ©Silberschatz, Korth and Sudarshan10 Java Identifiers n Legal Examples: countnameaddress count1count2count3 xyz ijk myFavoriteHobbyMy_Favorite_Hobby n Illegal Examples: 1count_name 7-11netscape.comutil.*

11 ©Silberschatz, Korth and Sudarshan11 Java Identifiers, cont. Java is case sensitive i.e., stuff, Stuff, and STUFF are different identifiers. n Keywords or reserved words have special, predefined meanings: abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while n Keywords cannot be used as identifiers n Identifiers can be arbitrarily long.

12 ©Silberschatz, Korth and Sudarshan12 Naming Conventions A common recommendation is to choose names that are helpful, or rather readable, such as count or speed, but not c or s.  Sometimes short names are appropriate. n Class types:  begin with an uppercase letter (e.g. String ). n Primitive types:  begin with a lowercase letter (e.g. int ). n Variables of both class and primitive types:  begin with a lowercase letters (e.g. myName, myBalance ).  multiword names are “punctuated” using uppercase letters.

13 ©Silberschatz, Korth and Sudarshan13 Primitive Types n Four integer types:  byte  short  int (most common)  long n Two floating-point types:  float  double (most common) n One character type:  char n One boolean type:  boolean

14 ©Silberschatz, Korth and Sudarshan14 Primitive Types, cont.

15 ©Silberschatz, Korth and Sudarshan15 Examples of Primitive Values n Integer values: 0 -1 365 12000 n Floating-point values: 0.99 -22.8 3.14159 5.0 n Character values: `a` `A` `#` ` ` n Boolean values: true false

16 ©Silberschatz, Korth and Sudarshan16 Motivation for Primitive Types n Why are there several different integer types?  storage space  operator efficiency n More generally, why are there different types at all?  reflects how people understand different kinds of data, e.g., letter vs. numeric grades.  helps prevent programmer errors.

17 ©Silberschatz, Korth and Sudarshan17 Assignment Statements n An assignment statement is used to assign a value to a variable: int answer; answer = 42; The “equal sign” is called the assignment operator. In the above example, the variable named answer is assigned a value of 42, or more simply, answer is assigned 42.

18 ©Silberschatz, Korth and Sudarshan18 Assignment Statements, cont. n Assignment syntax: variable = expression ; where expression can be  a literal or constant (such as a number),  another variable, or  an expression which combines variables and literals using operators

19 ©Silberschatz, Korth and Sudarshan19 Assignment Examples n Examples: int amount; int score, numberOfCards, handicap; int eggsPerBasket; char firstInitial; : score = 3; firstInitial = ‘ W ’ ; amount = score; score = numberOfCards + handicap; eggsPerBasket = eggsPerBasket - 2; => Some note that the last line looks weird in mathematics. Why?

20 ©Silberschatz, Korth and Sudarshan20 Assignment Evaluation n The expression on the right-hand side of the assignment operator ( = ) is evaluated first. n 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;

21 ©Silberschatz, Korth and Sudarshan21 Simple Input n Sometimes data is needed and obtained from the user at run time. n Simple keyboard input requires: import java.util.*; or import java.util.Scanner; at the beginning of the file.

22 ©Silberschatz, Korth and Sudarshan22 Simple Input, cont. A “Scanner” object must be initialized before inputting data: Scanner keyboard = new Scanner(System.in); n To input data: eggsPerBasket = keyboard.nextInt(); which reads one int value from the keyboard and assigns it to the variable eggsPerBasket.

23 ©Silberschatz, Korth and Sudarshan23 Simple Input, cont. n class EggBasket2

24 ©Silberschatz, Korth and Sudarshan24 Command-Line Arguments Frequently input is provided to a program at the command-line. public class UseArgument { public static void main(String[] args) { System.out.print(“Hi, ”); System.out.print(args[0]); System.out.println(“. How are you?”); } Sample interaction: % javac UseArgument.java % java UseArgument Alice Hi, Alice. How are you? % java UseArgument Bob Hi, Bob. How are you?

25 ©Silberschatz, Korth and Sudarshan25 Command-Line Arguments Frequently multiple values are provided at the command-line. public class Use3Arguments { public static void main(String[] args) { System.out.print(“The first word is ”); System.out.print(args[0]); System.out.print(“, the second is ”); System.out.print(args[1]); System.out.print(“, and the third is ”); System.out.println(args[2]); } Sample interaction: % javac Use3Arguments.java % java Use3Arguments dog cat cow The first word is dog, the second is cat, and the third is cow

26 ©Silberschatz, Korth and Sudarshan26 Command-Line Arguments Command-line arguments can be numeric. public class IntOps { public static void main(String[] args) { int a = Integer.parseInt(args[0]);// Notice the variable declaration int b = Integer.parseInt(args[1]);// Notice the comments…lol int sum = a + b; int prod = a * b; int quot = a / b; int rem = a % b; System.out.println(a + " + " + b + " = " + sum); System.out.println(a + " * " + b + " = " + prod); System.out.println(a + " / " + b + " = " + quot); System.out.println(a + " % " + b + " = " + rem); } Sample interaction: % javac IntOps.java % java IntOps 1234 99 1234 + 99 = 1333 1234 * 99 = 122166 1234 / 99 = 12 1234 % 99 = 46

27 ©Silberschatz, Korth and Sudarshan27 Literals Values such as 2, 3.7, or ’ y ’ are called constants or literals. Integer literals can be preceded by a + or - sign, but cannot contain commas. n There are two distinct properties that every integer literal has:  format – either decimal, hexadecimal or octal, and  type – either long or int Both the format and the type of an integer literal can be determined by…looking at it!

28 ©Silberschatz, Korth and Sudarshan28 Integer Literal Formats n Decimal:  0, 10, 37, 643, -47, 829, etc.  first digit must NOT be zero, for any non-zero integer n Hexadecimal:  consists of the leading characters 0x or 0X followed by one or more hexadecimal digits, i.e., 0 through F (lower and upper case equivalent)  each letter may be either upper case or lower case  0xA (decimal 10), 0x0 (decimal 0), 0xFF (decimal 255), 0xf0 (decimal 240), 0x34A2, 0Xff decimal (255), etc. n Octal:  Consists of the leading digit 0 followed by one or more octal digits, i.e., 0 through 7  010 (decimal 8), 023 (decimal 19), 037 (decimal 31)

29 ©Silberschatz, Korth and Sudarshan29 Integer Literal Formats n What is the format?  0  2  0372  0xDadaCafe  1996  0x00FF00FF  0A3C  0945  450xA  0x5FGC3

30 ©Silberschatz, Korth and Sudarshan30 Integer Literal Formats The format used to specify an integer literal has no impact on its corresponding internal value. All of the following println statements output the same thing: int x; x = 16; System.out.println("Value:" + x); x = 020; System.out.println("Value:" + x); x = 0x10; System.out.println("Value:" + x);

31 ©Silberschatz, Korth and Sudarshan31 Integer Literal Type Now lets talk about the type of an integer literal… An integer literal is of type long if it is suffixed with an letter L or l; otherwise it is of type int.  note that capital L is preferred n Integer literals of type long:  2L0777L  0372L0x100000000l  0xDadaCafeL0xC0B0L  1996L2147483648L  0x00FF00FFL0l

32 ©Silberschatz, Korth and Sudarshan32 Integer Literal Type See the program:  http://www.cs.fit.edu/~pbernhar/teaching/cse1001/literals http://www.cs.fit.edu/~pbernhar/teaching/cse1001/literals

33 ©Silberschatz, Korth and Sudarshan33 Floating Point Literals n Just like with integer literals… Floating point literals can also be preceded by a + or - sign, but cannot contain commas. n There are two distinct properties that every floating point literal has:  format – either fully expanded notation or scientific notation  type – either float or double Both the format and the type of a floating point literal can be determined by…looking at it!

34 ©Silberschatz, Korth and Sudarshan34 Floating Point Literal Formats n Floating-point constants can be written:  with digits after a decimal point, as in 3.5 or  using scientific notation n Examples:  865000000.0 can be written as 8.65e8  0.000483 can be written as 4.83e-4 The number in front of the “e” does not need to contain a decimal point, e.g. 4e-4 n Floating point numbers can also be specified in hexidecimal, but we won’t go there…

35 ©Silberschatz, Korth and Sudarshan35 Floating Point Literal Type Now lets talk about the type of a floating point literal… An floating point literal is of type float if it is suffixed with an letter F or f; otherwise it is of type double. n Floating point literals of type float:  2.5F  0.0f  8.65e8f  4e-4 F  3f  +35.4f  -16F

36 ©Silberschatz, Korth and Sudarshan36 Assignment Compatibilities n Java is said to be strongly typed, which means that there are limitations on mixing variables and values in expressions and assignments. int x = 0; long y = 0; float z = 0.0f; x = y;// illegal x = z;// illegal y = z;// illegal z = 3.6;// illegal (3.6 is of type double) y = 25;// legal, but…why?

37 ©Silberschatz, Korth and Sudarshan37 Assignment Compatibilities n Sometimes automatic conversions between types do take place: short s; int x; s = 83; x = s; double doubleVariable; int intVariable; intVariable = 7; doubleVariable = intVariable;

38 ©Silberschatz, Korth and Sudarshan38 Assignment Compatibilities, cont. n In general, a value (or expression) of one numeric type can be assigned to a variable of any type further to the right, as follows: byte --> short --> int --> long --> float --> double but not to a variable of any type further to the left. Makes sense intuitively because, for example, any legal byte value is a legal short value. On the other hand, many legal short values are not legal byte values.

39 ©Silberschatz, Korth and Sudarshan39 Assignment Compatibilities, cont. Example – all of the following are legal, and will compile: byte b; short s; int i; long l; float f; double d; s = b; i = b; l = i; f = l;// This one is interesting, why? d = f; b = 10;

40 ©Silberschatz, Korth and Sudarshan40 Assignment Compatibilities, cont. Example – NONE (except the first) of the following will compile: byte b; short s; int i; long l; float f; double d; d = 1.0; f = d; l = f; i = l; s = i; b = s;

41 ©Silberschatz, Korth and Sudarshan41 Type Casting n A type cast creates a value in a new type from an original type. n A type cast can be used to force an assignment when otherwise it would be illegal (thereby over-riding the compiler, in a sense). n Example: double distance; distance = 9.0; int points; points = distance;// illegal points = (int)distance;// legal

42 ©Silberschatz, Korth and Sudarshan42 Type Casting, cont. The value of (int)distance is 9, but the value of distance, both before and after the cast, is 9.0. The type of distance does NOT change and remains double. What happens if distance contains 9.7?  Any value right of the decimal point is truncated (as oppossed to rounded). n Remember to “cast with care,” because the results can be unpredictable. int x; long z = ?; x = (int)z;

43 ©Silberschatz, Korth and Sudarshan43 Characters as Integers n Like everything else, each character is represented by a binary sequence. n The binary sequence corresponding to a character is a positive integer. n Which integer corresponds to each character is dictated by a standardized character encoding.  Each character is assigned a unique integer code  The codes are different for upper and lower case letters, e.g., 97 may be the integer value for ‘a’ and 65 for ‘A’  Some characters are printable, others are not n Why should different computers and languages use the same code? n ASCII and Unicode are the most common character codes.

44 ©Silberschatz, Korth and Sudarshan44 Unicode Character Set n Most programming languages use the ASCII character encoding.  American Standard Code for Information Interchange (ASCII)  (only) encodes characters from the north American keyboard  uses one byte of storage n Java uses the Unicode character encoding. n The Unicode character set:  uses two bytes of storage  includes many international character sets (in contrast to ASCII)  codes characters from the North American keyboard the same way that ASCII does Hey, lets google ASCII!!!!

45 ©Silberschatz, Korth and Sudarshan45 Assigning a char to an int A value of type char can be assigned to a variable of type int to obtain its Unicode value. n Example: char answer = ’y’; System.out.println(answer); System.out.println((int)answer); >y >121 n See the program at: http://www.cs.fit.edu/~pbernhar/teaching/cse1001/charTest

46 ©Silberschatz, Korth and Sudarshan46 Initializing Variables n A variable that has been declared, but not yet given a value is said to be uninitialized. int x, y, z; x = y; x = z + 1; n Some languages automatically initialize a variable when it’s declared, other languages don’t. n Others (Java) initialize in some circumstances, but not in others.  Variables declared to be of a primitive type are NOT automatically initialized.  In other cases Java will initialize variables; this will be discussed later.

47 ©Silberschatz, Korth and Sudarshan47 Initializing Variables n Some languages report an error when a variable is used prior to initialization by the program.  Sometimes at compile time, other times at run-time. n Some languages won’t report an error, and will even let you use an uninitialized variable.  In such cases the initial value of the variable is arbitrary!  The program might appear to run correctly sometimes, but give errors on others. n Java:  The compiler will (try) to catch uninitialized variables. => Always make sure your variables are initialized prior to use!

48 ©Silberschatz, Korth and Sudarshan48 Initializing Variables, cont. n In Java, a variable can be assigned an initial value in it’s declaration. n Examples: int count = 0; char grade = ’ A ’ ; // default is an A n Syntax: type variable1 = expression1, variable2 = expression2, … ;

49 ©Silberschatz, Korth and Sudarshan49 Arithmetic Operations n Arithmetic expressions:  Formed using the +, -, *, / and % operators  Operators have operands, which are literals, variables or sub-expressions. n 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 an operand which is used in the next step.  Java is left-associative.  Most of the basic rules of precedence apply. n Example: int x = 0, y = 50, z = 20; double balance = 50.25, rate = 0.05; x = x + y + z; balance = balance + (balance * rate)

50 ©Silberschatz, Korth and Sudarshan50 Expression Type n An arithmetic expression can have operands of different numeric types.  x + (y * z) / w  Note that this does not contradict our rules for assignment. n Every arithmetic expression has a (resulting) type.  k = x + (y * z) / w;// Does this compile? n Given an arithmetic expression:  If any operand in the expression is of type double, then the expression has type double.  Otherwise, if any operand in the expression is of type float, then the expression has type float.  Otherwise, if any operand in the expression is of type long, then the expression has type long.  Otherwise the expression has type int.

51 ©Silberschatz, Korth and Sudarshan51 Expression Type, cont. n Example: int hoursWorked = 40; double payRate = 8.25; double totalPay; Then the expression in the assignment: totalPay = hoursWorked * payRate is a double with a value of 500.0.

52 ©Silberschatz, Korth and Sudarshan52 Operators with integer and floating point numbers n See the program:  http://www.cs.fit.edu/~pbernhar/teaching/cse1001/expressions http://www.cs.fit.edu/~pbernhar/teaching/cse1001/expressions  http://www.cs.fit.edu/~pbernhar/teaching/cse1001/integralConversion http://www.cs.fit.edu/~pbernhar/teaching/cse1001/integralConversion

53 ©Silberschatz, Korth and Sudarshan53 The Division Operator The division operator ( / ) behaves as expected. n If one of the operands is a floating-point type then the result is of the same floating point type.  9.0 / 2 = 4.5  9 / 2.0 = 4.5 n If both operands are integer types then the result is truncated, not rounded.  9 / 2 = 4  99 / 100 = 0 n Note that the typing rules previously presented (slide 50) still apply!

54 ©Silberschatz, Korth and Sudarshan54 The mod Operator The mod ( % ) operator is used with operands of integer type to obtain the remainder after integer division. n 14 divided by 4 is 3 with a remainder of 2.  Hence, 14 % 4 is equal to 2. n The mod operator has many uses, including determining:  If an integer is odd or even ( x % 2 = 0 )  If one integer is evenly divisible by another integer ( a % b = 0 )  Frequently we want to map (a large number of) m “items,” number 1 through m, into n>=2 buckets.

55 ©Silberschatz, Korth and Sudarshan55 Example: Vending Machine n Program Requirements:  The user enters an amount between 1 cent and 99 cents.  The program determines a combination of coins equal to that amount.  For example, 55 cents can be two quarters and one nickel. => What are “requirements” anyway? n Sample dialog: Enter a whole number from 1 to 99. The machine will determine a combination of coins. 87 87 cents in coins: 3 quarters 1 dime 0 nickels 2 pennies

56 ©Silberschatz, Korth and Sudarshan56 Example, cont. n Algorithm (version #1, in pseudo-code): 1. Read the amount. 2. Find the maximum number of quarters in the amount. 3. Subtract the value of the quarters from the amount. 4. Repeat the last two steps for dimes, nickels, and pennies. 5. Print the amount and the quantities of each coin. n Program Variables Needed: int amount, quarters, dimes, nickels, pennies;

57 ©Silberschatz, Korth and Sudarshan57 Example, cont. n Interpreted literally, the algorithm leaves out one detail - the original amount is changed (and hence lost) by the intermediate steps. n So we add an additional variable: int amount, originalAmount, quarters, dimes, nickles, pennies; and update the algorithm.

58 ©Silberschatz, Korth and Sudarshan58 Example, cont. n Algorithm (version #2): 1. Read the amount. 2. Make a copy of the amount. 3. Find the maximum number of quarters in the amount. 4. Subtract the value of the quarters from the amount. 5. Repeat the last two steps for dimes, nickels, and pennies. 6. Print the original amount and the quantities of each coin. n Typically pseudo-code is iteratively embellished or enhanced.

59 ©Silberschatz, Korth and Sudarshan59 Example, cont. n How do we determine the number of quarters in an amount?  There are 2 quarters in 55 cents, but there are also 2 quarters in 65 cents.  That’s because 55 / 25 = 2 and 65 / 25 = 2. n How do we determine the remaining amount?  Using the mod operator: 55 % 25 = 5 and 65 % 25 = 15 n Similarly for dimes, nickels and pennies  Pennies are simply amount % 5.

60 ©Silberschatz, Korth and Sudarshan60 Example, cont.

61 ©Silberschatz, Korth and Sudarshan61 Testing the Program n The program should be tested with several different amounts. n Test with values that give zero values for each possible coin denomination. n Test with amounts close to:  “Extreme” or “boundary condition” values such as 0, 1, 98 and 99.  Coin denominations such as 24, 25, and 26.

62 ©Silberschatz, Korth and Sudarshan62 Increment (and Decrement) Operators n Used to increase (or decrease) the value of a variable by 1.  count = count +1  count = count -1 n The increment and decrement operations are easy to use, and important to recognize. n The increment operator:  count++  ++count n The decrement operator:  count--  --count

63 ©Silberschatz, Korth and Sudarshan63 Increment (and Decrement) Operators “Mostly” equivalent operations: count++; ++count; count = count + 1; count--; --count; count = count - 1; n Unlike the assignment versions, however, the increment and decrement operators are operators and have a resulting value…huh?

64 ©Silberschatz, Korth and Sudarshan64 Increment (and Decrement) Operators in Expressions n After executing: int m = 4; int result = 3 * (++m); result has a value of 15 and m has a value of 5 n After executing: int m = 4; int result = 3 * (m++); result has a value of 12 and m has a value of 5

65 ©Silberschatz, Korth and Sudarshan65 Increment and Decrement Operator, Cont. n Common code: int n = 3; int m = 4; int result; What will be the value of m and result after each of these executes? (a) result = n * ++m; (b) result = n * m++; (c) result = n * --m; (d) result = n * m--;

66 ©Silberschatz, Korth and Sudarshan66 Precedence Rules—Binary Operators n An expression (without parenthesis) is evaluated according to the (basic) rules of precedence:  Highest precedence – unary operators +, -, ++, -- and !  Intermediate precedence – binary arithmetic operators *, / and %  Lowest precedence – binary arithmetic operators + and - n Binary operators in Java are “left-associative:”  When binary operators have equal precedence the operator on the left has higher precedence than the operator(s) on the right. n Unary operators in Java are “right-associative:”  When unary operators have equal precedence the operator on the right has higher precedence  if x contains 10 -++x is -11 and x is 11 afterwards; same as – (++x) -x++ is -10 and x is 11 afterwards; same as – (x++)

67 ©Silberschatz, Korth and Sudarshan67 Use Parentheses n Parentheses can be used to over-ride the rules of precedence: (cost + tax) * discount n Parenthesis can also be used to clarify code, even when precedence is not over-ridden: balance + (interestRate * balance) n Spaces also clarify code: balance + interestRate*balance but spaces do not dictate precedence.

68 ©Silberschatz, Korth and Sudarshan68 Sample Expressions

69 ©Silberschatz, Korth and Sudarshan69 The Class String As we already have seen, a String is a sequence of characters. We’ve used constants, or rather, literals of type String : “Enter a whole number from 1 to 99.” “Number of quarters:” “I will output a combination of coins”

70 ©Silberschatz, Korth and Sudarshan70 Declaring and Printing Strings n Variables of type String can be declared and Initialized: String greeting; greeting = “ Hello! ” ; n Equivalent to the above: String greeting = “ Hello! ” ; String greeting = new String( “ Hello! ” ); n Printing: System.out.println(greeting);

71 ©Silberschatz, Korth and Sudarshan71 Inputting Strings n Variables of type String can be input: String Word; System.out.print(“Enter a word:”); Word = keyboard.next(); System.out.print(“The word entered was: “ + Word);

72 ©Silberschatz, Korth and Sudarshan72 Concatenation of Strings Two strings can be concatenated using the + operator: String greeting = “Hello”; String name = “Smith”; String sentence; sentence = greeting + “ officer ”; sentence = sentence + name; System.out.println(sentence); Any number of strings can be concatenated using the + operator.

73 ©Silberschatz, Korth and Sudarshan73 Concatenating Strings and Integers n Strings can be concatenated with other types: String solution; solution = “The temperature is “ + 72; System.out.println (solution); Output: The temperature is 72

74 ©Silberschatz, Korth and Sudarshan74 Classes n Recall that Java has primitive types and class types:  primitive types  class types n Primitive types have:  simple, “atomic,” non-decomposable values  Operations (built-in) n Class types have:  complex values, with structure  Methods (some built-in, others user-defined)

75 ©Silberschatz, Korth and Sudarshan75 Objects, Methods, and Data n A primitive type is use to create variables. n A class type is used to produce “objects.” n An object is an entity that:  stores data  can take actions defined by methods  basically a complex variable. n The data and methods applicable to an object are defined by its class.

76 ©Silberschatz, Korth and Sudarshan76 The Class String String is a class type The length() method returns an int, which is the number of characters in a particular String object. String solution = “dog”; int howMany = solution.length(); You can use a call to method length() anywhere an int can be used. int X = 10; int count = solution.length(); System.out.println(solution.length()); X = X * solution.length() + 3;

77 ©Silberschatz, Korth and Sudarshan77 Positions in a String n Each character in a String has its own position. n Positions are numbered starting at 0.  ‘ J ’ in “ Java is fun. ” is in position 0  ‘ f ’ in “ Java is fun. ” is in position 8 n The position of a character is also referred to as its index.

78 ©Silberschatz, Korth and Sudarshan78 Positions in a String, cont.

79 ©Silberschatz, Korth and Sudarshan79 Indexing Characters within a String using Methods n charAt(position)  returns the char at the specified position Example: String greeting = "Hi, there!"; char ch1 = greeting.charAt(0); // Stores ‘H’ in ch1 char ch2 = greeting.charAt(2); // Stores ‘,’ in ch2 n substring(start, end)  returns the string from start up to, but not including, end String myWord; myWord = greeting.substring(4,7) // Stores the in myWord

80 ©Silberschatz, Korth and Sudarshan80 Example of Class String

81 ©Silberschatz, Korth and Sudarshan81 String Methods n See the Java on-line documentation for more details!

82 ©Silberschatz, Korth and Sudarshan82 Escape Characters n How would you print the following? “Java” refers to a language. n The following don’t work: System.out.println(“Java refers to a language.”); System.out.println(““Java” refers to a language.”); The compiler needs to be told that the quotation marks ( “ ) do not signal the start or end of a string, but instead are to be printed. System.out.println(“\”Java\” refers to a language.”);

83 ©Silberschatz, Korth and Sudarshan83 Escape Characters n “Escape sequences” are used to print “problematic” characters. n Each escape sequence is a single character even though it is written with two symbols.

84 ©Silberschatz, Korth and Sudarshan84 Examples n Examples: System.out.println( “ abc\\def ” );=>abc\def System.out.println( “ new\nline ” );=>new line char singleQuote = ‘ \ ’’ ; System.out.println(singleQuote); => ‘

85 ©Silberschatz, Korth and Sudarshan85 Number Constants DecimalBinaryOctalHexidecimal 0000000000 0000 0000 0001000001 0001 0001 0002000010 0002 0002 0003000011 0003 0003 0004000100 0004 0004 0005000101 0005 0005 0006000110 0006 0006 0007000111 0007 0007 0008001000 0010 0008 0009001001 0011 0009 0010001010 0012 000A 0011001011 0013 000B 0012001100 0014 000C 0013001101 0015 000D 0014001110 0016 000E 0015 001111 0017 000F 0016 010000 0020 0010 0017 010001 0021 0011 0018 010010 0022 0012 0019 010011 0023 0013 0020 010100 0024 0014 0021 010101 0025 0015 0022 010110 0026 0016 0023 010111 0027 0017 0024 011000 0030 0018 0025 011001 0031 0019 0026 011010 0032 001A 0027 011011 0033 001B 0028 011100 0034 001C 0029 011101 0035 001D 0030 011110 0036 001E 0031 011111 0037 001F 0032 100000 0040 0020


Download ppt "©Silberschatz, Korth and Sudarshan1 Primitive Types, Strings, and Console I/O n Variables and Expressions The Class String n Keyboard and Screen I/O n."

Similar presentations


Ads by Google