0% found this document useful (0 votes)
2 views30 pages

CS Fundamentals Java Python

This comprehensive reference guide covers essential computer science concepts and programming fundamentals, focusing on Java and Python. Topics include binary representation, data structures, algorithms, object-oriented programming, and error handling, with practical code examples. The guide serves as a valuable resource for understanding the software development lifecycle and core programming principles.

Uploaded by

khilafatkingwing
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views30 pages

CS Fundamentals Java Python

This comprehensive reference guide covers essential computer science concepts and programming fundamentals, focusing on Java and Python. Topics include binary representation, data structures, algorithms, object-oriented programming, and error handling, with practical code examples. The guide serves as a valuable resource for understanding the software development lifecycle and core programming principles.

Uploaded by

khilafatkingwing
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Science

Fundamentals
A Comprehensive Reference Guide

With Java & Python Code Examples

This guide covers the core concepts of computer science and programming — from binary representation and
algorithm design to object-oriented programming, data structures, and file I/O — illustrated with side-by-side
Java and Python examples.

Binary & Data Variables & Types Control Flow Functions

OOP Data Structures Algorithms Error Handling

File I/O Recursion Complexity Memory Model


Computer Science Fundamentals — Java & Python CS Reference Guide

Table of Contents

1. Introduction to Computer Science


• What is Computer Science?
• Abstraction Layers
• The Software Development Lifecycle

2. Binary & Data Representation


• Binary, Octal & Hexadecimal
• Integer Encoding
• Floating-Point Numbers
• Characters & Unicode
• Boolean Logic

3. Variables, Types & Operators


• Primitive vs Reference Types
• Type Conversion
• Operators & Expressions

4. Control Flow
• Conditionals
• Loops
• Switch / Match Statements

5. Functions & Methods


• Defining Functions
• Parameters & Return Values
• Scope & Lifetime
• Lambda / Anonymous Functions

6. Recursion
• Base & Recursive Cases
• Call Stack
• Classic Examples

7. Object-Oriented Programming
• Classes & Objects
• Encapsulation
• Inheritance
• Polymorphism
• Interfaces & Abstract Classes

8. Core Data Structures


• Arrays & Lists

Page 2
Computer Science Fundamentals — Java & Python CS Reference Guide

• Stacks & Queues


• Hash Maps / Dictionaries
• Sets
• Linked Lists
• Trees

9. Algorithms & Complexity


• Big-O Notation
• Sorting Algorithms
• Searching Algorithms
• Divide & Conquer

10. Error Handling & Exceptions


• Try/Catch/Finally
• Custom Exceptions
• Best Practices

11. File I/O


• Reading Files
• Writing Files
• Working with Paths

12. Memory & the Execution Model


• Stack vs Heap
• Garbage Collection
• Pass by Value vs Reference

Page 3
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 1 — Introduction to Computer Science

1.1 What is Computer Science?


Computer Science (CS) is the systematic study of computation — the processes, structures, and algorithms
that underpin how computers store, process, and communicate information. CS spans a wide spectrum: from
pure mathematics and logic (discrete mathematics, computability theory) through engineering disciplines
(operating systems, compilers, networking) to applied fields (artificial intelligence, databases, human-computer
interaction).
Two central languages in modern CS education and industry are Java and Python. Java is statically typed,
compiled to JVM bytecode, and prized for performance and reliability in large systems. Python is dynamically
typed, interpreted, and celebrated for readability and rapid prototyping.

1.2 Abstraction Layers


Modern computing is built on layers of abstraction, each hiding complexity from the layer above:
• Hardware — transistors, logic gates, circuits.
• Machine code — raw binary instructions executed by the CPU.
• Assembly language — human-readable mnemonics for machine instructions.
• Operating system — manages hardware resources (memory, I/O, processes).
• High-level languages (Java, Python) — human-readable syntax compiled or interpreted to machine code.
• Applications — programs built with high-level languages.

1.3 The Software Development Lifecycle


• Requirements — understand what the software must do.
• Design — architecture, data models, algorithms.
• Implementation — write and review code.
• Testing — unit tests, integration tests, system tests.
• Deployment — ship the software to users.
• Maintenance — fix bugs, add features, refactor.

Page 4
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 2 — Binary & Data Representation

2.1 Numeral Systems


Computers store everything as binary (base-2) values — sequences of 0s and 1s called bits. Eight bits form a
byte. Programmers also use octal (base-8) and hexadecimal (base-16) as compact representations of binary
data.

Base Name Digits Example (decimal 255)

2 Binary 0, 1 11111111

8 Octal 0–7 377

10 Decimal 0–9 255

16 Hexadecimal 0–9, A–F FF

Literals in Java vs Python


JAVA PYTHON
int bin = 0b11111111; // 255 bin_val = 0b11111111 # 255
int oct = 0377; // 255 oct_val = 0o377 # 255
int hex = 0xFF; // 255 hex_val = 0xFF # 255
[Link]([Link] print(bin(255)) # '0b11111111'
(255)); print(hex(255)) # '0xff'
[Link]([Link](25
5));

