Compsci 121 Exam 2
LOGICAL OPERATORS ( &&, ||, ! )
&& = and || = or ! = not 1. (x > 0 && x < 10 ) is true when x is greater than zero AND less than 10 2. (isEven || n % 2 == 0) (isEven is a boolean) is true if EITHER condition is true, one or the other 3. (!isEven) is true if isEven is NOT true
A common error often made by new programmers is to write expressions like (16 < age < 25), as one might see in mathematics. Instead...
( ( 16 < age) && ( age < 25 ));
INTRO TO CONDITIONALS (if & else) & BRANCHES What is the answer if x = -2? USE JAVA VISUALIZER TO SEE THE CONTROL FLOW OF PROGRAM! (Style 1) if (x > 0) { System.out.println("x is positive"); } else if (x < 0) { System.out.println("x is negative"); } else { System.out.println("x is zero"); }
(Style 2) if (x == 0) { System.out.println("x is zero"); } else { if (x > 0) { System.out.println("x is positive"); } else { System.out.println("x is negative"); } }
WHAT IS THE OUTPUT public void mysteryFunction() { for(int i=1;i<=4;i++) { for(int j=1;j<=i;j++) { System.out.print("*"); } System.out.println(); } }
* ** *** ****
{{{{ EXAM 1 Quizlet }}}} THE RANDOM CLASS: (WEEK 4 LECTURE) Write code to generate random numbers (in the other chapters learn to generate random letters) in our case, call the class DiceRoll
* Import the random class package " import java.util.Random; " public class DiceRoll { public static void main (String [ ] args) { Random randDice = new Random ( ); //(((call random constuctor to create an object, reference variable to store the random number))) System.out.print( randDice.nextInt(10) ); by invoking the nextInt() method on the randDice reference variable, and specifically putting 10 inside the parentheses as nextInt(10), randDice will be assigned to a number from 0-9, a total of "10 possibilities".
STRING COMPARISON Should " == " operator be used to compare strings? Can it be used to compare character?
* The operator should not be used with strings, it behaves weirdly; unexpected results will occur. See card sections below discussing string comparison methods equals() and compareTo(). * The " == " operator however can be used to compare characters * str1.equals(str2) method should be used. The == is still used but it better to not do so. c
Shortcut operators: ++ and -- Explain the difference of: ++i (prefix form) i++ (postfix form).
++i (prefix form) increments i first; then evaluates result ------------------------------------------ i++ (postfix form). evaluates result first; then increments i.
TERNARY OPERATOR: PRACTICE THIS OVER AND OVER AGAIN; COME UP WITH QUESTIONS AND MORE EXAMPLES TO GET IT DOWN PAT! TRY USING THESE STATEMENTS FOR THE PROJECTS, more efficient and compact
---
THE FOLLOWING CARDS WILL BE FROM CHP 4. IF NECESSARY AND OVERLAPPING with other card sets, ADD THOSE SLIDES TO BASIC TERMINOLOGY AS WELL. Indicate using "***" for terminology
---
THE FOLLOWING CARDS WILL BE FROM CHP 5:
---
THE FOLLOWING CARDS WILL BE FROM CHP 6: LOOPS
----
{{{{ EXAM 1 }}}} != and ==
!= operator tests if the identities ARE NOT EQUAL. == checks if identities are equal
FOR LOOP EXAMPLE( explain code & pseudocode) for (int j = 0; j < 10; j = j+2) { System.out.print( j ); } 0 2 4 6 8
General for-loop format: for ( <dec/intialize variable> <conditonal test> <update variable> ) { .....(stuff) } The code basically declares a variable j and initialized that to 0. If j satisfies the condition of being less than 10, THEN j is printed. It is only after the condition is checked and j is printed where j is then updated by adding 2. As long as j is less than 10 this will keep repeating.
\' (prints single quote) What is the output for the following: (NOTICE HOW THE BACKSLASH (\) IS IN-FRONT OF THE SINGLE QUOTES) System.out.print ( "Beyonce once said, \'Best revenge is yo paper\', and that's on period. ")
Output: Beyonce once said, 'Best revenge is yo paper', and that's on period.
Convert the if-else statement to a single line using conditional statements & ternary operator: if ( x > 50 ) { y = 50; } else { z = x; }
Not possible, one branch assigns the variable y whereas the other branch assigns a completely different variable of z.
WTF DOES A CONTINUE STATEMENT EVEN DO? int i = 0; while (i < 10) { if (i == 4) { i++; continue; } System.out.println(i + " "); i++; }
OUTPUT: 0 1 2 3 5 6 7 8 9 The continue statement causes it to skip 4. Within the if-branch, if i evaluates to 4, then i is incremented to 5, but the CONTINUE statement causes the program to not execute the rest of the loops-body statements, it prevents the compiler to continue through the code. And instead the compiler with CONTINUE BACK TO THE LOOP CONDITION( i <10) AND CHECK FROM THERE. In addition, when i was evaluated to 4, i was incremented to 5, then the compiler continued to check this current value to the while condition (5< 10). When the program executes through the if-conditional, since 5 == 4, the if-body statements and the continue statement does not execute allowing for the compiler to execute through the rest of the loop statements such as printing i.
\t (creates tab) What is the output for the following: System.out.print( "Cash me outside \thow bout that ")
Output: Cash me outside how bout that (creates a tab)
\\ (prints backlash) What is the output for the following: system.out.print( "Computer science\\engineering" )
Output: Computer science\engineering If it was only a single \, it would print error
Loop body executions = outerIterations * innerIterations. How many iterations total? int row; int col; for ( row = 0; row < 2; row++) { for (col = 0; col < 3; col++) { .....} }
Outer = 2 Inner = 3 Thus 2 * 3 = 6 Answer: 6 iterations
\n (creates new line) What is the output for the following: 1) System.out.print( "Cash me outside \nhow bout that") 2) System.out.print( "\n\nCash me outside how bout that")
Output (1): Cash me outside how bout that (created a new line) The \n escape sequence acts like a println, where a new line is created after it, below Output (2): (Empty line) (Empty line) Cash me outside how bout that
\" (prints double quotes) What is the output for the following: (NOTICE HOW THE BACKSLASH (\) IS IN-FRONT OF THE SINGLE QUOTES) System.out.print ( "Beyonce once said, \"Best revenge is yo paper\", and that's on period. ")
Output: Beyonce once said, "Best revenge is yo paper", and that's on period.
***** ASCII storage: It's important to understand how exactly data is being saved. (check Exam 2 Quizlet Diagrams) + Chp 4 Diagrams
When initializing a char type, ASCII is used to store that value. For example: char userLet = a; Storage visual: 76 [ 97 ] (where userLet is stored) 77 [ ] The 76 and 77 are just the object address', the labeling of an array. The data of the char type variable userLet is stored as 97 in the memory address of 76. the lower case a of userLet is stored as 97 because that is it's ASCII encoding. ASCII chart & encodings: a = 97 b = 98 c = 99 d = 100 ..... Question, how can program then differentiate the identity/equality of the char type a, from an int variable of 97?
Write code to get the area code of that phone number...
phoneNum = 9785556719; //(area-code is 978) int areaCode = phoneNum / 1000000; //(shifts right by 7, so 978)
REAL LIFE PROBLEMS: HOW TO GET A PRE-FIX OF A PHONE: Given and 10-digit phone number stored as an int, the "%" and "/" operators can be used to get any part of the phone number.
phoneNum = 9785556719; //(prefix is 555) int tempVal = phoneNum / 1000; //(the /1000 shifts right by 4, int stores only 978555) int prefixNum = tempVal; ( the %1000 gives the last 3 remaining digits, so 555) Practice more like this...
Write a method which takes a String as parameter and returns a String with the same characters in reverse order. ** public String reverse(String originalString) { String reverseString = "";
public String reverse(String originalString) { String reverseString = ""; for ( int i = (originalString.length() - 1); i >= 0; i--) { reverseString = reverseString.concat( originalString.chartAt(i) ); } return reverseString; }
{{{{ EXAM 1 }}}} Explain the code: System.out.print( randDice.nextInt(6) + 10 );
randDice with store 6 integer possibilities but the + 10 causes those 6 possibilities to start at 10. Th possibilities include 10, 11, 12, 13, 14, 15
{{{{ EXAM 1 Quizlet }}}} What is the result of the following code fragment? Discuss and write an explanation. System.out.println( "1 + 2 = " + 1 + 2 ); System.out.println( "1 + 2 = " + (1 + 2) );
1 + 2 = 12 1 + 2 = 3 The first portion of the fragment results in 12 because numbers 1 and 2 are simply placed next to each other through the insertion of +. The second portion of the fragment results in 3 because the parentheses introduce a mathematical operation. PARENTHESES ARE VERY IMPORTANT!
Shortcut operators: ++(increment) and --(decrement) PRACTICE PROBLEMS 1) int i = 5; int x = ++i; X EQUALS? 2) int i = 5; int y = i++; Y EQUALS?
1) x = 6 because i is incremented by 1 from 5 first then the expression if evaluated 2) y = 5 because the expression is evaulted before i is incremented when i is 5.
OUTPUTTING MULTIPLE CHARACTER VARIABLES WITH ONE OUTPUT STATEMENT: Let's say the following char variables are initialized to... char char1 = a; char char2 = b; What is the difference and problem between the following: 1) System.out.print ( char1 + char2 ); 2) System.out.print(" " + char1 + char2);
1) System.out.print ( char1 + char2 ); The line would output the digit of 105 because the ASCII of lower-case 'a' is 97 and lower-case 'b' is 98. (97 + 98 = 195). When char variables in an expression as such are parsed through the print() method, the program interprets them through their ASCII value and then adds them together; outputting a number rather than the characters. 2) System.out.print(" " + char1 + char2); The initial " " placed in-front of the variables tells the compiler to output a string of characters instead of numerical values. Without the " " operator, the compiler would've simply added the numerical values of char1 and char2, and output the resulting sum. The "+" operator when parsed through the print() method in between variables, simply outputs them side-by-side.
{{{{ EXAM 1 }}}} IDENTITY(==) VS. EQUALITY(.equals) (STRINGS) and String constructors... (CHECK WEEK 4 DIAGRAMS) Explain the following codes in relation to identity vs. equality ( == & .equals() operator): (USE DIAGRAMS from Exam 1 Quizlet folder) 1) String greeting1 = "bonjour"; String greeting2 = "bonjour"; -------------------------------------- 2) String input1 = new String("bye"); String input2 = new String("bye");
1) greeting1 -----> | string: "bonjour" | <------- greeting2 greeting1 and greeting2 both point to the same string literal value. THEY HAVE THE SAME IDENTITY since they reference the same string literal value. In the condition (greeting1 == greeting2), it evaluates to true because the "==" operator checks to see if the variables refer to the same reference itself/identity. " == " TESTS IDENTITY 2) input1 -----> | string: "bye" | input2 -----> | string: "bye" | input1 and input 2, because initialized and declared through constructors using the new operator, the constructor method implemented and created on a new reference variable TO REFER TO each time it was called... Thus input1 and input2 REFER TO DIFFERENT LITERAL STRINGS OF BYE. THEY DO NOT HAVE THE SAME IDENTITY. In the condition of (input1 == input2), it evaluates to FALSE, because they don't have the same identity. HOWEVER...... In the condition (input1.equals(input2), it evaluates to TRUE, because the equals() operator checks if the actual values of the references are equal. And bye and bye are equal. " input1.equals(input2) " TESTS EQUALITY OF THE REFERENCE'S VALUE
De Morgan's Law ( Statistics / Probability ) (Check hand-written notes and videos) https://www.youtube.com/watch?v=-LW2lGHv0GE
1) !(A && B) is the same as !A || !B !(A && B) = !A || !B Kinda like the distributive property. It is essentially saying, in order for the condition of (A && B) to be false(!), A and B needn't both be false, but rather either A or B must be false. 2) !(A || B) is the same as !A && !B !(A || B) = !A && !B It is essentially saying, for the condition of (A || B) to be false (!), not only A OR B can be false, but rather both A AND B must be false. A process for simplifying Boolean expressions Two laws in Boolean algebra which state that AND and OR, or union and intersections, are duel. The rules can be expressed in English as 1) 'The negation of a conjunction is the disjunction of the negations.'
Compare the first string with the second, determine if it is less than, great than, or equal to (based of ASCII): 1) "Apples" & "Oranges" 2) "merry" & "Merry" 3) "banana" & "bananaijcakao"
1) LESS THAN 'A' is less than 'O' 2) GREATER THAN 'm' is greater than 'M' 3) LESS THAN first part of the string "banana" was equal but the longer string has greater value.
System.out.println((letter >= 'a' && letter <= 'z') || (letter >= 'A' && letter <= 'Z')); See the following declarations of letter (type char) 1) letter = '&'; 2) letter = 'p' 3) letter = 'O'; When would it evaluate to "true" and when would it be "false"?
1) letter = '&'; FALSE because you can use the logical understanding that the symbol of '&' isn't between the ranges of a-b 2) letter = 'p' TRUE because p is in the range of a-b 3) letter = 'O'; TRUE because O is in between A-Z
WHAT IS THE OUTPUT public void mysteryFunction() { for(int i=1;i<=5;i++) { for(int j=1;j<=5;j++) { System.out.print(j); } System.out.println(); } }
12345 12345 12345 12345
What are the 3 different types of loops?
3 types of loops: * For loop * While loop * Do-while loop
SHORT CIRCUIT EVALUATION IS WHEN?: Give examples with || and &&: true || anything is always....... false && anything is always.......
A complex conditional expression where the subsequent condition(s) might not be executed. true || anything is always true false && anything is always false
The conditional expression has the form of?
A conditional expression has the form : "condition ? exprWhenTrue : exprWhenFalse" A conditional expression has three operands and thus the "?" and ":" together are sometimes referred to as a ternary operator.
What happens with different inputs due to the continue operator? Scanner in = new Scanner ( System.in ); int x = -1; int sum = 0; while (x != 0){ x = in.nextInt(); if (x <= 0) { continue; } System.out.println( "Adding " + x); sum += x; }
A continue statement in a loop causes an immediate jump to the loop condition check In this case, the continue statements causes the program to skip over any negative values. (check java visualized to better understand, input different numbers); If x is assigned to (-5), -5 isn't positive thus the program won't continue through the loop without execution.
LOOP
A loop is a program construct that repeatedly executes the loop's statements/statements (known as the loop body) while the loop's expression is true; when false, execution proceeds past the loop. Each time through a loop's statements is called an iteration.
Nested for-loop? And what is the formula for the total number of iterations?
A loop structure inside of another loop structure, as would be found in an insertion sort, bubble sort, or selection sort, or in the processing of a two-dimensional array structure. Total loop iterations = Inner total loop body Total loop iterations = executionsouterIterations * innerIterations . Inner total loop body executions = outerIterations * innerIterations.
Branch (multi-branch if-statements)
A program's path taken only if an expression's value is true. Such a branch is commonly known as an If branch: A branch taken only if an expression is true.
Dividing by zero causes....
A run-time error: causes a program to terminate early. Exception in thread "main" java.lang.ArithmeticException: / by zero
boolean result = (((a % 7) > 2) || (b/3 < 7)) && ((b + a > 10) && !(c + a < 25)); Which of the following assignments will result in the variable result being true? A) int a =19, b=22, c=10; B) int a =14, b=13, c=5; C) int a =19, b=13, c=5; D)int a =16, b=22, c=10;
A) int a =19, b=22, c=10;
How many times does this loop execute? for(int i = 0; i < 30; i += 3) { System.out.println(i + " " ); } A. 10 B. 30 C. 5 D. Prints endlessly E. 29
A. 10 ( 0, 3, 6, 9, 12, 15, 18, 21, 24, 27)
What is the output? String island = "Corfu"; switch ( island ) case "Corfu" : System.out.println( "User wants to visit Corfu"); case "Crete" : System.out.println( "User wants to visit Crete"); break; case "Santorini" : System.out.println( "User wants to visit Santorini"); break; default: System.out.println( "Unknown island"); --------------------------------------------------------- A. User wants to visit Corfu User wants to visit Crete B. User wants to visit Crete C. Unknown Island D. User wants to visit Corfu E. Error
A. User wants to visit Corfu User wants to visit Crete Top two statements are print because there's only a break after the second statement.
***** ASCII stands for? What is the order? Search up the ASCII chart. ( http://www.asciitable.com/ )
ASCII (American Standard Code for Information Interchange) Encoding characters through binary numbers. Other characters such as control characters (e.g., a "line feed" character) or extended characters (e.g., the letter "n" with a tilde above it as used in Spanish) are not shown. Order: CAPITALIZED LETTERS HAVE LOWER VALUES THAT THEIR LOWER CASE VERISION, EXAMPLE: A < a encodings: A = 65 B= 66 a = 97
IMPLICIT VS. EXPLICIT RANGES
An implicit range is a range without gaps. An explicit range has gaps. Explicit ranges within the conditions of if-else statements must be stated explicitly and clearly using logical operators(&&, ||) Implicit range example: Ranges: <=10 11..20 21...50 51+ if (x <= 10) { .... } else if ( x < 20 ) { .... } else if ( x < 50 ) { ..... } ---------------------------------------- Explicit Range example: Ranges: <=10 50...100 150...200 *** notice how is jumps from 11 to 49 and 101 to 150, there are gaps in the range. Gaps in the condition must be explicitly eliminated from the possibility. if ( x <= 10 ) { ..... } else if ( ( x <= 50 ) && (x => 100) ) { ...... } else if ( ( x <= 150) && (x <= 200) { .... }
INFINITE LOOPS
An infinite loop is a loop that never stops iterating. A common error is to accidentally create an infinite loop, often by forgetting to update a variable in the body, or by creating a loop expression whose evaluation to false isn't always reachable.
WHAT IS PRINTED? for (int j = 2; j < 100; j = j * j) { System.out.print( j + " "); } A. 2 4 6 8 10 B. 2 4 16 C. 2 4 16 256 D. 2 4 16 32 64 E. Error
B. 2 4 16
String str = "I ordered the large coffee, not the small tea."; String subStr = str.substring(10, str.length()); What is the value of subStr? A. the large coffee, not the small tea B. the large coffee, not the small tea. C. Error, index out of bounds. D. he large coffee, not the small tea.
B. the large coffee, not the small tea. * remember whitespaces count as index's and period punctuation count as the index's as well
What is the output? for (int i = 0; i < 3; i++) { for (int i = 0; i < 8; i++) { if (j >= 2) { break; } System.out.print( "" + i + j + " "); } A) 00 11 22 00 11 22 B) 012 123 234 C) 00 01 10 11 20 21
C) 00 01 10 11 20 21
Given int x = 4, y = 1, z = 10 which comparisons are evaluated? ((x > 2) || (y < 4)) && (z == 10) A. Error B. (x>2), (y<4) and (z==10) C. (x>2) and (z==10) D. (x>2) and (y <4)
C. (x>2) and (z==10) Only one condition within a condition of OR is evaluated. The computer evaluates left to right. (4 > 2) is true so OR operator evaluates to true. (z == 10) is evaluated to determine final result.
String a = "cow" , b = "snake", c = "walrus"; a.compareTo(b); b.compareTo(c); c.compareTo(a); c.compareTo(c); WHAT ARE THE OUTPUTS? A. All negative values B. All positive values C. Negative, negative, positive, zero D. Positive, negative, positive, zero
C. Negative, negative, positive, zero
{{{{ EXAM 1 }}}} Which of the following will work like flipping a coin and getting us 0 and 1 (heads/tail)? A. randGen.nextInt(0); B. randGen.nextInt(1); C. randGen.nextInt(2); D. randGen.nextInt(3);
C. randGen.nextInt(2);
A Break or Continue statement in loops causes? (Check CHP 6 Empanada code)
Check diagrams! A break statement in a loop causes an immediate exit of the loop. A break statement can sometimes yield a loop that is easier to understand. A continue statement in a loop causes an immediate jump to the loop condition check. A continue statement can sometimes improve the readability of a loop. Break and continue statements can avoid excessive indenting/nesting within a loop. But they could be easily overlooked, and should be used sparingly, when their use is clear to the reader.
**** Constant variables
Constant variables are variables whom which values don't change and must be capitalized. They are FINAL VARIABLES. For example pi or e must is capitalized, to make constant variables clearly visible in code. final double SPEED_OF_SOUND = 761.207; MUST emphasize the "final" can't just have double in front
What is the output when n = 5? while (n != 1) { System.out.print(n + " "); if (n % 2 == 0) { n = n / 2; } else { n = n * 3 + 1; } } A. 2 B. 5 16 8 4 2 -1 C. 5 16 8 4 2 1 D. 5 16 8 4 2 E. 0
D. 5 16 8 4 2
While-loop question: What does this loop do when executed? int x = 10; while( x < 15 ) { System.out.println(x + " " ); } A. prints 10 B. prints 10 11 12 13 14 C. prints 10 11 12 13 14 15 D. Prints 10 endlessly E. Does not execute
D. Prints 10 endlessly 10 is forever less than 15 and while this is true, it will print x endlessly This is known as an: INFINITE LOOP
Solve question boolean var1 = true; boolean var2 = false; System.out.println(var2 && var1); A. 0 B. 1 C. true D. false E. error
D. false At first I thought there would be an error but since it is encapsulated, it can be a conditional statement. Since both aren't true, since var2 AND (keyword: &&) var1 aren't both true, it evaluates to false.
DO-WHILE LOOPS
Do-While loop executes the body first then the test. Do-while loops (POST-TEST), on the other hand, execute whatever action is instructed at least once before checking the condition
What is the output generated by the following code fragment? Explain using pseudocode. int x = 0; while (x < 10) { if (x % 2 != 0) { x++; continue; } else if (x > 5) { break; } System.out.print(x++); } A. 0123456789 B. 13579 C. 02468 D. 13 E. 024
E. 024 The code is basically saying: While x is less than 10... and if( x == ODD), if x is ODD, increment x and continue to check back to check the loop-condition. While also x is less than 10, if x is not ODD by negation... then else-if x is EVEN and GREATER than 5, break from the whole loop and terminate all execution of statements. When x = 0, 0 which is even won't satisfy the first if-conditional statements thus it falls through the rest of the body's statements. Now because x is even and LESS than 5, it doesn't satisfy the else-if condition; thus if won't break out of the loop completely. Since it didn't break out of the loop 0 is gone on to be printed and then post-form incremented. Essentially only even numbers that are less than 5 don't break out of the loop and actually go on to be printed.
WHAT IS PRINTED? for (int j = 2; j < 100; j = j * j) { System.out.print( j + " "); } System.out.print( j ) A. 2 4 6 8 10 B. 2 4 16 C. 2 4 16 256 D. 2 4 16 32 64 E. Error
E. Error j variable is outside the scope!
***** Escape Sequences
Escape sequences allow java to print out characters that already have operations. An escape sequence is a two-character sequence that escapes the implemented operations of java upon a symbol. For example operations such as " ", or /, already have a purpose System.out.print( "Sarah stated, "Can we go get food?" after they left" ) In this case the java compiler won't print out the inner " " because the operation will detect it as a string literal and only prints what's inside/between it...Hence escape sequences and programs are used to achieve the print of these character operations and prevents their java implementation.
{{{{ EXAM 1 }}}} String name1 = "Grace Hopper"; String name2 = new String("Grace Hopper"); Evaluate: name1 == name2.....
FALSE!!!! name1 ----> | string: Grace Hopper| name2 ---> | string: Grace Hopper| THEY DO NOT HAVE THE SAME IDENTITY!! thus it is false. If it was, name1.equals(name2), it would've evaluated to TRUE.
How to determine what loop should be used? * For loop * While loop * Do-while loop
FOR LOOP: Use when # of iterations is known before the loop: like iterating N times WHILE LOOP: Use when # of iterations isn't computable before the loop. Like iterating until 'Q'.
Introduction to REFERENCES: Explain the following codes through a diagram: 1) String greeting1 = new String ( "hi" ); String greeting2 = new String ( "hello" ); ------------------------------------------------- 2) greeting1 = greeting2;
In the first piece of code... 1) greeting1 -----> | string: "hi" | greeting2 -----> | string: "hello" | the variable greeting1 references the string of "hi" the variable greeting2 references the string of "hello" In the second piece of code... 2) When greeting1 is assigned to greeting2, they now both reference the same string, they point at the same box... ASSIGNING A REFERENCE VARIABLE TO ANOTHER REFERENCE VARIABLE SIMPLY CAUSES THEM BOTH TO REFER TO THE SAME MEMORY ADDRESS. greeting1 -----> | string: "hello" | <------- greeting2 It is not the same as.... greeting1 -----> | string: "hello" | greeting2 -----> | string: "hello" |
WHILE LOOP EXAMPLE: (explain code and pseudocode) public static void countdown(int n) { while (n > 0) { System.out.println(n); n = n - 1; } System.out.println("Blastoff!"); }
It's a countdown method, that count's down from n parameter to 0. While the conditon (n>0) is true, while n is positive, it will print n and then decrement n. When n is no longer positive, when n is 0, the method prints "Blastoff! ------------------------------------------ PSUEDOCODE: While n is greater than zero { print the value of n and then reduce the value of n by 1. } When n gets to zero, print "Blastoff!"
Explain what is going on. int y = (5 + 10 + 15) * (1 / 3);
It's a logical error (30) * (0) = 0 because ⅓ is a fraction and will evaluate/round to 0
***** ASCII vs. UNICODE
Many earlier programming languages like C or C++ use ASCII. Java uses a more recent standard called Unicode. ASCII can represent 255 items, whereas Unicode can represent over 64,000 items; Unicode can represent characters from many different human languages, many symbols, and more. (For those who have studied binary: ASCII uses 8 bits, while Unicode uses 16, hence the 255 versus 64,000). Unicode's first several hundred items are the same as ASCII. The Unicode encoding for these characters has 0's on the left to yield 16 bits. ASCII is 7 bit (or 128 values). This takes care of 0-9 A-Z, a-z, and punctuation. UNICODE- More than 100,000 characters, Universal Character Set, Includes ASCII.
Math method calls. Java offers over 30 operations. Check java oracle for all operations/specifics.
Math.methodName() Method: * sqrt(x) ---------- takes square root of x * pow(x,y) -------- x^y * abs(x) --------- takes aboslute value of x
compareTo() COMPARING STRINGS with compareTo() method WHAT IS THE OUTPUT? String name1 = "Alan Turing"; String name2 = "Ada Lovelace"; int diff = name1.compareTo(name2); if(diff == 0) System.out.println ("The names are the same."); if(diff < 0) System.out.println ("name1 comes before name2."); if(diff > 0) System.out.println ("name2 comes before name1.");
Outputs: name2 comes before name1. Diff is positive. Return value from compareTo is the difference between first characters in the strings that differ. If the strings are equal, their difference is zero. If the first string (the one on which the method is invoked) comes first in the alphabet, the difference is negative. Otherwise, the difference is positive.
CHARACTER CLASS STATIC METHODS Character.isDigit( char ) Character.isLetter( char ) Character.isLetterOrDigit( char ) Character.isLowerCase( char ) Character.isUpperCase( char ) Character.isWhitespace( char ) Character.toLowerCase( char ) Character.toUpperCase( char )
Returns boolean
Introduction to arrays & string class methods... String pupName = "Spot"; char ch = pupName.charAt(1); //(ch is assigned to 'p') ch = pupName.charAt(0); //(ch is assigned to 'p')
S P O T ^ ^ ^ ^ 0 1 2 3 The 'S' character has an index of 0, in the array, that is its position.
PROBLEM: How to join 2 Strings (st1 and st2) (more than 1 method)
SOLUTION: Use the " + " operator or use st1.concat(st2)to return a new string that appends st2 to st1. String st1 = "Dis"; String st2 = "enfranchisement"; System.out.println( st1 + st2 ); System.out.println( st1.concat(st2) ); Output: Disenfranchisement Disenfranchisement
Write the code: PROBLEM: Find the last character in the string "Supercalifragilisticexpialidocious".
String word = "Supercalifragilisticexpialidocious"; int wordLength = word.length(); int lastIndexOfWord = wordLength - 1; char lastChar = word.charAt( lastIndexOfWord ); System.out.print( lastChar);
Floating-point division
The "/" operator performs floating-point division if at least one operand is a floating-point type. EXAMPLE: double a = 10/4.0; ( evaluates to 2.5 because 4.0 is a floating-point operand) For an arithmetic operator like + or *, if either operand is a double, the other is automatically converted to double, and then a floating-point operation is performed. 3/2 = 1 3/2.0 = 1.5
TERNARY OPERATOR - CONDITIONAL EXPRESSIONS (CHECK/SEARCH DIAGRAMS from W5 lectures and diagrams in Exam 2 Quizlet folder) Re-write pseudo-code below with a ternary operator approach: if (condition) { myVar = expr1; } else { myVar = expr2; }
The code given can written with a ternary operator approach: myVar = (condition) ? exp1 : exp2; Basically, when the condition is true, myVar is initialized to exp1, whatever is before the colon( : ). However, when the conditional statement evaluates to false, myVar is initialized to exp2, whatever is after the colon ( : ). The "?" is the ternary operator.
DO-LOOP EXAMPLE: (explain code and pseudocode) (Check lab 5) Scanner in = new Scanner(System.in); boolean okay; double inputNum; do{ //THE DO PART EXECUTES ATLEAST ONCE System.out.print("Enter a number: "); if (in.hasNextDouble()) { okay = true; } else { okay = false; String word = in.next(); System.out.println(word + " is not a number"); } } while (!okay); //LOOP EXIT CHECK inputNum = in.nextDouble();
The statements encapsulated in the do operator's scope will execute at-least once regardless if the condition is true or not. To understand this code we must understand what the hasNextDouble() method exactly does. It basically returns a boolean determined off of if whatever the user next inputs is a double. This function returns true if and only if this scanner's next token is a valid Double. Regardless if true or not, if it's a valid Double, the do part executes the statements of either the if-branch or else-branch at least once. Note that though, it never initializes the inputNum variable to the keyboard input, it just tells the user whether or not the input is a number or not. Then later on in the code, where the while loop takes place... the do part statements will continue to be executed WHILE the condition is false! (( while (!okay) )) It is only once the while loop, once the condition that a valid double was inputted is true that it is exited. Hence then, the double inputNum variable is initialized to user input when it satisfies the condition of true. ---------------------------------------------- PSUEDOCODE: General form: do { // statements in body } while (loop test);
WHILE LOOPS
While loops execute the loop test first, then body. A while loop is a program construct that repeatedly executes a list of sub-statements (known as the loop body) WHILE the loop's condition/expression evaluates to true. Each execution of the loop body is called an iteration. Once entering the loop body, execution continues to the body's end, even if the expression would become false midway through. While loops (PRE-TEST) check the condition before performing any kind of task.
DO WHITESPACES COUNT AS AN INDEX? Explain: What is the output? String pupActivity = "My dog Spot runs"; pupActivity.charAt(2);
YES! pupActivity.charAt(2); Output: " " It would simply output a single whitespace because the index as 2 is a space. Between the words "My" and "dog" My dog Spot runs ^ ^ ^ 0 1 2
CONVERTING VARIABLE TYPES..... TYPE CASTING
You can convert the object type by type casting: double myDoubleVar = 5/4; int myIntVar = 1; myIntVar = (int)myDoubleVar; //(converts the 5/4 to an 1 to store as an int) myDoubleVar = (double)myIntVar; //(converts the 1 to a 1.0)
double Z = Math.pow(2.0, Math.pow(x, y) + 1); Evaluate was Z is...
Z = 2^((x^y) + 1)
Common escape sequences/ methods: (check chp 4 diagrams) (there are more sequences than the ones listed below, search up) \n (creates new line) \t (creates...) \' (prints...) \" (prints...) \\ (prints...)
\n (creates new line) \t (creates tab) \' (prints single quote) \" (prints double quotes) \\ (prints backlash)
***** Sentinel Value
a preselected value that stops the execution of a program. ( n > 0) : While n is greater than 0, 0 is the sentinel value
What's outputted? public void mystery1() { int sum=0; for(int i=1;i<4;i++) { for(int j=1;j<4;j++) { sum+=j; } } System.out.print(sum); } a) 18 b) 40 c) 10 d) 6
a) 18 Because (1+2+3=6 ) this is repeated 3 times total(i)
What it is the possible outputs for: Random randGen = new Random () (randGen.nextInt(9) + 4) a) 4 - 12 b) 4 -13
a) 4 - 12
When is it best to use switch statements instead? SWITCH STATEMENT definition and restrictions:
allows multi-way branching Duplicate case values are not allowed. * The switch statement's expression should be an integer, char, or string. The expression should not be a Boolean or a floating-point type. Each case must have a constant expression like 2 or 'q'; a case expression cannot be a variable. • The value for a case must be a constant or a literal. Variables are not allowed. • The value for a case must be the same data type as the variable in the switch. • The break statement is used inside the switch to terminate a statement sequence. • The break statement is optional. If omitted, execution will continue on into the next case. • The default statement is optional, and it must appear only at the end of the switch.
indexOf(String) STRING METHOD & indexOf(String, int) WHAT IS THE OUTPUT? String fruit = "banana"; int indexA = fruit.indexOf( 'a' ); System.out.println( indexA ); int index2A = fruit.indexOf( 'a' , 2 ); System.out.println( index2A );
b a n a n a ^ ^ ^ ^ ^ ^ 0 1 2 3 4 5 Outputs: 1 3 The statement " int index2A = fruit.indexOf( 'a' , 2 ); " specificed for index of the second occurence of a.
What is the output? public void mystery2() { int sum=0; for(int i=1;i<4;i++) { for(int j=1; j < i; j++) { sum+=j; } } System.out.print(sum); } a) 14 b) 4 c) 16 d) 20
b) 4 When i = 1, j is also 1, thus it j doesn't satisfy the condition of j<i. Therefore sum is not increased. When i=2, j can be 1 and 1 only to satisfy 1<2. Thus sum = sum + 1; When i=3, j can only be 1 and 2 to be less than 3. Thus sum = sum + 1 + 2; Essentially the expression would be.. sum = 0 + 1 + 1 + 2; = 4
What is the value of variable x after the following statements execute? int y = 6; int x = (1/2) * y + 8; a) 11 b) 8 c) 7 d) 14
b) 8 !!!! Because the 1/2 is a double, and it can't be stored as 0.5 in an int object type. Thus it's stored as just 0 since the floating point is removed. (0*6) = 0, and 0 + 8 = 8.
***** Numerical Data Types ( CHP 4 )
byte, short, int, long, float, double
What is the output? int i = 1; System.out.println( i++ ); System.out.println( ++i ); a) 1 2 b) 2 3 c) 1 3
c) 1 3 The i++ first prints 1 BEFORE it's incremented. Once printed it's incremented 1 to 2. Then the ++i increments 2 to 3! It is only AFTER i is incremented that it prints i's value which is 3.
STRING METHODS: ((( more than ones listed below, like .equalsIgnoreCase() etc, search up ))) * state the return type, give a description of method, and give example charAt(int) indexOf(String) length() substring(int, int) toUpperCase() concat(String)
charAt(int) * Return type: char * Description: invoke this method on a string with an int parameter of the index desired of that string. It returns the character at that index of the parameter given. ________________________________________ indexOf(String) * Return type: int * Description: invoke on a string. Returns the position/index of the first occurrence of the parameter String. Returns -1 if the string is not found. Example: String Str = new String("Welcome to geeksforgeeks"); String subst = new String("geeks"); System.out.print("Found geeks starting at position : "); System.out.print(Str.indexOf(subst)); Output: Found geeks starting at position : 11 ________________________________________ length() * Return type: int * Description: returns the number of characters on the invoked String. ________________________________________ substring(int, int) * Return type: string * Description: substring(int beginIndex, int endIndex): Returns the substring of the calling object String starting from the first parameter beginIndex to the second parameter (endIndex -1). substring(int begIndex, int endIndex) Parameters : beginIndex : the begin index, inclusive. endIndex : the end index, EXCLUSIVE. __________________________________________ toUpperCase() * Return type: String * Description: Returns a String with the same characters as the calling object String, but with all characters converted to uppercase. __________________________________________ concat(String) * Return: String * Description: Returns a combined string of the parameter and the invoked upon string.
{{{{ EXAM 1 }}}} REVIEW: SCANNER CLASS METHODS & nextInt() method Scanner console = new Scanner(System.in); Scanner object means: input from keyboard. Finish the purpose of the specified methods below: console.nextInt()--- looking for int value... console.nextDouble()--- looking for a.... console.next() --- looking for a.... console.nextLine() --- looking for a....
console.nextInt()--- looking for int value console.nextDouble()--- looking for double value console.next() --- looking for String value console.nextLine() --- looking for a whole line/remainder of a line
Write a method to find and return the sum of factorials of numbers from 1 to n. *** I.e: 1!+2!+3!+...+n! = 1+1*2+1*2*3+...+1*2*3*...*n FINISH THE REST: public int sumOfFactorials(int n) { int fact = 1; int sum = 0;
for (int i = 1; i <=n; i++) //parses through numbers { for (int j=1; j<=i;j++) { //finds factorials of individual numbers fact = fact * i; } sum = sum + fact; }
Write a method which takes an int as parameter and returns its factorial. (Factorial of a number x= x!= 1*2*3*4*5*...*x) ** public int factorial(int num) { .............
int factorial = 1; for ( int i = 1; i <= num; i++) { factorial = factorial * i; } return factorial; }
CONVERTING VARIABLE TYPES * int - to - double * double - to - int
int-to-double conversion is automatic, also know as implicit conversion: Example int a = 5; double b = a; (b is assigned to 5) but double-to-int conversion may lose precision. Example double a = 5/4; (1.25) int b = a; ( b is assigned to 1) HOW DO YOU CONVERT? **** type casting
From the Java API Math class, summarize some of the methods
max(double a, double b) - outputs the max value double r = Math.max(3.5, 7.1); //7.1 (outputs max) double s = Math.sqrt(16.0); //4 (outputs square root) double t = Math.sin(.7); //(outputs sin(.07)) double u = Math.min(3.5, 7.1); //3.5 (outputs min) double v = Math.pow(2,5); //32.0 (outputs 2 to the 5th power)
Java does not have a method for specifically getting one character from user input. Instead, the following sequence can be used... There isn't a nextChar() like there is for a nextLine().... There isn't any method looking for a char like there is for looking for lines, int, double, string
myChar = scnr.next().charAt(0) The next() gets the next sequence of non-whitespace characters (as a string), and charAt(0) gets the first index , the first character in that string.
" == " RELATIONAL OPERATOR TO COMPARE CHARACTERS, STRINGS, AND FLOATING-POINT TYPES The relational and equality operators work for integer, character, and floating-point built-in types. WILL THE FOLLOWING COMPILE? WHY & WHY NOT? myInt == 42 myChar == 'q' myDouble == 3.25
myInt == 42 WILL COMPILE myChar == 'q' WILL COMPILE BECAUSE... The characters' numerical encodings will be compared. myDouble == 3.25 WILL NOT COMPILE because Floating-point types should not be compared using the equality operators, due to the imprecise representation of floating-point numbers. DOUBLES WITH DECIMALS SHOULD NOT BE COMPARED
RANDOM CLASS and %(mod) operator Let's say randNum generates a random number: randNum % 51; //(can only yield 0 - 50; 51 cannot be a possible remainder) With this being said answer the following.... What non-negative randomly generated number of x will yield the range of 5-10?
storeVariable = (x % 6) + 5; The "% 6" makes it so that the only possible outputted remainers of the expression (x % 6) will be through 0-5. Then by adding the "+ 5" slides the range to become 5-10.
What non-negative randomly generated number of xyz will yield the range of 60-100? (40 possibilities) note that xyz, must because greater than the number of possibilities, and greater than the range itself to actually output these ranges.
storeVariable = (xyz % 41) + 60; 40 possibilities, starting at 60, ending at 100.
USING SWITCH STATEMENTS INSTEAD OF MULTIPLE IF STATEMENTS note : for numerical case values instead of '5' used parantheses! Examples case (5) :
switch(grade) { case 'A' : System.out.println("Excellent!"); break; case 'B' : case 'C' : System.out.println("Well done"); break; default : System.out.println("Invalid grade");} System.out.println("Your grade is " + grade); IF THE (grade variable == case ) then print the statement. Must follow up with a break to separate the different cases/conditions. Notice how case B and C are both under the "Well done" condition/evaluation because there is no break between them.
substring(int, int) STRING METHOD WHAT IS THE OUTPUT? String fruit = "tangle"; System.out.println( fruit.substring(4, 6));
t a n g l e ^ ^ ^ ^ ^ ^ 0 1 2 3 4 5 Outputs: le substring(startIndex, endIndex) returns substring starting at startIndex and ending at (endIndex - 1). The length of the substring is given by (endIndex - startIndex).
Convert the if-else statement to a single line using conditional statements & ternary operator: if ( x > 50 ) { y = 50; } else { y = x; }
y = ( x > 50 ) ? 50 : x;