Presentation is loading. Please wait.

Presentation is loading. Please wait.

1001ICT Programming 1 Semester 1, 2011 Lecture 8 Course Review 1.

Similar presentations


Presentation on theme: "1001ICT Programming 1 Semester 1, 2011 Lecture 8 Course Review 1."— Presentation transcript:

1 1001ICT Programming 1 Semester 1, 2011 Lecture 8 Course Review 1

2 2 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

3 Java Primitive Data Types There are eight primitive data types in Java Four of them represent integers byte, short, int, long Two of them represent floating point numbers float, double One of them represents characters char And one of them represents boolean values boolean 1-3

4 Java Primitive Data Types - Numeric The difference between the various numeric primitive types is their size, and therefore the values they can store: Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value ,768 -2,147,483,648 < -9 x /- 3.4 x with 7 significant digits +/- 1.7 x with 15 significant digits Max Value ,767 2,147,483,647 > 9 x

5 Java Primitive Data Types - char A char variable stores a single character Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Example declarations char topGrade = 'A'; char terminator = ';', separator = ' '; Note the distinction between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters 1-5

6 Java Primitive Data Types - boolean A boolean value represents a true or false condition The reserved words true and false are the only valid values for a boolean type boolean done = false; A boolean variable can also be used to represent any two states, such as a light bulb being on or off 1-6

7 7 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

8 Java Extended Data Types - String A string of characters can be represented as a string literal by putting double quotes around the text Examples "This is a string literal." "123 Main Street" "X" Every character string is an object in Java, defined by the String class Every string literal represents a String object 1-8

9 Java Extended Data Types - String The string concatenation operator ( + ) is used to append one string to the end of another "Peanut butter " + "and jelly" It can also be used to append a number to a string A string literal cannot be broken across two lines in a program 1-9

10 Java Extended Data Types - String The + operator is also used for arithmetic addition The function that it performs depends on the type of the information on which it operates If both operands are strings, or if one is a string and one is a number, it performs string concatenation If both operands are numeric, it adds them The + operator is evaluated left to right, but parentheses can be used to force the order 1-10

11 1-11 Java Extended Data Types - String Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; This is special syntax that works only for strings Each string literal (enclosed in double quotes) represents a String object

12 1-12 Java Extended Data Types - String It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The indexes begin at zero in each string In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4

13 1-13 Java Extended Data Types - String Once a String object has been created, neither its value nor its length can be changed Thus we say that an object of the String class is immutable However, several methods of the String class return new String objects that are modified versions of the original

14 Java Extended Data Types - String Some Java String methods 1-14 MethodUse char charAt(int index) s.charAt(3); boolean equals (String str) s.equals(abcd); int length() s.length(); String trim() s.trim(); String substring(int offset, int endIndex) s.substring(2,10); String replace(char oldChar, char newChar) s.replace(a, x); String toLowerCase() s.toLowerCase();

15 Java Extended Data Types - String What if we wanted to print a the quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character ( \ ) System.out.println ("I said \"Hello\" to you."); 1-15

16 Java Extended Data Types - String Some Java escape sequences Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash 1-16

17 Java Extended Data Types - Arrays An array is an ordered list of values An array of size N is indexed from zero to N-1 scores The entire array has a single name Each value has a numeric index This array holds 10 values that are indexed from 0 to

18 18 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

19 Java Variables A variable is a name for a location in memory A variable must be declared by specifying the variable's name and the type of information that it will hold int total; int count, temp, result; Multiple variables can be created in one declaration data type variable name 1-19

20 Java Variables A variable can be given an initial value in the declaration When a variable is referenced in a program, its current value is used int sum = 0; int base = 32, max = 149; 1-20

21 Java Variables - final A constant is an identifier that is similar to a variable except that it holds the same value during its entire existence As the name implies, it is constant, not variable The compiler will issue an error if you try to change the value of a constant In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; 1-21

22 Java Variables - final Constants are useful for three important reasons First, they give meaning to otherwise unclear literal values For example, MAX_LOAD means more than the literal 250 Second, they facilitate program maintenance If a constant is used in multiple places, its value need only be updated in one place Third, they formally establish that a value should not change, avoiding inadvertent errors by other programmers 1-22