2.2 Integer Encoding


Integers are stored in a fixed number of bits. For a n-bit unsigned integer the range is 0 … 2n−1. For signed
integers, two's complement encoding is standard: the most-significant bit represents a negative weight, giving a
range of −2n−1 … 2n−1−1.
Java has fixed-width primitives: byte (8-bit), short (16-bit), int (32-bit), long (64-bit). Python integers are
arbitrary precision — they never overflow.

2.3 Floating-Point Numbers


Real numbers are approximated using the IEEE 754 standard. A 64-bit double has 1 sign bit, 11 exponent bits,
and 52 mantissa bits, giving roughly 15–16 significant decimal digits of precision.

■ Note: Floating-point arithmetic is not exact. 0.1 + 0.2 ≠ 0.3 in most languages. Use integer arithmetic (e.g., cents
instead of dollars) or BigDecimal / [Link] for financial calculations.

JAVA PYTHON

Page 5
Computer Science Fundamentals — Java & Python CS Reference Guide

double d = 0.1 + 0.2; d = 0.1 + 0.2


[Link](d); // 0.3000000 print(d) # 0.3000000
0000000004 0000000004

import [Link]; from decimal import Decimal


BigDecimal a = new BigDecimal("0.1"); a = Decimal('0.1')
BigDecimal b = new BigDecimal("0.2"); b = Decimal('0.2')
[Link]([Link](b)); // 0.3 print(a + b) # 0.3

2.4 Characters & Unicode


Text is represented by mapping characters to integer code points. ASCII uses 7 bits for 128 characters.
Unicode defines over 140,000 characters across all writing systems. The dominant encoding is UTF-8, which
uses 1–4 bytes per character and is backward-compatible with ASCII.
JAVA PYTHON
char c = 'A'; c = 'A'
[Link]((int) c); // 65 print(ord(c)) # 65
[Link]('\u0041'); // A print(chr(65)) # 'A'
String s = "Hello, World!"; s = 'Hello, World!'
[Link]([Link]()); // 13 print(len(s)) # 13

2.5 Boolean Logic


Boolean algebra deals with values true and false and three fundamental operations: AND, OR, NOT. All digital
logic circuits and conditional expressions are built from these.

Operation Java Python Result (T=True, F=False)

AND a && b a and b T only when both T

OR a || b a or b T when at least one T

NOT !a not a Negates the value

XOR a^b a^b T when exactly one T

Page 6
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 3 — Variables, Types & Operators

3.1 Primitive vs Reference Types


In Java, variables hold either a primitive value (stored directly in memory) or a reference (a pointer to an
object on the heap). Python has no primitives — everything is an object, but CPython caches small integers and
interned strings for performance.

Type Java Python Notes

Integer int, long int Python int is arbitrary precision

Float float, double float Both IEEE 754 double

Boolean boolean bool True/False (capitalized in Python)

Character char str (len 1) Python has no char type

String String str Immutable in both

Array int[] list Java arrays fixed size

Null null None Absence of value

3.2 Variable Declaration & Type Inference


JAVA PYTHON
// Explicit types (required pre-Java 10) # Dynamic typing – no declarations
int age = 25; age = 25
double price = 9.99; price = 9.99
boolean isReady = true; is_ready = True
String name = "Alice"; name = 'Alice'

// Type inference (Java 10+) # Type hints (optional, Python 3.5+)


var score = 100; // inferred int age: int = 25
var message = "Hi!"; // inferred String price: float = 9.99
name: str = 'Alice'

3.3 Type Conversion


JAVA PYTHON

Page 7
Computer Science Fundamentals — Java & Python CS Reference Guide

// Widening (automatic) # Python converts explicitly


int i = 42; i = 42
double d = i; // 42.0 d = float(i) # 42.0

// Narrowing (explicit cast) x = 9.7


double x = 9.7; n = int(x) # 9 (truncated)
int n = (int) x; // 9 (truncated)
# String conversions
// String conversions s = str(42) # '42'
String s = [Link](42); k = int('42') # 42
int k = [Link]("42");

3.4 Operators
Category Java Python Notes

Arithmetic + - * / % ** + - * / % ** ** = power (Python); [Link]() Java

Integer div 5/2 → 2 5 // 2 → 2 Java int÷int truncates; Python //

Comparison == != < > <= >= == != < > <= >= Java == on objects checks reference

Identity == (refs) is / is not Python 'is' checks object identity

Logical && || ! and or not Short-circuit in both

Bitwise & | ^ ~ << >> >>> & | ^ ~ << >> Java >>> unsigned right-shift

String concat + (overloaded) + or f-string Use StringBuilder for loops (Java)

String Formatting
JAVA PYTHON
String name = "Bob"; name = 'Bob'
int age = 30; age = 30

