Plus
$7.99 / month
- Nemotron Nano 12B VL
- Nemotron Nano 30B
- 20 AI credits/week
Save your current position in the course
Certificates are issued to Unlimited subscribers who finish a course. Your progress is saved either way — upgrade whenever you want yours.
Report a problem with this course via Discord
View available keyboard shortcuts
Reset all section and file completion progress
Welcome to the world of Computer Science! At its core, programming is not just about typing lines of text into a computer; it is the art of problem-solving. Imagine you are tasked with designing a system for a self-driving car, a high-frequency trading platform, or a simple mobile game. All these complex systems rely on the same fundamental building blocks: Algorithms and Objects.
In this unit, we will explore the foundational elements of the Java programming language. We begin by understanding how to give instructions to a computer through algorithms and how the computer translates our human-readable code into something it can execute. We will then dive into the way data is stored using variables and how we can manipulate that data using mathematical expressions. Finally, we will introduce the "Object-Oriented" nature of Java, where we learn to use pre-written blueprints (Classes) to create powerful tools (Objects) that can perform complex tasks with just a few lines of code. By the end of this chapter, you will be able to write programs that interact with users, perform precise calculations, and manipulate text—all while maintaining the rigorous logic required for college-level software development.
ArithmeticException).int, double, and boolean.= operator to store a value in a variable.(int)3.5)."Hello".\n) to represent non-printable or reserved characters.+= or *= that perform an operation and assign the result.new keyword.String).An algorithm is a precise set of instructions. In Java, we implement algorithms through sequencing. This means the computer starts at the first line of the main method and executes each line in order.
When you write code in an IDE (Integrated Development Environment), it must be compiled. The compiler checks for Syntax Errors—violations of Java's rules, such as a missing semicolon or a misspelled keyword. If syntax is perfect, the code runs. However, it may still have:
Java is a "strongly typed" language. You must declare a variable's type before using it.
true or false.Variables of Reference Types do not hold the actual data; they hold a "pointer" or memory address to where the object is stored.
We use System.out.print() to display text. System.out.println() does the same but moves the cursor to a new line afterward.
Escape Sequences allow us to print special characters:
\" : Prints a double quote.\\ : Prints a backslash.\n : Moves to a new line.Arithmetic Rules:
ints, the decimal portion is truncated (dropped).double, the result is a double.The assignment operator = evaluates the right side first, then stores the result in the variable on the left.
int x = 10 + 5; // x becomes 15
To get input, we use the Scanner class from the java.util package.
Scanner input = new Scanner(System.in);
int age = input.nextInt();
Casting is the manual conversion of types.
(double) 5 becomes 5.0.(int) 5.9 becomes 5 (truncation).Rounding Rule: To round a positive double $x$ to the nearest integer:
$$rounded = (int)(x + 0.5)$$
Integer Limits:
An int is 32-bit.
Integer.MIN_VALUE = $-2^{31}$Integer.MAX_VALUE = $2^{31} - 1$Integer.MAX_VALUE, you get Integer Overflow, and the value wraps around to Integer.MIN_VALUE.Shorthand makes code cleaner:
| Operator | Equivalent to |
|---|---|
x += 5 |
x = x + 5 |
x -= 2 |
x = x - 2 |
x *= 3 |
x = x * 3 |
x /= 4 |
x = x / 4 |
x %= 2 |
x = x % 2 |
x++ |
x = x + 1 |
x-- |
x = x - 1 |
A Library is a collection of pre-written classes. The API (Application Programming Interface) is the manual that tells you how to use them. For example, java.lang is a package included automatically that contains the Math and String classes.
// : Single-line comment./* ... */ : Multi-line block comment./** ... */ : Javadoc comment for documentation.Preconditions: What must be true before calling a method (e.g., "radius must be positive").
Postconditions: What the method guarantees after it finishes (e.g., "returns the area of the circle").
A Method Signature is defined by: methodName(parameterTypes).
The Math class contains static methods. You don't need to create a Math object; you just call them using Math.methodName().
| Method | Return Type | Description |
|---|---|---|
Math.abs(x) |
int or double |
Absolute value $ |
Math.pow(b, e) |
double |
$b^e$ |
Math.sqrt(x) |
double |
$\sqrt{x}$ |
Math.random() |
double |
Returns $r$ where $0.0 \le r < 1.0$ |
Random Integer Formula:
To get a random integer in the range $[low, high]$:
$$result = (int)(Math.random() * (high - low + 1) + low)$$
An object is an instance of a class.
Rectangle box; (Creates a reference variable, currently null).box = new Rectangle(5, 10); (Calls the Constructor to allocate memory and initialize attributes).Instance Methods are called on the object: box.getArea();. If you call a method on a null reference, you get a NullPointerException.
String objects are sequences of characters. They are immutable.
Essential String Methods:
| Method | Description |
|---|---|
int length() |
Number of characters. |
String substring(int from, int to) |
Returns string from from to to-1. |
String substring(int from) |
Returns string from from to the end. |
int indexOf(String str) |
Index of first occurrence of str, or -1. |
boolean equals(String other) |
Checks if contents are identical. |
int compareTo(String other) |
$0$ if equal, negative if this < other, positive if this > other. |
int result = 10 / 4;
System.out.println(result);
Explanation: $10 / 4 = 2.5$. Since both are int, the result is truncated to 2.
double result = 10 / 4.0;
Explanation: Since 4.0 is a double, the integer 10 is promoted to 10.0. Result is $2.5$.
int remainder = 17 % 5;
Explanation: $17 = (3 \times 5) + 2$. The remainder is 2.
int result = -15 % 4;
Explanation: Java's modulus maintains the sign of the dividend. $-15 / 4 = -3$ remainder $-3$. Result is -3.
int val = 5 + 10 * 2 / 5;
Calculation:
9.System.out.println(0.1 + 0.2);
Explanation: Because doubles are stored in binary, simple decimals might result in values like 0.30000000000000004.
int big = Integer.MAX_VALUE + 1;
System.out.println(big);
Explanation: $2,147,483,647 + 1$ becomes $-2,147,483,648$ (the MIN_VALUE).
double money = 99.99;
int dollars = (int) money;
Explanation: dollars becomes 99. The .99 is deleted, not rounded.
double score = 85.7;
int roundedScore = (int)(score + 0.5);
Calculation: $85.7 + 0.5 = 86.2 \rightarrow (int)86.2 = 86$.
Scanner kb = new Scanner(System.in);
System.out.print("Enter radius: ");
double r = kb.nextDouble();
double area = Math.PI * Math.pow(r, 2);
Explanation: Reads a double from the user and calculates $\pi r^2$.
String s = "Score: " + 10 + 5;
Explanation: Evaluation is left-to-right. "Score: " + 10 becomes "Score: 10". Then "Score: 10" + 5 becomes "Score: 105".
String s = "Score: " + (10 + 5);
Explanation: Parentheses first. $10+5=15$. Result: "Score: 15".
System.out.println("Path: C:\\Users\\Name\n\"Hello\"");
Output:
Path: C:\Users\Name
"Hello"
int diff = Math.abs(10 - 25);
Result: $|-15| = 15$.
int side = (int) Math.sqrt(25);
Result: Math.sqrt(25) returns 5.0 (double), which is cast to the int 5.
int rand = (int)(Math.random() * 11);
Explanation: Math.random() is $[0.0, 1.0)$. Multiplying by 11 gives $[0.0, 11.0)$. Casting to int gives ${0, 1, 2, ..., 10}$.
int die = (int)(Math.random() * 6) + 1;
Calculation: $(int)([0.0, 6.0)) + 1 \rightarrow {0..5} + 1 \rightarrow {1..6}$.
String name = "Java";
int len = name.length();
Result: 4.
String fruit = "Pineapple";
String sub = fruit.substring(0, 4);
Result: "Pine". (Indices 0, 1, 2, 3 included; 4 is excluded).
String sub = "Pineapple".substring(4);
Result: "apple". (From index 4 to the end).
int idx = "Mississippi".indexOf("iss");
Result: 1. (It finds the first occurrence).
int idx = "Java".indexOf("python");
Result: -1.
String s1 = new String("Hi");
String s2 = new String("Hi");
boolean b1 = (s1 == s2); // false (different memory addresses)
boolean b2 = s1.equals(s2); // true (same text)
int res = "Apple".compareTo("Banana");
Result: Negative value (since "Apple" comes before "Banana" alphabetically).
int res = "Cat".compareTo("Cat");
Result: 0.
int x = 10;
x += 5; // 15
x /= 3; // 5
int count = 0;
count++;
count++;
Result: count is 2.
// In some class
public void printInfo(String name) { ... }
public void printInfo(int age) { ... }
Explanation: These methods have the same name but different signatures (different parameter types).
String s = null;
int len = s.length(); // CRASH!
double root = Math.sqrt(144);
Explanation: Called via the Class Name Math, not an object.
int x = 5 / 0; // CRASH!
/**
* @param x must be non-negative (Precondition)
*/
public void calculateSqrt(double x) { ... }
String s = "Hello";
s.toUpperCase();
System.out.println(s);
Explanation: Prints "Hello". toUpperCase() returns a new string; it doesn't change s. To change it, you must assign: s = s.toUpperCase();.
String a = "Blue";
String b = a;
a = "Red";
System.out.println(b);
Explanation: Prints "Blue". b was pointing to the original object. Changing a to point to a new object "Red" doesn't change where b points.
double val = (double) (1/4) * 10;
Explanation: 1/4 happens first inside parentheses, resulting in 0. (double)0 is 0.0. 0.0 * 10 is 0.0. Correct way: (double)1 / 4 * 10 which is 2.5.
Right-click any tab and choose Split screen to view it here.
Course Mastery Certificates require an active Unlimited subscription at the time of generation and 100% course completion. They recognise learning content completion only — not an accredited qualification, licence, or professional credential unless explicitly stated. edusolum may modify eligibility, design, and issuance requirements per its Terms of Service.