23 23 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

24 Java Arithmetic Expressions An expression is a combination of one or more operators and operands Arithmetic expressions compute numeric results and make use of the arithmetic operators If either or both operands used by an arithmetic operator are floating point, then the result is a floating point Addition Subtraction Multiplication Division Remainder +-*/%+-*/% 1-24

25 Java Arithmetic Expressions - / and % If both operands to the division operator ( / ) are integers, the result is an integer (the fractional part is discarded) The remainder operator ( % ) returns the remainder after dividing the second operand into the first 14 / 3 equals 8 / 12 equals % 3 equals 8 % 12 equals

26 Java Arithmetic Expressions - Operator Precedence Operators can be combined into complex expressions result = total + count / max - offset; Operators have a well-defined precedence which determines the order in which they are evaluated Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation Arithmetic operators with the same precedence are evaluated from left to right, but parentheses can be used to force the evaluation order 1-26

27 Java Arithmetic Expressions - Operator Precedence What is the order of evaluation in the following expressions? a + b + c + d + e 1432 a + b * c - d / e 3241 a / (b + c) - d % e 2341 a / (b * (c + (d - e)))

28 28 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

29 Java Boolean Expressions A condition often uses one of Java's equality operators or relational operators, which all return boolean results == equal to != not equal to < less than > greater than <= less than or equal to >= greater than or equal to Note the difference between the equality operator ( == ) and the assignment operator ( = ) 1-29

30 Java Boolean Expressions Boolean expressions can also use the following logical operators ! Logical NOT && Logical AND || Logical OR They all take boolean operands and produce boolean results Logical NOT is a unary operator (it operates on one operand) Logical AND and logical OR are binary operators (each operates on two operands) 1-30

31 Java Boolean Expressions The logical NOT operation is also called logical negation or logical complement If some boolean condition a is true, then !a is false; if a is false, then !a is true Logical expressions can be shown using a truth table a!a truefalse true 1-31

32 Java Boolean Expressions The logical AND expression a && b is true if both a and b are true, and false otherwise The logical OR expression a || b is true if a or b or both are true, and false otherwise 1-32

33 Java Boolean Expressions Expressions that use logical operators can form complex conditions 1-33 if (total < MAX+5 && !found) System.out.println ("Processing…"); All logical operators have lower precedence than the relational operators Logical NOT has higher precedence than logical AND and logical OR

34 Java Boolean Expressions A truth table shows all possible true-false combinations of the terms Since && and || each have two operands, there are four possible combinations of conditions a and b aba && ba || b true false true falsetruefalsetrue false 1-34

35 Java Boolean Expressions Specific expressions can be evaluated using truth tables total < MAXfound!foundtotal < MAX && !found false truefalse truefalse truefalsetrue false 1-35

36 Java Boolean Expressions The processing of logical AND and logical OR is short-circuited If the left operand is sufficient to determine the result, the right operand is not evaluated This type of processing must be used carefully if (count != 0 && total/count > MAX) System.out.println ("Testing…"); 1-36

37 37 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

38 Java Assignment An assignment statement changes the value of a variable The assignment operator is the = sign total = 55; The expression on the right is evaluated and the result is stored in the variable on the left The value that was in total is overwritten You can only assign a value to a variable that is consistent with the variable's declared type 1-38

39 Java Assignment The assignment operator has a lower precedence than the arithmetic operators First the expression on the right hand side of the = operator is evaluated Then the result is stored in the variable on the left hand side answer = sum / 4 + MAX * lowest;

40 Java Assignment The right and left hand sides of an assignment statement can contain the same variable First, one is added to the original value of count Then the result is stored back into count (overwriting the original value) count = count + 1; 1-40

41 Java Assignment - Operators Often we perform an operation on a variable, and then store the result back into that variable Java provides assignment operators to simplify that process For example, the statement num += count; is equivalent to num = num + count; 1-41