// Concatenation # Concatenation
String s1 = "Name: " + name; s1 = 'Name: ' + name

// [Link] # % formatting (legacy)


String s2 = [Link]( s2 = 'Name: %s, Age: %d' % (name, age)
"Name: %s, Age: %d", name, age);
# f-string (Python 3.6+) – preferred
// Text blocks (Java 15+) s3 = f'Name: {name}, Age: {age}'
String json = """
{ \"name\": \"%s\" } # .format()
""".formatted(name); s4 = 'Name: {}, Age: {}'.format(name, age
)

Page 8
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 4 — Control Flow

4.1 Conditionals
Conditionals allow a program to execute different code branches depending on run-time conditions. Both Java
and Python use if / else if / else (spelled elif in Python).
JAVA PYTHON
int score = 75; score = 75

if (score >= 90) { if score >= 90:


[Link]("A"); print('A')
} else if (score >= 80) { elif score >= 80:
[Link]("B"); print('B')
} else if (score >= 70) { elif score >= 70:
[Link]("C"); print('C')
} else { else:
[Link]("F"); print('F')
}
# Conditional expression (ternary)
// Ternary operator result = 'Pass' if score >= 70 else 'Fail
String pass = (score >= 70) ? "Pass" : "F '
ail";

4.2 Loops
For loops
JAVA PYTHON
// Traditional for loop # Range-based for loop
for (int i = 0; i < 5; i++) { for i in range(5):
[Link](i); print(i)
}
# Iterate over a list
// Enhanced for-each nums = [10, 20, 30]
int[] nums = {10, 20, 30}; for n in nums:
for (int n : nums) { print(n)
[Link](n);
} # enumerate gives index + value
for i, n in enumerate(nums):
// Range via IntStream print(i, n)
[Link]
.range(0, 5) # range(start, stop, step)
.forEach([Link]::println); for i in range(0, 10, 2):
print(i) # 0 2 4 6 8

While loops
JAVA PYTHON

Page 9
Computer Science Fundamentals — Java & Python CS Reference Guide

int n = 1; n = 1
while (n <= 5) { while n <= 5:
[Link](n); print(n)
n++; n += 1
}
# Python has no do-while; emulate:
// do-while (executes at least once) x = 0
int x = 0; while True:
do { print(x)
[Link](x); x += 1
x++; if x >= 3:
} while (x < 3); break

Loop Control Statements

Statement Java Python Effect

Break break break Exit innermost loop immediately

Continue continue continue Skip to next iteration

Return return return Exit entire function

Labeled label: …break label; N/A (use flags) Break outer loop (Java only)

4.3 Switch / Match Statements


JAVA PYTHON
// Java switch expression (Java 14+) # Python match-case (Python 3.10+)
String day = "MON"; day = 'MON'
String type = switch (day) { match day:
case "SAT", "SUN" -> "Weekend"; case 'SAT' | 'SUN':
case "MON","TUE", result = 'Weekend'
"WED","THU", case ('MON'|'TUE'|'WED'
"FRI" -> "Weekday"; |'THU'|'FRI'):
default -> "Unknown"; result = 'Weekday'
}; case _:
[Link](type); result = 'Unknown'
print(result)

Page 10
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 5 — Functions & Methods

5.1 Defining Functions


A function (called a method in Java) encapsulates a reusable block of code. It may accept parameters
(inputs) and return a value (output). Functions are the primary mechanism for code reuse and abstraction.
JAVA PYTHON
// Java – must be inside a class # Python – top-level or inside class
public static int add(int a, int b) { def add(a, b):
return a + b; return a + b
}
# No return value → returns None
// Void method (no return value) def greet(name):
public static void greet(String name) { print(f'Hi {name}')
[Link]("Hi " + name);
} # Calling
total = add(3, 4) # 7
// Calling greet('Alice') # Hi Alice
int sum = add(3, 4); // 7
greet("Alice"); // Hi Alice

5.2 Default & Keyword Arguments


JAVA PYTHON
// Java: overloading for defaults # Python: default parameter values
public static void connect( def connect(host, port=80):
String host, int port) { print(f'{host}:{port}')
[Link](host + ":" + port)
; connect('[Link]') # :80
} connect('[Link]', 443) # :443
public static void connect(String host){
connect(host, 80); // default port # Keyword arguments
} connect(port=443, host='[Link]')

5.3 Variable-Length Arguments


JAVA PYTHON
// Varargs in Java # *args – positional varargs
public static int sum(int... nums) { def total(*nums):
int total = 0; return sum(nums)
for (int n : nums) total += n;
return total; print(total(1, 2, 3, 4)) # 10
}
[Link](sum(1,2,3,4)); // 10 # **kwargs – keyword varargs
def show(**kw):
for k, v in [Link]():
print(f'{k} = {v}')

Page 11
Computer Science Fundamentals — Java & Python CS Reference Guide

5.4 Lambda / Anonymous Functions


