An introductory course focusing on problem-solving, code structure, and tools
Analysing the problem before writing code. Using algorithms to describe the solution.
// Sorting a list example here
int[] numbers = {8, 0, 15, 3};
Arrays.sort(numbers);
// bubble sort
int[] numbers = {21, 2, 9, 13};
/*
looping through the array from start to second last element.
comparing each pair of elements in the unsorted part.
If current element is bigger than the next one, swap them.
Swap elements.
*/
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - i - 1; j++) {
if (numbers[j] > numbers[j + 1]) {
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
Breaking up the code into methods and classes for better structure.
class Calculator {
// Adding two numbers and returns the result
int add(int a, int b) {
return a + b;
}
// Subtracts second number from first and returns the result
int subtract(int a, int b) {
return a - b;
}
// Multiplies two numbers and returns the result
int multiply(int a, int b) {
return a * b;
}
// Divides first number by second and returns the result
// Checks if the divisor is not zero
int divide(int a, int b) {
if (b != 0) {
return a / b;
} else {
System.out.println("Cannot divide by zero.");
return 0;
}
}
}
Using comments and JavaDoc to document your code.
// Calculating the sum of two numbers
public int add(int x, int y) {
return x + y;
}
// multiply 2 numbers
public int multiply(int x, int y){
return x * y;
}
// divide a number by another
public int divide(int a, int b) throws ArithmeticException{
if (b == 0) {
throw new ArithmeticException("Cannot divide by zero");
}
return a / b;
}
// checking if the number is Even or odd
public boolean sEven(int nbr){
return nbr % 2 == 0;
}
Java programs are compiled with javac and run with java.
javac MyApp.java
java MyApp
Common tools: VS Code, IntelliJ IDEA, javac, debugger, etc.
Examples: int, double, boolean, if, while.
int age = 20;
if (age >= 18) {
System.out.println("Adult");
}
int, whole number
int age = 20;
double, decimal number
double price = 44.62;
boolean, true & false
boolean is = true;
char, single character
char letter = 'S';
byte, extrem small whole number
byte smallNumber = 321;
short, smaller range whole number
short shortNumber = 30021;
long, longer whole number
long longNumber = 143477458L;
/*
String, a sequence of characters.
Concatenating strings.
*/
String name = "John";
String greeting = "Hello, " + name + "!";
System.out.println(greeting);
// output: Hello John!
// if else, statement
int age = 20;
if (age >= 18) {
System.out.println("Adult");
} else {
System.out.println("Not an adult");
}
// if-else statement
int marks = 75;
if (marks >= 90) {
System.out.println("Excellent");
} else if (marks >= 70) {
System.out.println("Good");
} else {
System.out.println("Try Harder");
}
// while loop - repeats block of code as long as the condition is true
int count = 1;
while (count <= 5) {
System.out.println("Count: " + count);
count++;
}
// Output: 1, 2, 3, 4, 5
Implicit: automatic, Explicit: requires type casting.
double d = 10; // implicit
int i = (int) d; // explicit
implicit conversion
int num = 100;
double d = num; int to double
System.out.println(d); 100.0
explicit conversion
double value = 9.78;
int result = (int) value; double to int
System.out.println(result); 9 , decimal lost
char to int, implicit conversion
char c = 'A';
int ascii = c;
System.out.println(ascii);
int to char, explicit conversion
int code = 66;
char ch = (char) code;
System.out.println(ch);
Java has built-in classes like String, ArrayList, Scanner.
import java.util.ArrayList;
import java.util.Scanner;
import java.lang.StringBuilder;
creating list of strings
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Orange");
System.out.println(fruits);
output: Apple, Banana, Orange
// using built in String methods
String name = "Alice";
System.out.println(name.length()); 5
System.out.println(name.toUpperCase()); ALICE
System.out.println(name.charAt(0)); A
/*
reading user input.
*/
Scanner scan = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scan.nextLine();
System.out.println("Hello, " + name + "!");
// storing numbers in an ArrayList
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println(numbers.get(1)); 20
// efficient string appending
StringBuilder sb = new StringBuilder();
sb.append("Hello");
sb.append(" ");
sb.append("World");
System.out.println(sb.toString()); Hello World
arrays store multiple values of the same type.
int[] scores = {90, 85, 78};
System.out.println(scores[0]); 90
System.out.println(scores[1]); 85
System.out.println(scores[2]); 78
// changing second element from 85 to 95
int[] scores = {90, 85, 78};
scores[1] = 95;
System.out.println(scores[1]); 95
// looping through an array using for
int[] scores = {90, 85, 78};
for (int i = 0; i < scores.length; i++) {
System.out.println("Score " + i + ": " + scores[i]);
}
for each
int[] scores = {90, 85, 78};
for (int score : scores) {
System.out.println(score);
}
finding the sum of elements
int[] scores = {90, 85, 78};
int sum = 0;
for (int score : scores) {
sum += score;
}
System.out.println("Total: " + sum); 253
finding the highest score
int[] scores = {90, 85, 78};
int max = scores[0];
for (int i = 1; i < scores.length; i++) {
if (scores[i] > max) {
max = scores[i];
}
}
System.out.println("Highest score: " + max); 90
Use try-catch and thoroughly test your code.
int[] numbers = {1, 2, 3};
try {
System.out.println(numbers[5]); // Invalid index
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: index is out of bounds!");
}
number format Exception
try {
int num = Integer.parseInt("abc"); Invalid string
} catch (NumberFormatException e) {
System.out.println("Error: not a valid number!");
}
NUll pointer Exception
String name = null;
try {
System.out.println(name.length()); Will throw exception
} catch (NullPointerException e) {
System.out.println("Error: null value found!");
}
multiple catch blocks
try {
String s = null;
System.out.println(s.charAt(0));
} catch (NullPointerException e) {
System.out.println("Caught NullPointerException");
} catch (Exception e) {
System.out.println("Caught general exception");
}
try catch finally
try {
int result = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Division error");
} finally {
System.out.println("This always runs");
}
Test your knowledge of the course material. Select the best answer for each question.