42 Java Assignment - Operators There are many assignment operators in Java, including the following 1-42 Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y

43 Java Assignment - Operators The right hand side of an assignment operator can be a complex expression The entire right-hand expression is evaluated first, then the result is combined with the original variable Therefore result /= (total-MIN) % num; is equivalent to result = result / ((total-MIN) % num); 1-43

44 Java Assignment - Operators The behavior of some assignment operators depends on the types of the operands If the operands to the += operator are strings, the assignment operator performs string concatenation The behavior of an assignment operator ( += ) is always consistent with the behavior of the corresponding operator ( + ) 1-44

45 Java Assignment - Increment and Decrement The increment and decrement operators use only one operand The increment operator ( ++ ) adds one to its operand The decrement operator ( -- ) subtracts one from its operand The statement count++; is functionally equivalent to count = count + 1; 1-45

46 Java Assignment - Increment and Decrement The increment and decrement operators can be applied in postfix form count++ or prefix form ++count When used as part of a larger expression, the two forms can have different effects Because of their subtleties, the increment and decrement operators should be used with care 1-46

47 47 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

48 Java Data Conversion Sometimes it is convenient to convert data from one type to another For example, in a particular situation we may want to treat an integer as a floating point value These conversions do not change the type of a variable or the value that's stored in it – they only convert a value as part of a computation 1-48

49 Java Data Conversion Conversions must be handled carefully to avoid losing information Widening conversions are safest because they tend to go from a small data type to a larger one (such as a short to an int ) Narrowing conversions can lose information because they tend to go from a large data type to a smaller one. In Java, data conversions can occur in three ways assignment conversion promotion casting 1-49

50 Java Data Conversion Assignment conversion occurs when a value of one type is assigned to a variable of another If money is a float variable and dollars is an int variable, the following assignment converts the value in dollars to a float money = dollars Only widening conversions can happen via assignment Note that the value or type of dollars did not change 1-50

51 Java Data Conversion Promotion happens automatically when operators in expressions convert their operands For example, if sum is a float and count is an int, the value of count is converted to a floating point value to perform the following calculation result = sum / count; 1-51

52 Java Data Conversion Casting is the most powerful, and dangerous, technique for conversion Both widening and narrowing conversions can be accomplished by explicitly casting a value To cast, the type is put in parentheses in front of the value being converted For example, if total and count are integers, but we want a floating point result when dividing them, we can cast total result = (float) total / count; 1-52

53 53 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

54 Java Input / Output The Scanner class provides convenient methods for reading input values of various types A Scanner object can be set up to read input from various sources, including the user typing values on the keyboard Keyboard input is represented by the System.in object 1-54

55 Java Input / Output The following line creates a Scanner object that reads from the keyboard Scanner scan = new Scanner (System.in); The new operator creates the Scanner object Once created, the Scanner object can be used to invoke various input methods, such as answer = scan.nextLine(); 1-55

56 Java Input / Output The Scanner class is part of the java.util class library, and must be imported into a program to be used The nextLine method reads all of the input until the end of the line is found 1-56

57 Java Input / Output Unless specified otherwise, white space is used to separate the elements (called tokens) of the input White space includes space characters, tabs, new line characters The next method of the Scanner class reads the next input token and returns it as a string Methods such as nextInt and nextDouble read data of particular types 1-57

58 Java Input / Output The System.out object represents a destination (the monitor screen) to which we can send output System.out.println ("Whatever you are, be a good one."); object method name information provided to the method (parameters) 1-58

59 Java Input / Output The System.out object provides another service as well The print method is similar to the println method, except that it does not advance to the next line Therefore anything printed after a print statement will appear on the same line 1-59

60 60 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

61 Java Flow of Control Unless specified otherwise, the order of statement execution through a method is linear: one statement after another in sequence Some programming statements allow us to decide whether or not to execute a particular statement execute a statement over and over, repetitively These decisions are based on boolean expressions (or conditions) that evaluate to true or false The order of statement execution is called the flow of control 1-61