JAVA PYTHON
// Java lambda (functional interface) # Python lambda
import [Link]; square = lambda x: x * x
print(square(5)) # 25
Function<Integer,Integer> square =
x -> x * x; # Used in sort
[Link]([Link](5)); // 2 names = ['Charlie', 'Alice', 'Bob']
5 [Link](key=lambda n: n)

// Used in sort # Or use a named function


List<String> names = new ArrayList<>( [Link](key=[Link])
[Link]("Charlie","Alice","Bob"));
[Link]((a, b) -> [Link](b));

5.5 Scope & Lifetime


Variables have a scope (where they are visible) and a lifetime (how long they exist in memory).
• Local scope — variable declared inside a function, only accessible there.
• Global scope — variable at module/class level, accessible everywhere.
• Block scope — Java creates new scope inside {}, Python does NOT (if/for bodies do not create new scope).
JAVA PYTHON
int x = 10; // class/local level x = 10 # module-level (global)

public static void demo() { def demo():


int y = 20; // local to method y = 20 # local
[Link](x); // OK (if stat print(x) # OK (reads global)
ic field) print(y) # OK
[Link](y); // OK
} # To modify global inside function:
// y is not accessible here def increment():
global x
x += 1

Page 12
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 6 — Recursion

6.1 Base & Recursive Cases


A recursive function calls itself with a simpler version of the same problem until it reaches a base case that
can be solved directly. Every recursive function must have at least one base case — without it, the function
recurses infinitely and causes a stack overflow.

6.2 Factorial (Classic Example)


JAVA PYTHON
public static long factorial(int n) { def factorial(n):
// Base case # Base case
if (n <= 1) return 1; if n <= 1:
// Recursive case return 1
return n * factorial(n - 1); # Recursive case
} return n * factorial(n - 1)

[Link](factorial(5)); // 120 print(factorial(5)) # 120

6.3 The Call Stack


Each function call pushes a stack frame on the call stack holding local variables and the return address. Deep
recursion can exhaust stack space (Java default ~500–1000 frames; Python default 1000 frames). Tail
recursion can be optimised by some compilers, but Python does not perform this optimisation — prefer
iteration for very deep problems.

6.4 Fibonacci
JAVA PYTHON
// Naive O(2^n) recursion # Naive O(2^n) recursion
public static int fib(int n) { def fib(n):
if (n <= 1) return n; if n <= 1: return n
return fib(n-1) + fib(n-2); return fib(n-1) + fib(n-2)
}
# Memoized with @cache (Python 3.9+)
// Memoized O(n) from functools import cache
Map<Integer,Long> memo = new HashMap<>();
public static long fibMemo(int n) { @cache
if (n <= 1) return n; def fib_fast(n):
return [Link](n, if n <= 1: return n
k -> fibMemo(k-1) + fibMemo(k-2)) return fib_fast(n-1) + fib_fast(n-2)
;
}

6.5 Binary Search (Recursive)


JAVA PYTHON

Page 13
Computer Science Fundamentals — Java & Python CS Reference Guide

public static int bSearch( def b_search(arr, lo, hi, t):


int[] arr, int lo, int hi, int t) if lo > hi:
{ return -1
if (lo > hi) return -1; mid = (lo + hi) // 2
int mid = (lo + hi) / 2; if arr[mid] == t:
if (arr[mid] == t) return mid; return mid
if (arr[mid] < t) return bSearch(arr if arr[mid] < t:
, mid+1, hi, t); return b_search(arr, mid+1, hi, t
return bSearch(arr, lo, mid-1, t); )
} return b_search(arr, lo, mid-1, t)

Page 14
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 7 — Object-Oriented Programming

7.1 Classes & Objects


A class is a blueprint that defines state (fields/attributes) and behaviour (methods). An object (instance) is a
concrete realisation of that blueprint in memory. OOP organises programs around data rather than logic,
making large codebases easier to understand and maintain.
JAVA PYTHON
public class Dog { class Dog:
// Fields (state) # Constructor
private String name; def __init__(self, name, age):
private int age; [Link] = name
[Link] = age
// Constructor
public Dog(String name, int age) { # Method
[Link] = name; def bark(self):
[Link] = age; print(f'{[Link]}: Woof!')
}
def __repr__(self):
// Method (behaviour) return f'Dog({[Link]!r}, {self
public void bark() { .age})'
[Link](name + ": Woof
!"); # Instantiation
} rex = Dog('Rex', 3)
[Link]() # Rex: Woof!
public String getName() { return name print(rex) # Dog('Rex', 3)
; }
}

// Instantiation
Dog rex = new Dog("Rex", 3);
[Link](); // Rex: Woof!

7.2 Encapsulation
Encapsulation hides internal state and exposes only a controlled public interface. In Java, fields are typically
marked private with public getters/setters. Python uses naming conventions: _protected and __private
(name-mangled), and @property decorators.
JAVA PYTHON

Page 15
Computer Science Fundamentals — Java & Python CS Reference Guide

