Unit 1.1: Algorithms and Errors
Algorithms

An algorithm is a set of code statements that you write as a program to solve a computational problem. It is a step-by-step, sequential process for solving problems. Once an algorithm is written, the computer executes it the exact same way every time it is run.
Consider the flowchart above. It visualizes the decision-making process for choosing an outfit. You check the weather (input), make decisions based on conditions (is it raining? is it cold?), and perform an action (wear specific clothes).
- An algorithm is a precise, sequential set of instructions to accomplish a task or solve a problem. In programming, algorithms are implemented through code.
In computer programming, we do the exact same thing, but instead of diamonds and boxes, we use code. The Java program below illustrates a simple algorithm that takes two inputs (a first name and a last name) and combines them to produce a greeting.
Task: Implementing a simple concatenation algorithm.
public class FullNameGreeter {
public static void main(String[] args) {
String firstName = args[0];
String lastName = args[1];
String fullName = firstName + " " + lastName;
System.out.println("Hello, " + fullName + "!");
}
}
In the above program, we wrote an algorithm to create a personalized greeting by passing in a first and last name as program arguments. This is one of the simplest algorithms. In real-world projects, you will be writing algorithms ranging from simple to very complex to solve specific problems.
Sequencing

Sequencing defines the one-at-a-time, specific order of steps in a process.
- Computer programs execute statements in order from top to bottom. This sequential flow is the most basic structure of an algorithm.
It's a fundamental concept in algorithms, ensuring that steps are completed in a specific, logical order.
In the above example, the order of execution within the method main is from top to bottom, one statement at a time.
Compilers
A compiler is a program that translates code from a high-level language like Java into the machine code that a computer's processor can execute. It checks the source code for errors that must be fixed before the program can be run.
We use the javac command to compile a Java program. You have likely used this command earlier (e.g., javac MyProgram.java) to manually convert your source code into executable bytecode.
In modern IDEs like Eclipse, compiling happens as soon as you save. This is where the command javac is still called behind the scenes. The below program shows compile issues. When there are compiler issues, the program cannot be converted to the .class file for it to run on JVM subsequently.
Task: Identifying a compiler error caused by case-sensitivity.
public class FullNameGreeter {
public static void main(String[] args) {
String firstName = args[0];
String lastName = args[1];
System.out.println("Hello, " + firstName + " " + lastname + "!"); // compiler error:
// Look at lastName variable!
// Is it the same variable used in System.out.println statement?
// Java is case-sensitive!
}
}
Integrated Development Environment (IDE)
As we discussed in the last lesson, while you can write Java code in any plain text editor, most programmers use an Integrated Development Environment (IDE). An IDE is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of at least a source code editor, build automation tools, and a debugger.
Depending on your project's needs or personal preference, you might choose from several popular IDEs for Java. These include Eclipse, IntelliJ IDEA, and Visual Studio Code. They provide tools to write, compile, run, and debug your code in one place, making development much easier and more efficient.
Task: Examining code formatting in an IDE.
// This is how code might look inside an IDE's text editor.
// The IDE provides features like syntax highlighting to make the code easier to read.
public class IdeExample {
public static void main(String[] args) {
System.out.println("This code is written in an IDE.");
}
}
Syntax Error
You were introduced to syntax errors earlier. A syntax error is a specific kind of compiler error. It happens when you violate the grammatical rules of the Java language. These are mistakes in the structure or spelling of your code.
Common examples include:
- Forgetting a semicolon ; at the end of a statement.
- Mismatched parentheses (), brackets [], or curly braces {}.
- Misspelling a keyword (e.g., publick instead of public).
- Using a variable before declaring it.
Task: Identifying common syntax errors.
public class SyntaxErrorExample {
public static void main(String[] args) {
String firstName = args[0] // syntax error: missing semicolon
String lastName = args[1];
System.out.println('Hello, " + firstName); // syntax error: mismatched quotes
}
}
Logic Error
A logic error is a mistake in the program's algorithm causing incorrect behavior. The program compiles and runs, but produces the wrong result. These are often the hardest to find.
Task: Identifying a logic error in an area calculation.
public class LogicErrorExample {
public static void main(String[] args) {
// Goal: Calculate the area of a rectangle with width 5 and height 4.
int width = 5;
int height = 4;
// Logic error: using addition instead of multiplication
int area = width + height;
System.out.println("The area is: " + area); // Prints 9, but should be 20
}
}
Run-time Error
A run-time error is a mistake that occurs during program execution, often causing it to terminate abnormally.
Task: Triggering an ArithmeticException runtime error.
public class RuntimeErrorExample {
public static void main(String[] args) {
// RUN-TIME ERROR: This will cause an ArithmeticException because you cannot divide by zero.
int result = 10 / 0;
System.out.println("The result is: " + result);
}
}
Exception
An exception is a type of run-time error from an unexpected event that interrupts the program's normal flow. An exception can occur for many different reasons, such as a user entering invalid data. Programmers can anticipate and handle some exceptions to prevent the program from crashing.
Task: Triggering an ArrayIndexOutOfBoundsException through missing arguments.
public class ExceptionExample {
public static void main(String[] args) {
// If you run this program without passing any arguments, an exception occurs.
System.out.println(args[0]);
}
}
Running the above will throw a stacktrace that begins with Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
This is because while running the program, the user did not provide the required program arguments that will be used in the program.
Scanner for Input
For handling user input, introductory Java programs often utilize the Scanner class due to its simplicity. It is in the java.util package and must be imported.
- Input allows programs to be interactive and process real-world data provided by the user at runtime.
Task: Reading user input from the keyboard using Scanner.
import java.util.Scanner;
public class ScannerDemo {
public static void main(String[] args) {
Scanner inputReader = new Scanner(System.in);
System.out.print("What is your name? ");
String name = inputReader.nextLine();
System.out.print("How old are you? ");
int age = inputReader.nextInt();
System.out.println("Hello, " + name + "! You are " + age + " years old.");
inputReader.close();
}
}
Let's look at how the Scanner is used in the above program:
Import:
import java.util.Scanner;
This statement tells Java that we want to use theScannerclass, which is located in thejava.utilpackage. Without this import, the program wouldn't know what aScanneris.Creation:
Scanner inputReader = new Scanner(System.in);
Here, we create a newScannerobject namedinputReader. We passSystem.into it, which represents the standard input stream (typically your keyboard). This tells the Scanner to watch for input coming from the keyboard.Reading a Line:
String name = inputReader.nextLine();
ThenextLine()method waits for the user to type something and press Enter. It then captures everything the user typed (including spaces) and stores it in thenamevariable.Reading an Integer:
int age = inputReader.nextInt();
ThenextInt()method waits for the user to type a number. It grabs the integer value and stores it in theagevariable.Closing:
inputReader.close();
It's good practice to close the Scanner when you're done with it to free up system resources.