Docsity

Java OCA Logic Cheat Sheet | Control Flow & Algorithms, Exams of Java Programming

Toggle sidebar
bg1
๐Ÿ Python Logic Cheat Sheet
1. Control Flow Logic
Concept
Syntax
Logic Pattern
If / Elif / Else
if x > 0:
elif x == 0:
else:
Evaluate conditions top-to-bottom; first
match wins
Ternary
result = "yes" if cond
else "no"
Inline decision for simple assignments
Match
(3.10+)
match value:
case 1:
...
case _:
...
Pattern matching; _ = default/wildcard
Truthiness
if items: (empty list =
False)
Falsy: None, False, 0, "", [], {}, ()
2. Loop Logic
python
# For loop โ€” iterate over sequence
for item in items:
if item == target:
break # exit loop entirely
if item < 0:
continue # skip to next iteration
else:
# runs only if loop completed WITHOUT break
print("not found")
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Java OCA Logic Cheat Sheet | Control Flow & Algorithms and more Exams Java Programming in PDF only on Docsity!

๐Ÿ Python Logic Cheat Sheet

1. Control Flow Logic

Concept Syntax Logic Pattern

If / Elif / Else

if x > 0: elif x == 0: else:

Evaluate conditions top-to-bottom; first

match wins

Ternary

result = "yes" if cond else "no"

Inline decision for simple assignments

Match

match value: case 1: ... case _: ...

Pattern matching; _ = default/wildcard

Truthiness

if items: (empty list =

False)

Falsy: None, False, 0 , "", [], {}, ()

2. Loop Logic

python # For loop โ€” iterate over sequence for item in items: if item == target: break # exit loop entirely if item < 0 : continue # skip to next iteration else: # runs only if loop completed WITHOUT break print("not found")

# While loop โ€” repeat until condition fails while not done: done = check() # Enumerate โ€” index + value for i, val in enumerate(items, start= 1 ): print(i, val) # Zip โ€” parallel iteration for a, b in zip(list1, list2): print(a, b) # Comprehension โ€” build list in one line squares = [x** 2 for x in range( 10 ) if x % 2 == 0 ] lookup = {k: v for k, v in pairs} unique = {x for x in items}

Logic rule: Use for when you know the sequence; use while when you know the

condition. Always ask: "Do I need the index?" โ†’ enumerate; "Do I need pairs?" โ†’ zip.

3. Data Structure Selection Logic

Structure Use When Key Operations

list

Ordered, mutable, duplicates

OK

append(), pop(), sort() โ€” O(1) access by

index

tuple

Immutable record / fixed

group

Unpacking: x, y = point

dict Keyโ†’value lookup^

d.get(k, default), d.items() โ€” O(1)

lookup

set

Uniqueness / membership

test

in check O(1), | union, & intersection

risky() except (ValueError, KeyError) as e: # catch specific, not bare log(e) except Exception as e: # last resort raise RuntimeError("context") from e else: # runs if NO exception celebrate() finally: cleanup() # always runs

Logic rule: Catch the narrowest exception that you can actually handle. Never swallow

errors silently.

6. Common Algorithm Patterns python # Accumulator pattern total = 0 for x in nums: total += x # Filter-map-reduce result = sum(x** 2 for x in nums if x > 0 ) # Two-pointer (sorted list) l, r = 0 , len(arr)- 1 while l < r: if arr[l] + arr[r] == target: break elif arr[l] + arr[r] < target: l += 1 else: r - = 1 # Frequency count from collections import Counter freq = Counter(items).most_common( 3 ) # Guard clauses โ€” flatten nested ifs def process(x): if x is None: return None # exit early if x < 0 : raise ValueError

return x * 2 # main path unindented

7. Complexity Quick Reference

Operation List Dict/Set

Access by index/key O(1) O(1)

Search (in) O(n) O(1)

Insert (end) O(1) amortized O(1)

Delete O(n) O(1)

โ˜• Java Logic Cheat Sheet

1. Control Flow Logic

java // If / else-if / else โ€” same logic as Python if (x > 0 ) { ... } else if (x == 0 ) { ... } else { ... } // Switch statement (classic) switch (day) { case MONDAY: case TUESDAY: doWork(); break; // fall-through: both cases default: rest(); break; }

// Streams โ€” functional iteration (Java 8+) List upper = names.stream() .filter(n - > !n.isBlank()) .map(String::toUpperCase) .sorted() .collect(Collectors.toList());

Logic rule: Use enhanced for for readability; use classic for when you need the index or

to modify the collection. Use streams for filter/map/reduce pipelines.

3. Data Structure Selection Logic

Structure Use When Key Operations

ArrayList Ordered, fast index access add(), get(i), size() โ€” O(1) get

LinkedList Frequent insert/remove at ends addFirst(), removeLast()

HashMap Keyโ†’value lookup^ get(),^ put(),^ getOrDefault()^ โ€”^ O(1)

HashSet Uniqueness^ add(),^ contains()^ โ€”^ O(1)

TreeMap Sorted keys firstKey(), headMap() โ€” O(log n)

ArrayDeque Stack or queue push(), pop(), offer(), poll()

Decision tree: Need key lookup? โ†’ HashMap. Need sorted order? โ†’ TreeMap. Need

uniqueness? โ†’ HashSet. Need a stack/queue? โ†’ ArrayDeque (never Stack).

4. Class & Method Logic java // Immutable class โ€” best practice for data carriers public final class Point { private final int x, y; public Point(int x, int y) { this.x = x; this.y = y; }

public int x() { return x; } public int y() { return y; } } // Interface with default method โ€” shared logic public interface Shape { double area(); // abstract โ€” must implement default String describe() { // default โ€” inherited return "A shape with area " + area(); } } // Record (Java 16+) โ€” auto-generated constructor/equals/toString public record Point(int x, int y) {} // Varargs + generics public static List listOf(T... items) { return new ArrayList<>(Arrays.asList(items)); }

Logic rule: Program to interfaces (List list = new ArrayList<>()), not

implementations. Prefer final fields for immutability. Use record for simple data

holders.

5. Exception Handling Logic java try { risky(); } catch (IllegalArgumentException | NullPointerException e) { // multi-catch log(e); } catch (Exception e) { throw new RuntimeException("context", e); // preserve cause } finally { cleanup(); // always runs } // Try-with-resources โ€” auto-closes try (var reader = Files.newBufferedReader(path)) {

7. Collections Quick Reference

Operation ArrayList HashMap HashSet

Add O(1)* O(1) O(1)

Get / Contains O(1) by index / O(n) search O(1) O(1)

Remove O(n) O(1) O(1)

Iterate for-each entrySet() / keySet() for-each

*Amortized. TreeMap/TreeSet are O(log n) for all ops but keep sorted order.