private double balance = 0; class BankAccount:


def __init__(self):
public void deposit(double amount) { self.__balance = 0.0
if (amount > 0) balance += amount;
} def deposit(self, amount):
if amount > 0:
public double getBalance() { self.__balance += amount
return balance;
} @property
def balance(self):
return self.__balance

7.3 Inheritance
Inheritance lets a subclass reuse and extend the behaviour of a superclass. Java uses extends; Python
passes the parent class in the class definition. Both support calling the parent implementation via super().
JAVA PYTHON
public class Animal { class Animal:
protected String name; def __init__(self, name):
public Animal(String name) { [Link] = name
[Link] = name;
} def speak(self):
public String speak() { return '...'
return "...";
}
} class Cat(Animal):
def __init__(self, name):
public class Cat extends Animal { super().__init__(name)
public Cat(String name) {
super(name); def speak(self):
} return f'{[Link]}: Meow!'
@Override
public String speak() { c = Cat('Whiskers')
return name + ": Meow!"; print([Link]()) # Whiskers: Meow!
}
}

7.4 Polymorphism
Polymorphism ('many forms') allows objects of different types to be treated through a common interface.
Runtime polymorphism (method overriding) means the correct method is dispatched at runtime based on the
actual object type.
JAVA PYTHON

Page 16
Computer Science Fundamentals — Java & Python CS Reference Guide

Animal[] animals = { animals = [Dog('Rex', 3), Cat('Mia')]


new Dog("Rex", 3),
new Cat("Mia"), for a in animals:
}; # Python is dynamically typed –
# duck typing applies naturally
for (Animal a : animals) { print([Link]())
// Calls [Link]() or [Link]()
[Link]([Link]());
}

7.5 Interfaces & Abstract Classes


Concept Java Python

Interface interface Printable { void print(); } ABC with @abstractmethod

Abstract class abstract class Shape { abstract double area();


class Shape(ABC):
} @abstractmethod def area

Multiple inherit Implements multiple interfaces class C(A, B): — MRO resolves order

Concrete class Must implement all interface methods Must implement all abstract methods

Page 17
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 8 — Core Data Structures

8.1 Arrays & Lists


An array stores elements of the same type in contiguous memory, enabling O(1) random access by index. Java
arrays have a fixed size; Python lists are dynamic arrays that resize automatically.
JAVA PYTHON
// Fixed array # Python list is dynamic
int[] arr = {10, 20, 30, 40}; lst = [10, 20, 30, 40]
[Link](arr[2]); // 30 print(lst[2]) # 30
[Link]([Link]); // 4 print(len(lst)) # 4

// Dynamic list [Link](50) # add to end


List<Integer> list = new ArrayList<>(); [Link](1, 15) # insert at index
[Link](10); [Link](20); [Link](30); [Link](20) # remove by value
[Link]([Link](20)); [Link]() # in-place sort
[Link](list); lst2 = sorted(lst) # new sorted list

8.2 Stacks & Queues


A stack is a LIFO (Last In, First Out) structure — the most recently pushed item is the first to be popped. A
queue is FIFO (First In, First Out). Both are used pervasively in algorithms (DFS, BFS, undo systems,
scheduling).
JAVA PYTHON
// Stack via Deque from collections import deque
Deque<Integer> stack = new ArrayDeque<>()
; # Stack (use list or deque)
[Link](1); [Link](2); [Link]( stack = []
3); [Link](1); [Link](2); stack.a
[Link]([Link]()); // 3 ppend(3)
print([Link]()) # 3 (LIFO)
// Queue via Deque
Deque<Integer> queue = new ArrayDeque<>() # Queue (use deque for O(1) popleft)
; queue = deque([1, 2, 3])
[Link](1); [Link](2); [Link] print([Link]()) # 1 (FIFO)
er(3);
[Link]([Link]()); // 1

8.3 Hash Maps / Dictionaries


A hash map (Java) / dictionary (Python) stores key-value pairs with O(1) average-case lookup, insertion, and
deletion. Internally it uses a hash function to compute a bucket index for each key.
JAVA PYTHON

Page 18
Computer Science Fundamentals — Java & Python CS Reference Guide

Map<String,Integer> freq = new HashMap<>( freq = {}


);
freq['apple'] = 3
[Link]("apple", 3); freq['banana'] = 1
[Link]("banana", 1);
# Get with default
// Get with default n = [Link]('cherry', 0)
int n = [Link]("cherry", 0);
# Iterate
// Iterate for key, val in [Link]():
for (var entry : [Link]()) { print(f'{key}: {val}')
[Link](
[Link]() + ": " + [Link] # Counter (frequency map shortcut)
Value()); from collections import Counter
} c = Counter(['a','b','a','c','a'])
print(c) # Counter({'a':3,'b':1,'c':1})

