Programming Final Exam Summary (Algonquin College) PDF

Summary

This document summarizes the final exam for Introduction to Computer Programming at Algonquin College. It covers fundamental concepts like data types, scope, and conversions. It's a useful study guide for students.

Full Transcript

lOMoARcPSD|47808042 Document 1 - summary for the final exam Introduction to Computer Programming (Algonquin College) Scan to open on Studocu Studocu is not sponsored or endorsed by any college or university Downloaded by Sadek Ayoub (sadekayou...

lOMoARcPSD|47808042 Document 1 - summary for the final exam Introduction to Computer Programming (Algonquin College) Scan to open on Studocu Studocu is not sponsored or endorsed by any college or university Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 PROGRAMMING FINAL EXAM STUDIES Module 7 DATA TYPES Java data types it can be classified as primitive types or reference types (using reference/id values) It stores the value directly into the memory PRIMITIVE TYPES Primitive types always begin with a lowercase character Each primitive type is characterized by four features: Size – Range – precision – format Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 Boolean the boolean type has only two possible values: true and false (both keywords as well). So you can set e.g. boolean loop = true; or boolean loop = false; char Each char is stored in a two-byte value. Internally, a char is just a number (as is every data type). But when a variable is declared as a char, Java knows that it must treat that value (a number between 0 to 65,535) as a character to be displayed; You cannot assign a character value to a String (or a String to a character for that matter). Thus the following are legal: String s = "A"; // Strings use double quotes, " " char c = 'A'; // chars use single quotes, ' ' If we add +1 to the maximum value of int or long, it will round up to the negative number System.out.println(“Add 1 to the maximum value ” + intger.MAX.VALUE + 1); But if we do the same thing to byte or short it will change to an integer (int) By default, whenever you assign an integral value to a variable, it is assumed the number is an int by default, rather than a long, byte, or short. If you want to load a large ‘long-size’ number into a variable declared as long, you must append ‘L’ or ‘l’ (lowercase L) to the number, i.e. long populationOfEarth = 80847249266L; float, double These two data types store decimal values, those holding decimal and exponential Components Just as there is a BigInteger class to handle super-large integers, there is a BigDecimal class to handle decimal/exponential values of almost any size SCOPE Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 Where a variable is declared affects its scope, if a variable is declared inside the class, it will be class-level scope. if a variable is declared inside the main method it will only be visible inside the method and it call local scope note: if you change the modifier for the variable it wil effect who can see/ use it but it will not change the scope level block-level scope, which is the third kind of scope after local- and class- level scope , introduced in Module 7. A variable declared inside of an if, else, switch or any of the looping structures seen in the next module, is limited to that block only. always the calculation must be performed on RHS and then assigned to the LHS currentEggs = brokenEgg – totalEggs; shortform operations += | -= | /= | *= | %= PREFIX & POSTFIX The ++ before the variable is known as the prefix operator—it ‘fixes’ the value by adding 1 to the variable. There is also a postfix operator PREFIX EXAMPLE ++Loopctr //it’s mean loopctr + 1 POSTFIX EXAMPLE Loopctr++ //it’s mean loopctr + 1 differently Also we can decrement using preficx and postfix --loopctr, loopctr— Widening conversion Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 Converting from small data type to a larger data type known as widening conversion Example Long value = 99947; // the value is int it converted to long float value = 844343; // this value is int converted to float data type In each case the smaller-sized value on the RHS is implicitly converted to the larger data type declared on the LHS. Such implicit type conversions happen automatically, without the programmer’s intervention Implicit type conversions also occur during math operations. When two values of different type are used, the result of the expression is automatically converted up to the wider of the two types. For example, assume CAST Is changing the data type of a value float result = (float)numerator/denominator; //Example Note that it is impossible to cast a number to a Boolean We can call it Narrowing conversion or downcast Using final to Define Constants To create a constant value—one which cannot be altered in code once set—use the keyword final. For example: final float ABSOLUTE_ZERO = -273.15; // in degrees Celsius final int VOTING_AGE = 18; final int GOLD = 1, SILVER = 2, BRONZE = 3; Declaring constants in code, rather than using their values directly, is good practice since it avoids the use of magic numbers. A magic number is any value that is context-dependent, perhaps known only to the programmer. Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 MODULE 8 Logic Operators Java allows logical operations—AND, OR, XOR and NOT—to be performed on boolean data types. XOR: if two inputs are the same the result is false. The! Is a unary operator: it takes one argument, the value to the right of the!. Most of the operators you encounter, including previous logic operators and the math operators in the last module, are binary operators; that is, they require two arguments (like 1 + 2, or x > y) SHORT CIRCUITED The AND and OR operations may be short- circuited, that is, the second input does not need to be evaluated if the first corresponds to the boolean value indicated in the table on the preceding page Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 here is a distinct (and easily confused) difference between ‘=‘ and ‘==‘: = is the assignment operator. It says: take the variable on the LHS of the ‘=‘ and set it to the value returned on the RHS == is a comparison operator. This says: check to see if the LHS and RHS are equal, and if so, return true, otherwise false The result of any comparison operation is always a boolean value, i.e. true or false, never a number PRESEDENCE & ASSOCIATIVITY What will happen if we have a mixture of math operations and logic operations which one will get executed first Here comes the precedence when something have higher precedence from another thing means it will excuted first Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 For example, multiplication, division, and modulus operators (*, /, and %) have precedence over addition and subtraction, and are read left-to-right—from left of the expression to its right. ORDER OF PRECEDENCE thus associativity determines which symbols are associated with which values. Unary operators such as the unary negation (‘-’) always have right-to-left associativity. That is, the value to the right of the symbol—moving from it (2) to the left (-)—is associated first. So precedence is about the order of execution; associativity is about the relationship between the operators used in an expression Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 Different between PREFIX & POSTFIX is simple word postfix increment/decrement the value only after the process, on the hand prefix increment/decrement before the process Associativity is about grouping; precedence is about priority of execution A quick summary of the rules of precedence would include the following: 1. Operations in parentheses are associated together before all other operations Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 2. Unary operations take precedence over binary operations 3. Multiplication, division, and modulus take precedence over addition and subtraction, operating from left-to-right 4. Next, comparison operations take precedence over logic operators 5. The RHS result is assigned to the LHS variable; this has the lowest precedence, and is always the last operation performed. (Short-form operations are included here as well.) In prefix operations, the operation (++ or --) is performed first, then the value stored is returned for use in the current expression. In postfix operations, this order is reversed; the value is used first, and any addition/subtraction is performed afterward. MODULE 9 IF STATEMENT Both decision and looping structures rely on a boolean expression to determine the direction of program flow. The diamond symbol is used, as shown below. Note: the diamond structure should always have one input, two outputs* the logic expression is clearly indicated in the diamond the outputs are labelled as true/false, yes/no, etc. regardless of which branch is chosen, all routes must eventually terminate at an ‘stop’ or ‘return’ oval any of the vertices of the diamond may be used for input or output, e.g. The if statement is the simplest form of a decision structure. It says that, if a condition is true, one branch of code is taken, otherwise another branch Else if statement A variant of the if statement has an else statement attached. This is used when either the true or false branch must be chosen; there is no default choice for the branch not selected. SWITCH…CASE STATEMENT The switch...case structure can sometimes be used as an alternative to a series of nested if...else if statements. It has the form: switch (someIntegralVariable){ Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 case num1: // execute these statements if someIntegralVariable==num1 break; case num2: // execute these statements if someIntegralVariable==num2 break;... // etc., for multiple case statements default: // Do this if none of the other cases apply // i.e. catch anything not already covered. // This is the equivalent of the final ‘else’ // statement in a series of ‘if...else if’s } The Tinary if (?:) Statement Because the if...else structure is so commonly used, Java (and most C-based languages) contain a powerful, short-cut version known as the conditional if (also called the ternary if). The format is as follows result = booleanExpression ? truePart : falsePart same as: if (booleanExpression) result = truePart; else result = falsePart; Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 MODULE 10 REPUTATION STRUCTURE / LOOPS In a looping or repetition structure, a logical expression determines if code execution returns to a previous statement or not. The same code is executed until a condition is encountered that terminates the loop There are three requirements for any loop: 1. A loop control variable, or just LCV, is a value that is used to determine whether to continue the loop or not; this must be initialized before the loop is entered; 2. A condition (a statement or set of statements) that controls the actual loop. This determines where execution jumps to during each iteration of the code. 3. A condition that determines when the loop exits. This typically involves altering the LCV so that, when the loop’s decision structure is tested, execution falls outside the loop. An infinite loop occurs when the final condition is not met We have two types of loops definite & indefinite Indefinite definite While loop For loop Do…while loop hasNextInt() is a Scanner method that waits for input and checks to see if the input received is the correct data type Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 THE WHILE LOOP The while loop is the simplest form of loop. The looping condition is tested initially, at the start of the loop, and execution continues until the escape condition is met. THE DO..WHILE LOOP This loop makes sure that it will execute at least once without looking at the condition NOTES: The contents of the do...while loop are always executed once; the while loop may not be executed at all if its loop control condition is not met initially. This means the while loop’s condition will need to be defined before the loop is entered; the do’s can be set inside the loop and checked at the end of the loop; The while loop’s code is entirely contained in the {...}, without a ‘;’ at the end. The do...while statement terminates with a ‘;’ following the looping condition; As with decision structures, the parentheses may be omitted if only a single statement is present inside the loop As with decision structures, variables declared inside the loop have block scope; their visibility does not extend outside the loop itself THE FOR LOOP used when the number of iterations through the loop is known beforehand the for loop typically declares / sets, compares, and modifies (increments or decrements) its loop control variable (lcv) at the start of the loop. All three operations are in the ( )’s following the keyword for, separated by two ‘;’s. Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 In the for loop, even though the lcv is created inside the ( ) (and thus before the {... }’s), it is treated as having block scope, exactly as if it was declared inside the braces The above code hints at another curious feature of the for loop. All the internal operations of the for loop may be omitted except the keyword for, the parentheses, and the two ‘;’s. The following will not flag an error: for (;;){...} // an infinite loop 2. You can omit the first and third operations in the parentheses, but when you omit the second (conditional) statement, you have an infinite loop, and so you must use break (or return) somewhere in the code to escape from the loop. Another common mistake: you might forget to make the comparison, and write e.g. n = 1 when what you meant was n == 1; 3. Scope matters. Where a variable is declared affects its visibility, and therefore its utility in that part of the program; 4. All loops are interchangeable. A do...while loop can be turned into a while, and a while into a for. What determines which loop is most appropriate is: a) do you know the number of loops ahead of time? b) do you need to execute code before entering the loop? Possible Pitfalls using Loop Structures Avoid putÝng declarations inside a loop. If a loop is going to be done a million times, each time you re-declare a value, it costs execution time. When testing, always check the boundary conditions. That is, if a loop goes from 3 to 17, you need to test the values 3 and 17 to ensure the code does what it is supposed to do at those limits of the loop; Do not forget to use { } when there is more than one statement inside the loop. Use of labelled break and continue should be avoided at all costs Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 MODULE 11 ARRAYS An array is a construct that holds a sequential set of variables of the same datatype. Each element of an array can be accessed by a number known as its index To declare an array of primitive data types you’d write, e.g. int[] monthSize = new int; where the LHS indicates this is an array of int data type, and the RHS instantiates an array having (in this case) a size of 12 ints, storing the reference value to that array in the monthSize variable. You can populate the array at compile time using the { } notation: int[] monthSize = {31,28,31,30,31,30,31,31,30,31,30,31}; This list of values on the right is referred to as the initializer list. To summarize, arrays have the following features: An array is a list of identical data types loaded in contiguous (i.e. sequential) memory; Each data item in an array is called an element, and it is accessible via an index (or subscript), which must be an int value (or byte or short, as long as it can be resolved to an int); The usable range of indices are between 0 to one less than the number of elements in the array; Each element in the array can be accessed by e.g. arrayName[index]; Array elements may be set at the time the array is declared using the {item1, item2,...} notation. The value of an array element can also be set (or reset) using e.g. arrayName[index] =...; This use of separate, parallel arrays should be avoided. It presumes that both arrays have the same number of elements, and therefore the data in each array will be synchronized: int[] monthSize = {31, isLeapYr(yr)?29:28, 31, 30, 31, 30, 31, 30, 31, 30, 31}; String[] monthNames = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"}; Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 STACK & HEAP Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 Using an array index that is outside of the array bounds will result in an ArrayOutOfBoundsException. A good way to prevent this is to use ‘ < array.length’ in your for loop; The size of the array is set when the array is instantiated, it cannot be changed afterward. However, you can create a new array of the desired size, and copy the contents of the original array over. But this is computationally costly; Java array declarations have the curious feature that the [] can be applied before the array identifier or after. Thus to declare an array of Strings you can declare an array as either String[] arrayName OR String arrayName[] Note that this technically means that main() can be declared as public static void main (String args[]){...} As with all uninitialized object declarations in an instantiated class, uninitialized arrays are set to null by default. If the array object is loaded but uninitialized, primitive types are set to 0, 0.0, and false as before, and object references inside the array are set to null. Downloaded by Sadek Ayoub ([email protected]) lOMoARcPSD|47808042 As we’ve seen, it is possible to return reference values to arrays, thereby allowing their contents to be modified—an often-unwanted side effect of using reference values. It is sometimes necessary to make a defensive copy of an object (including whole arrays); this ensures the original object/array is unaffected by future manipulations. For arrays, this is best accomplished using the Arrays.copyOf() method, as follows: int[] copyOfArray = Arrays.copyOf (original, original.length); where the data type returned is based on the type of the original array, passed as the first argument to the copyOf() method. Downloaded by Sadek Ayoub ([email protected])

Use Quizgecko on...
Browser
Browser