Java Fundamentals: Errors, Conventions, Data Types, and Operators – CS 101 – Study Notes
offline

Difficulty: Beginner | Prerequisites: None


Big Picture

This is the foundation of everything else in an introductory Java course. Before you can write methods, build objects, or debug complex programs, you need to understand how Java handles data, what the rules of the language look like, and what happens when you break them. If you are coming in cold, start here. These concepts appear on every exam and in every assignment from this point forward. You should already be comfortable with the idea that programming is writing instructions a computer executes line by line.


TL;DR

Java has strict rules about how you write code (conventions), how data is stored (types), and how calculations work (operators). Errors come in three flavours: compile, runtime, and logic. Understanding type conversion, integer division, and operator precedence will save you from the most common early mistakes.


Key Terms

Assignment operator (=)

The single equals sign in Java. It assigns the value on the right to the variable on the left. It does not test equality. Think of it as: "put this value into that box."

Compile error

An error caught by the Java compiler before the program runs, usually caused by incorrect syntax. In simple terms, the code is written wrong and Java refuses to translate it into something the computer can run.

Runtime error

An error that occurs while the program is running, such as dividing by zero or accessing an invalid index. Think of it as: "the code looked fine on paper, but something went wrong during execution."

Logic error (algorithmic error)

The program compiles and runs but produces the wrong result because the instructions themselves are flawed. In simple terms, the code does what you told it to do, not what you meant it to do.

Convention

A set of agreed-upon formatting and naming rules that make code readable and consistent. Not enforced by the compiler, but expected by other programmers (and your lecturer).

Identifier

A name given to a variable, method, or class. Must start with a letter, underscore (_), or dollar sign ($). Using an illegal character is a syntax error.

camelCase

The naming convention for variables and methods in Java. The first word is lowercase, each subsequent word starts with a capital letter (e.g., myVariableName).

Scope

The region of code where a variable is accessible. Think of it as: "where a variable lives and can be seen."

Local variable

A variable declared inside a method. It can only be used within that method.

Global variable (class-level / instance variable)

A variable declared outside any method but inside the class. It is accessible anywhere within the class.

final

A keyword that makes a variable's value immutable (unchangeable) once assigned. Useful for constants and avoiding hardcoded values scattered through your code.

Immutable

Cannot be changed after creation. In Java, String objects are immutable. If you need a different string, you create a new one.

Integer division

When you divide two integers in Java, the result is an integer. The decimal portion is truncated (chopped off), not rounded.

Truncation

Cutting off the decimal portion of a number, with no rounding. 7 / 2 gives 3, not 3.5.

Modulus (%)

The remainder operator. 7 % 2 gives 1. The result is always positive in Java when the dividend is positive.

Type conversion (implicit casting)

When you mix int and double in an expression, Java automatically converts the int to a double. The conversion happens per operator, affecting only the operands involved in that operation.

Casting (explicit)

Manually converting one type to another, e.g., (int) Math.pow(2, 3) converts the double result to an int.

Pre-increment / pre-decrement (++x / --x)

Increments or decrements the variable first, then returns the updated value.

Post-increment / post-decrement (x++ / x--)

Returns the current value first, then increments or decrements.

PEMDAS

The order of operations in expressions: Parentheses, Exponents, Multiplication/Division, Addition/Subtraction. In Java, method calls are evaluated before arithmetic operators.


Core Content

Errors in Java

  • Three categories: compile errors, runtime errors, and logic errors.

  • Syntax mistakes (missing semicolons, mismatched braces) fall under compile errors.

  • Logic errors are the hardest to find because the program runs without complaint but gives the wrong answer.

  • The compiler is your first line of defence. If it compiles, at least the syntax is sound.

Java Conventions and Style

  • Curly braces and bracket placement must be uniform throughout your code.

  • Use 3 spaces (or a tab) for indentation.

  • Leave a space after // in comments.

  • Leave a space before and after every operator (+, -, =, etc.).

  • Put a space between control-flow keywords and parentheses: for (), if (), while ().

  • Do not put a space when calling a method: myMethod(), not myMethod ().

  • Place variables and helper methods between the class declaration and the main method.

  • Use camelCase for variable and method names.

  • Identifiers must start with a letter, _, or $. Using a keyword as an identifier is a syntax error.

Data Types and Storage

  • Integers (int) take up less memory than doubles and are preferred when you do not need decimals.

  • An int value can be stored in a double variable (implicit widening), but not the other way around without an explicit cast.

  • When you concatenate a String with an int, the result is a String.

  • Math.pow() returns a double. To store the result as an int, cast it: (int) Math.pow(base, exp).