62 Java Flow of Control A conditional statement lets us choose which statement will be executed next Therefore they are sometimes called selection statements Conditional statements give us the power to make basic decisions The Java conditional statements are the if statement if-else statement switch statement 1-62

63 Java Flow of Control - if The if statement has the following syntax 1-63 if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed. If it is false, the statement is skipped.

64 Java Flow of Control - if An example of an if statement: if (sum > MAX) delta = sum - MAX; System.out.println ("The sum is " + sum); First the condition is evaluated -- the value of sum is either greater than the value of MAX, or it is not If the condition is true, the assignment statement is executed -- if it isnt, it is skipped. Either way, the call to println is executed next 1-64

65 Java Flow of Control - if condition evaluated statement true false 1-65

66 Java Flow of Control - if What do the following statements do? if (top >= MAXIMUM) top = 0; Sets top to zero if the current value of top is greater than or equal to the value of MAXIMUM if (total != stock + warehouse) inventoryError = true; Sets a flag to true if the value of total is not equal to the sum of stock and warehouse The precedence of the arithmetic operators is higher than the precedence of the equality and relational operators 1-66

67 Java Flow of Control – if-else An else clause can be added to an if statement to make an if-else statement 1-67 if ( condition ) statement1; else statement2; If the condition is true, statement1 is executed; if the condition is false, statement2 is executed One or the other will be executed, but not both

68 Java Flow of Control – if-else condition evaluated statement1 true false statement2 1-68

69 Java Flow of Control – block statements Several statements can be grouped together into a block statement delimited by braces A block statement can be used wherever a statement is called for in the Java syntax rules 1-69 if (total > MAX) { System.out.println ("Error!!"); errorCount++; }

70 Java Flow of Control – block statements In an if-else statement, the if portion, or the else portion, or both, could be block statements 1-70 if (total > MAX) { System.out.println ("Error!!"); errorCount++; } else { System.out.println ("Total: " + total); current = total*2; }

71 Java Flow of Control – nested if The statement executed as a result of an if statement or else clause could be another if statement These are called nested if statements An else clause is matched to the last unmatched if (no matter what the indentation implies) Braces can be used to specify the if statement to which an else clause belongs 1-71

72 Java Flow of Control – switch The switch statement provides another way to decide which statement to execute next The switch statement evaluates an expression, then attempts to match the result to one of several possible cases Each case contains a value and a list of statements The flow of control transfers to statement associated with the first case value that matches 1-72

73 Java Flow of Control – switch The general syntax of a switch statement is switch ( expression ) { case value1 : statement-list1 case value2 : statement-list2 case value3 : statement-list3 case... } switch and case are reserved words If expression matches value2, control jumps to here

74 Java Flow of Control – switch Often a break statement is used as the last statement in each case's statement list A break statement causes control to transfer to the end of the switch statement If a break statement is not used, the flow of control will continue into the next case Sometimes this may be appropriate, but often we want to execute only the statements associated with one case

75 Java Flow of Control – switch An example of a switch statement switch (option) { case 'A': aCount++; break; case 'B': bCount++; break; case 'C': cCount++; break; }

76 Java Flow of Control – switch A switch statement can have an optional default case The default case has no associated value and simply uses the reserved word default If the default case is present, control will transfer to it if no other case value matches If there is no default case, and no other value matches, control falls through to the statement after the switch

77 Java Flow of Control – switch The expression of a switch statement must result in an integral type, meaning an integer ( byte, short, int, long ) or a char It cannot be a boolean value or a floating point value ( float or double ) The implicit boolean condition in a switch statement is equality You cannot perform relational checks with a switch statement

78 Java Flow of Control – Repetition Statements Repetition statements allow us to execute a statement multiple times Often they are referred to as loops Like conditional statements, they are controlled by boolean expressions Java has three kinds of repetition statements: the while loop the do loop the for loop The programmer should choose the right kind of loop for the situation 1-78

79 Java Flow of Control – while A while statement has the following syntax 1-79 while ( condition ) statement; If the condition is true, the statement is executed Then the condition is evaluated again, and if it is still true, the statement is executed again The statement is executed repeatedly until the condition becomes false

