Java Programming Errors and Syntax Rules
Programming Fundamentals and Indexing
Computers in the room start indexing at 1, but standard programming index 0 is typically used.
Code files are identified by their name, such as
main dot Java.Error messages identify the specific file and the line number where the issue exists (e.g.,
main dot Java 6means the error is on line 6).
Compilation Errors
A compilation error occurs when the code cannot be built into a runnable program.
Binary Operators: These require two inputs (e.g., division requires a numerator and a denominator).
Bad Operand Types: An error occurs when a data type is incompatible with an operation, such as trying to divide an
intlike by astringlike "John Cena".Division in Java is an arithmetic operation and requires numerical data types for both inputs.
If a compilation error exists, the code never runs, and no output is produced.
Runtime Errors
These occur when the code compiles successfully and starts running but encounters a fatal issue during execution.
Infinite Loops: Logic that never terminates, such as a loop that continues "eating pizza" indefinitely.
Stack Overflow: This occurs during recursion when there is no end to the branch or base case, causing the recursion to go on forever.
Division by Zero: Attempting an integer division by will crash the program at runtime.
Execution Flow: Anything in the code that appears before the runtime error will execute (e.g., printing "hello"), but anything following the error will not occur.
Logic Errors
A logic error happens when the code runs to completion without crashing but produces incorrect results.
Example: A program designed to identify triangles that outputs "obtuse" for inputs of , , and (which should be a "right" triangle).
Causes: These can stem from incorrect calculations, improper rounding, or failing to follow the order of operations.
Java Syntax and Implicit Operations
Multiplication: Java requires explicit operators. Writing
4acin code will be interpreted as a single variable namedacrather than . All multiplication must use the*operator.Parentheses: In mathematical formulas like the quadratic formula, numerators and denominators must be explicitly wrapped in parentheses. For example, dividing by requires
/(2 * a)to avoid dividing by and then multiplying the result by .Range Logic: The mathematical notation 2 < x < 8 will not compile. It must be split into an explicit "and" statement:
2 < x && x < 8.
Questions & Discussion
Question: What is the difference between
public static voidandpublic static double?Response: If a method is marked as
void, it does not return a value. If it is marked asdouble, it must return a decimal (double) value. Use the specific data type (likeint,double, orstring) if you want to return a statement or value at the end of the method.