8.4 Sets
JAVA PYTHON
Set<String> s = new HashSet<>(); s = {'a', 'b', 'a'}
[Link]("a"); [Link]("b"); [Link]("a"); print(len(s)) # 2 (no duplicates)
[Link]([Link]()); // 2
# Set operations
// Set operations a = {1, 2, 3}
Set<Integer> a = [Link](1,2,3); b = {2, 3, 4}
Set<Integer> b = [Link](2,3,4); print(a & b) # intersection {2, 3}
// Intersection print(a | b) # union {1,2,3,4}
[Link]().filter(b::contains)... print(a - b) # difference {1}
print(a ^ b) # sym diff {1, 4}

8.5 Linked Lists


A linked list stores elements in nodes, each pointing to the next. Unlike arrays, insertion and deletion at the
head or tail are O(1), but random access is O(n). Java's LinkedList is doubly linked.
JAVA PYTHON
LinkedList<Integer> ll = new LinkedList<> # Manual singly-linked list node
(); class Node:
[Link](1); def __init__(self, val):
[Link](2); [Link] = val
[Link](3); [Link] = None
[Link]();
[Link](ll); // [2, 3] head = Node(1)
[Link] = Node(2)
[Link] = Node(3)

8.6 Trees
A binary tree has nodes each with up to two children (left, right). A binary search tree (BST) keeps left < root
< right, enabling O(log n) search in balanced trees. Trees model hierarchical data (file systems, expression

Page 19
Computer Science Fundamentals — Java & Python CS Reference Guide

trees, decision trees).


JAVA PYTHON
class TreeNode { class TreeNode:
int val; def __init__(self, val):
TreeNode left, right; [Link] = val
TreeNode(int v) { val = v; } [Link] = None
} [Link] = None

// In-order traversal (sorted for BST) # In-order traversal


void inOrder(TreeNode n) { def in_order(node):
if (n == null) return; if node is None:
inOrder([Link]); return
[Link]([Link] + " "); in_order([Link])
inOrder([Link]); print([Link], end=' ')
} in_order([Link])

Page 20
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 9 — Algorithms & Complexity

9.1 Big-O Notation


Big-O notation describes how the runtime (or space usage) of an algorithm scales with input size n as n → ∞.
We drop constant factors and lower-order terms and focus on the worst-case dominant term.

Big-O Name Example n=1000 ops (approx)

O(1) Constant Array index access 1

O(log n) Logarithmic Binary search 10

O(n) Linear Linear search 1,000

O(n log n) Linearithmic Merge sort, Heap sort 10,000

O(n²) Quadratic Bubble/Insertion sort 1,000,000

O(2^n) Exponential Naive Fibonacci 10^300

O(n!) Factorial Permutation generation Astronomical

9.2 Sorting Algorithms


Bubble Sort — O(n²)
JAVA PYTHON
public static void bubbleSort(int[] a) { def bubble_sort(a):
int n = [Link]; n = len(a)
for (int i = 0; i < n-1; i++) for i in range(n - 1):
for (int j = 0; j < n-i-1; j++) for j in range(n - i - 1):
if (a[j] > a[j+1]) { if a[j] > a[j+1]:
int tmp = a[j]; a[j], a[j+1] = a[j+1], a[
a[j] = a[j+1]; a[j+1] = tmp; j]
} return a
}

Merge Sort — O(n log n)


JAVA PYTHON

Page 21
Computer Science Fundamentals — Java & Python CS Reference Guide

public static int[] mergeSort(int[] a) { def merge_sort(a):


if ([Link] <= 1) return a; if len(a) <= 1:
int mid = [Link] / 2; return a
int[] L = mergeSort([Link] mid = len(a) // 2
e(a,0,mid)); L = merge_sort(a[:mid])
int[] R = mergeSort([Link] R = merge_sort(a[mid:])
e(a,mid,[Link])); return merge(L, R)
return merge(L, R);
} def merge(L, R):
static int[] merge(int[] L, int[] R) { result, i, j = [], 0, 0
int[] res = new int[[Link]+[Link] while i < len(L) and j < len(R):
]; if L[i] <= R[j]:
int i=0, j=0, k=0; [Link](L[i]); i += 1
while(i<[Link] && j<[Link]) else:
res[k++]=(L[i]<=R[j])?L[i++]:R[j+ [Link](R[j]); j += 1
+]; [Link](L[i:])
while(i<[Link]) res[k++]=L[i++]; [Link](R[j:])
while(j<[Link]) res[k++]=R[j++]; return result
return res;
}

Built-in Sort (preferred)


JAVA PYTHON
int[] arr = {5, 2, 8, 1, 9}; arr = [5, 2, 8, 1, 9]
[Link](arr); // primit [Link]() # in-place
ive sorted_arr = sorted(arr) # new list

List<String> names = new ArrayList<>( names = ['Charlie','Alice','Bob']


[Link]("Charlie","Alice","Bob")); [Link]()
[Link](names); [Link](reverse=True)
[Link]([Link]()); # Custom key
[Link](key=lambda x: len(x))