80 Java Flow of Control – while statement true false condition evaluated 1-80

81 Java Flow of Control – while The body of a while loop eventually must make the condition false If not, it is called an infinite loop, which will execute until the user interrupts the program This is a common logical error You should always double check the logic of a program to ensure that your loops will terminate normally 1-81

82 Java Flow of Control – Nested Loops Similar to nested if statements, loops can be nested as well That is, the body of a loop can contain another loop For each iteration of the outer loop, the inner loop iterates completely 1-82

83 Java Flow of Control – do A do statement has the following syntax do { statement; } while ( condition ) The statement is executed once initially, and then the condition is evaluated The statement is executed repeatedly until the condition becomes false 1-83

84 Java Flow of Control – do true condition evaluated statement false 1-84

85 Java Flow of Control – while and do statement true false condition evaluated The while Loop true condition evaluated statement false The do Loop 1-85

86 Java Flow of Control – for A for statement has the following syntax for ( initialization ; condition ; increment ) statement; The initialization is executed once before the loop begins The statement is executed until the condition becomes false The increment portion is executed at the end of each iteration 1-86

87 Java Flow of Control – for statement true condition evaluated false increment initialization 1-87

88 Java Flow of Control – for A for loop is functionally equivalent to the following while loop structure initialization; while ( condition ) { statement; increment; } 1-88

89 Java Flow of Control – for Each expression in the header of a for loop is optional If the initialization is left out, no initialization is performed If the condition is left out, it is always considered to be true, and therefore creates an infinite loop If the increment is left out, no increment operation is performed 1-89

90 90 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

91 Java Arrays A particular value in an array is referenced using the array name followed by the index in brackets For example, the expression scores[2] refers to the value 94 (the 3rd value in the array) That expression represents a place to store a single integer and can be used wherever an integer variable can be used 1-91

92 Java Arrays For example, an array element can be assigned a value, printed, or used in a calculation scores[2] = 89; scores[first] = scores[first] + 2; mean = (scores[0] + scores[1])/2; System.out.println ("Top = " + scores[5]); 1-92

93 Java Arrays The values held in an array are called array elements An array stores multiple values of the same type – the element type The element type can be a primitive type or an object reference Therefore, we can create an array of integers, an array of characters, an array of String objects, an array of Coin objects, etc. In Java, the array itself is an object that must be instantiated 1-93

94 Java Arrays Another way to depict the scores array scores

95 Java Arrays The scores array could be declared as follows int[] scores = new int[10]; The type of the variable scores is int[] (an array of integers) Note that the array type does not specify its size, but each object of that type has a specific size The reference variable scores is set to a new array object that can hold 10 integers 1-95

96 Java Arrays Some other examples of array declarations float[] prices = new float[500]; boolean[] flags; flags = new boolean[20]; char[] codes = new char[1750]; 1-96

97 Java Arrays Once an array is created, it has a fixed size An index used in an array reference must specify a valid element That is, the index value must be in range 0 to N-1 The Java interpreter throws an ArrayIndexOutOfBoundsException if an array index is out of bounds This is called automatic bounds checking 1-97

98 Java Arrays For example, if the array codes can hold 100 values, it can be indexed using only the numbers 0 to 99 If the value of count is 100, then the following reference will cause an exception to be thrown System.out.println (codes[count]); Its common to introduce off-by-one errors when using arrays for (int index=0; index <= 100; index++) codes[index] = index*50 + epsilon; problem 1-98

99 Java Arrays Each array object has a public constant called length that stores the size of the array It is referenced using the array name scores.length Note that length holds the number of elements, not the largest index 1-99

100 Java Arrays The brackets of the array type can be associated with the element type or with the name of the array Therefore the following two declarations are equivalent float[] prices; float prices[]; The first format generally is more readable and should be used 1-100