Operators and Arithmetic

  • Integer division truncates: 7 / 2 produces 3.

  • The modulus operator (%) gives the remainder: 17 % 5 produces 2.

  • Mixing int and double in the same expression promotes the result to double, but the conversion is per operator.

  • To extract digits from a number, use % 10 (last digit), / 10 (remove last digit), or % 100 (last two digits), and so on.

Scope

  • A local variable exists only inside the method where it is declared. Once that method finishes, the variable is gone.

  • A class-level (global) variable is declared outside methods but inside the class, and is accessible from any method in that class.

The final Keyword and Immutability

  • Declaring a variable as final prevents reassignment. This is how you create constants.

  • String in Java is immutable. You cannot modify a string in place; any operation that appears to change it creates a new String object.


Formulas / Key Syntax

int result = 7 / 2;          // result is 3 (truncated)
int remainder = 7 % 2;       // remainder is 1
double promoted = 7 / 2.0;   // promoted is 3.5 (one operand is double)
int power = (int) Math.pow(2, 3);  // cast double to int, result is 8

int x = 5;
System.out.println(x++);     // prints 5, then x becomes 6
System.out.println(++x);     // x becomes 7 first, then prints 7

Real-World Applications

Integer division and modulus are used everywhere in computing, from calculating how many full pages of results to display (integer division) to determining whether a year is a leap year (modulus). Coding conventions exist because professional codebases are read by dozens of people, and inconsistent style wastes everyone's time.


Common Misconceptions

  • Students often think = tests equality. It does not. = is assignment; == is equality comparison.

  • Students assume integer division rounds. It truncates. 7 / 2 is 3, not 4.

  • Students believe x++ and ++x are interchangeable. They are not, especially inside expressions or print statements. The order of the increment matters.

  • Students think final makes an object immutable. It only prevents reassignment of the variable. For objects, it means you cannot point the variable at a different object, but the object's internal state may still be modifiable (though String is a special case, as strings are immutable regardless).


Why It Matters / Exam Flags

⚠️ Integer division and truncation are among the most commonly tested topics. Know that 7 / 2 is 3, not 3.5.

⚠️ Pre-increment vs. post-increment appears in trace-the-output questions. Be able to walk through ++x vs. x++ inside a println.

⚠️ Scope questions will ask whether a variable declared inside a for loop can be used after the loop ends. It cannot.

⚠️ Convention questions may ask about proper identifier naming, spacing, and brace placement.


Quick Self-Test

  1. True or false: 9 / 2 evaluates to 4.5 in Java when both operands are int.

  1. Fill in the blank: A variable declared inside a method has ______ scope.

  1. True or false: String objects in Java can be modified after creation.

  1. Fill in the blank: The operator % returns the ______ of a division.

  1. True or false: ++x returns the value of x before incrementing it.

Answers: 1. False (it evaluates to 4). 2. Local. 3. False. 4. Remainder. 5. False (it increments first, then returns).


Practice Q&A

Q: What is the output of the following code?

int a = 10;
int b = 3;
System.out.println(a / b);
System.out.println(a % b);

A: The first line prints 3 (integer division truncates). The second line prints 1 (10 divided by 3 leaves a remainder of 1).

Q: What is the difference between a compile error and a logic error?

A: A compile error prevents the program from compiling at all, usually due to a syntax mistake. A logic error allows the program to compile and run, but it produces incorrect output because the algorithm or instructions are wrong.

Q: What does the final keyword do when applied to a variable?

A: It makes the variable's value immutable, meaning it cannot be reassigned after its initial assignment. This is used to create constants.

Q: If int x = 5;, what does System.out.println(x++); print, and what is the value of x afterwards?

A: It prints 5 (returns the current value first), and x becomes 6 afterwards.

Q: Why does "Score: " + 5 + 3 produce "Score: 53" rather than "Score: 8"?

A: String concatenation with + is evaluated left to right. "Score: " + 5 produces the string "Score: 5", and then "Score: 5" + 3 produces "Score: 53". To get 8, you would need parentheses: "Score: " + (5 + 3).


Connections to Other Topics

These fundamentals connect directly to control flow (loops and conditionals), where understanding operators and types is essential for writing correct boolean expressions. Scope becomes critical when you begin writing methods and classes, as you will need to know which variables are visible where. Type conversion reappears in object-oriented programming when you begin casting between object types.


Related Terms / Search Tags

Java errors, compile error vs runtime error, logic error, Java conventions, camelCase, Java scope, local variable, global variable, integer division, truncation, modulus operator, remainder, type conversion, implicit casting, explicit casting, pre-increment, post-increment, PEMDAS Java, final keyword, immutable, Java constants, assignment operator, identifier rules, CS 101 Java review