9.3 Searching Algorithms


Linear Search — O(n)
JAVA PYTHON
public static int linearSearch(int[] a, i def linear_search(a, target):
nt t){ for i, val in enumerate(a):
for (int i = 0; i < [Link]; i++) if val == target:
if (a[i] == t) return i; return i
return -1; return -1
}
# Or simply:
idx = [Link](target) if target in arr
else -1

Binary Search — O(log n)


JAVA PYTHON

Page 22
Computer Science Fundamentals — Java & Python CS Reference Guide

public static int binarySearch(int[] a, i def binary_search(a, target):


nt t){ lo, hi = 0, len(a) - 1
int lo = 0, hi = [Link] - 1; while lo <= hi:
while (lo <= hi) { mid = (lo + hi) // 2
int mid = lo + (hi - lo) / 2; if a[mid] == target:
if (a[mid] == t) return mid; return mid
if (a[mid] < t) lo = mid + 1; elif a[mid] < target:
else hi = mid - 1; lo = mid + 1
} else:
return -1; hi = mid - 1
} return -1

// Built-in (array must be sorted) # Built-in (bisect module)


[Link](arr); import bisect
int idx = [Link](arr, t); idx = bisect.bisect_left(sorted_arr, targ
et)

Page 23
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 10 — Error Handling & Exceptions

10.1 Exceptions Hierarchy


An exception is an object representing an error condition. When thrown (raised), normal execution stops and
the runtime unwinds the call stack looking for a matching handler. If none is found, the program terminates.
• In Java, Throwable is the root class. Error (JVM-level problems, usually unrecoverable) and Exception
(application errors) extend it. Checked exceptions must be declared or handled; unchecked
(RuntimeException) need not be.
• In Python, all exceptions inherit from BaseException → Exception. No checked/unchecked distinction.

10.2 Try / Catch / Finally


JAVA PYTHON
try { try:
int result = 10 / 0; result = 10 / 0
} catch (ArithmeticException e) { except ZeroDivisionError as e:
[Link]("Div by zero: " + print(f'Div by zero: {e}')
[Link]()); except Exception as e:
} catch (Exception e) { print(f'Unexpected: {e}')
[Link]("Unexpected: " + e else:
); print('No exception occurred')
} finally { finally:
[Link]("Always runs"); print('Always runs')
}

10.3 Custom Exceptions