101 Java Arrays An initializer list can be used to instantiate and fill an array in one step The values are delimited by braces and separated by commas Examples int[] units = {147, 323, 89, 933, 540, 269, 97, 114, 298, 476}; char[] letterGrades = {'A', 'B', 'C', 'D', F'}; 1-101

102 Java Arrays Note that when an initializer list is used the new operator is not used no size value is specified The size of the array is determined by the number of items in the initializer list An initializer list can be used only in the array declaration 1-102

103 Java Arrays An entire array can be passed as a parameter to a method Like any other object, the reference to the array is passed, making the formal and actual parameters aliases of each other Therefore, changing an array element within the method changes the original An individual array element can be passed to a method as well, in which case the type of the formal parameter is the same as the element type 1-103

104 Java Arrays A one-dimensional array stores a list of elements A two-dimensional array can be thought of as a table of elements, with rows and columns one dimension two dimensions 1-104

105 Java Arrays To be precise, in Java a two-dimensional array is an array of arrays A two-dimensional array is declared by specifying the size of each dimension separately int[][] scores = new int[12][50]; A array element is referenced using two index values value = scores[3][6] The array stored in one row can be specified using one index 1-105

106 Java Arrays ExpressionTypeDescription tableint[][] 2D array of integers, or array of integer arrays table[5]int[] array of integers table[5][12]int integer 1-106

107 Java Arrays An array can have many dimensions – if it has more than one dimension, it is called a multidimensional array Each dimension subdivides the previous one into the specified number of elements Each dimension has its own length constant Because each dimension is an array of array references, the arrays within one dimension can be of different lengths these are sometimes called ragged arrays 1-107

108 108 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

109 Java Methods Lets now examine method declarations in more detail A method declaration specifies the code that will be executed when the method is invoked (called) When a method is invoked, the flow of control jumps to the method and executes its code When complete, the flow returns to the place where the method was called and continues The invocation may or may not return a value, depending on how the method is defined 1-109

110 myMethod(); myMethodcompute Java Methods If the called method is in the same class, only the method name is needed 1-110

111 Java Methods We will only use static methods A method declaration begins with a method header static char calc (int num1, int num2, String msg) method name return type parameter list The parameter list specifies the type and name of each parameter The name of a parameter in the method declaration is called a formal parameter 1-111

112 Java Methods The method header is followed by the method body static char calc (int num1, int num2, String msg) { int sum = num1 + num2; char result = msg.charAt (sum); return result; } The return expression must be consistent with the return type sum and result are local data They are created each time the method is called, and are destroyed when it finishes executing 1-112

113 Java Methods - return The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type 1-113

114 Java Methods – Parameters When a method is called, the actual parameters in the invocation are copied into the formal parameters in the method header char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } ch = obj.calc (25, count, "Hello"); 1-114

115 Java Methods – Local Data As weve seen, local variables can be declared inside a method The formal parameters of a method create automatic local variables when the method is invoked When the method finishes, all local variables are destroyed (including the formal parameters) 1-115

116 116 Java Review Topics Primitive Data Types Extended Data Types Variables Arithmetic Expressions Boolean Expressions Assignment Data Conversion Input / Output Flow of Control Arrays (revisited) Methods Class Libraries

117 1-117 Java Class Libraries A class library is a collection of classes that we can use when developing programs The Java standard class library is part of any Java development environment Its classes are not part of the Java language per se, but we rely on them heavily Various classes we've already used ( System, Scanner, String ) are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create them yourself

118 1-118 Java Class Libraries The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are Package java.lang java.applet java.awt javax.swing java.net java.util javax.xml.parsers Purpose General support Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities Network communication Utilities XML document processing

119 1-119 Java Class Libraries When you want to use a class from a package, you could use its fully qualified name java.util.Scanner Or you can import the class, and then use just the class name import java.util.Scanner; To import all classes in a particular package, you can use the * wildcard character import java.util.*;

120 1-120 Java Class Libraries All classes of the java.lang package are imported automatically into all programs It's as if all programs contain the following line import java.lang.*; That's why we didn't have to import the System or String classes explicitly in earlier programs The Scanner class, on the other hand, is part of the java.util package, and therefore must be imported


Download ppt "1001ICT Programming 1 Semester 1, 2011 Lecture 8 Course Review 1."

Similar presentations


Ads by Google