JAVA PYTHON
public class InsufficientFundsException class InsufficientFundsError(ValueError):
extends RuntimeException { def __init__(self, amount):
private final double amount; [Link] = amount
public InsufficientFundsException(dou super().__init__(f'Need {amount}
ble a) { more')
super("Need " + a + " more");
[Link] = a;
}
public double getAmount() { return am
ount; } # Raising
} raise InsufficientFundsError(50.0)

// Throwing
throw new InsufficientFundsException(50.0
);

10.4 Try-with-resources / Context Managers


JAVA PYTHON

Page 24
Computer Science Fundamentals — Java & Python CS Reference Guide

// Auto-closes resource on exit # with-statement auto-closes file


try (BufferedReader br = new BufferedRead try:
er( with open('[Link]', 'r') as f:
new FileReader("[Link]"))) { for line in f:
String line; print(line, end='')
while ((line = [Link]()) != null except FileNotFoundError as e:
) print(f'File not found: {e}')
[Link](line);
} catch (IOException e) {
[Link]();
}

Page 25
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 11 — File I/O

11.1 Reading Files


JAVA PYTHON
import [Link].*; # Read all at once
with open('[Link]', 'r') as f:
// Read all lines content = [Link]()
Path p = [Link]("[Link]");
List<String> lines = [Link](p # Read line by line (memory efficient)
); with open('[Link]', 'r') as f:
[Link]([Link]::println); for line in f:
print(line, end='')
// Read entire file as String
String content = [Link](p); # Read all lines into a list
lines = open('[Link]').readlines()

11.2 Writing Files


JAVA PYTHON
import [Link].*; # Write (overwrites existing file)
with open('[Link]', 'w') as f:
// Write with BufferedWriter [Link]('Hello, File!\n')
try (BufferedWriter bw = new BufferedWrit [Link]('Line 2\n')
er(
new FileWriter("[Link]"))) { # Append mode
[Link]("Hello, File!"); with open('[Link]', 'a') as f:
[Link](); [Link]('Line 3\n')
[Link]("Line 2");
} # writelines
lines = ['Line 1\n', 'Line 2\n']
// Write all lines (NIO) open('[Link]','w').writelines(lines)
[Link]([Link]("[Link]"),
[Link]("Line 1","Line 2"));

11.3 Working with Paths


JAVA PYTHON

Page 26
Computer Science Fundamentals — Java & Python CS Reference Guide

import [Link].*; from pathlib import Path

Path p = [Link]("/home/user/docs","repor p = Path('/home/user/docs') / '[Link]


[Link]"); '
[Link]([Link]()); // r print([Link]) # [Link]
[Link] print([Link]) # /home/user/docs
[Link]([Link]()); // / print([Link]) # .txt
home/user/docs
# Check existence
// Check existence if [Link](): ...
if ([Link](p)) { ... }
# List directory
// List directory for child in Path('.').iterdir():
[Link]([Link](".")) print(child)
.forEach([Link]::println);

■ Note: Python's pathlib module (Python 3.4+) is the modern way to handle file paths in an OS-independent
manner. Prefer it over the older [Link] module.

Page 27
Computer Science Fundamentals — Java & Python CS Reference Guide

Chapter 12 — Memory & the Execution Model

12.1 Stack vs Heap


Programs use two primary regions of memory during execution:

Feature Stack Heap

Contents Local variables, return addresses Objects, arrays, dynamic data

Allocation Automatic (LIFO) Explicit (new / constructor)

Deallocation Automatic on function return Garbage collector (Java/Python)

Size Small (1–8 MB typical) Large (limited by RAM)

Speed Very fast Slower (GC overhead)

Thread safety Each thread has its own stack Shared; requires synchronisation

12.2 Garbage Collection


Both Java and Python use automatic garbage collection (GC) so programmers do not need to manually free
memory.
• Java uses a generational GC (Young/Old/Metaspace generations). Most objects die young and are collected
cheaply in the Young generation. Long-lived objects are promoted to the Old generation.
• Python (CPython) uses reference counting — each object tracks how many references point to it; when
count reaches zero it is freed immediately. A cyclic garbage collector handles reference cycles.

12.3 Pass by Value vs Pass by Reference


This is a common source of confusion. Both Java and Python are strictly pass-by-value, but what is passed
differs:
• Primitives (Java): a copy of the value is passed — the caller's variable is unaffected by changes inside the
method.
• Object references (Java & Python): a copy of the reference is passed. Mutating the object's contents is
visible to the caller; reassigning the local variable is not.
JAVA PYTHON

Page 28
Computer Science Fundamentals — Java & Python CS Reference Guide

// Primitive — caller unchanged # Immutable int — caller unchanged


static void doubleIt(int x) { x *= 2; } def double_it(x):
int a = 5; doubleIt(a); x *= 2
[Link](a); // still 5 a = 5; double_it(a)
print(a) # still 5
// Object — mutation is visible
static void addItem(List<Integer> lst) { # Mutable list — mutation is visible
[Link](99); def add_item(lst):
} [Link](99)
List<Integer> myList = new ArrayList<>(Li
[Link](1,2)); my_list = [1, 2]
addItem(myList); add_item(my_list)
[Link](myList); // [1, 2, 99] print(my_list) # [1, 2, 99]

12.4 Immutability
An immutable object cannot be changed after creation. Strings, integers, and tuples are immutable in Python.
Java Strings are also immutable (use StringBuilder for concatenation-heavy code). Immutability simplifies
reasoning about code and is essential for thread safety and use as hash-map keys.
JAVA PYTHON
// String is immutable in Java # str is immutable in Python
String s = "Hello"; s = 'Hello'
s = s + " World"; // new String object s = s + ' World' # new str object

// Efficient: StringBuilder # Efficient: join


StringBuilder sb = new StringBuilder(); parts = [str(i) for i in range(5)]
for (int i = 0; i < 5; i++) result = ''.join(parts) # '01234'
[Link](i);
String result = [Link](); // "01234" # Immutable tuple vs mutable list
t = (1, 2, 3) # tuple – immutable
l = [1, 2, 3] # list – mutable

Page 29
Computer Science Fundamentals — Java & Python CS Reference Guide

Quick Reference — Java vs Python at a Glance

Topic Java Python

Paradigm OOP + functional (Java 8+) Multi-paradigm

Typing Static + strong Dynamic + strong

Type declarations Required (or var) Optional hints

Execution Compiled → JVM bytecode Interpreted (CPython)

Entry point public static void main(String[] args) if __name__ == '__main__':

Print [Link](x) print(x)

String interpolation [Link]() or .formatted() f-string f'{x}'

Null/None null None

Boolean literals true / false True / False

List ArrayList<T> list []

Map HashMap<K,V> dict {}

Set HashSet<T> set {}

Array int[] / T[] list or array module

For each for (T x : collection) for x in collection:

Lambda x -> x * x lambda x: x * x

Exception base Exception Exception

File I/O [Link] / BufferedWriter open() / pathlib

Concurrency Thread, ExecutorService threading, asyncio

Package manager Maven / Gradle pip / conda

REPL jshell (Java 9+) python3

This guide has covered the foundational concepts every programmer needs: binary representation, types, control
flow, functions, OOP, data structures, algorithms, error handling, file I/O, and memory models — all illustrated with
parallel Java and Python examples. Master these building blocks and you will have a solid foundation for any
software engineering challenge.

Page 30

You might also like