Skip to main content

Syntax/Getting Started

In my AP Computer Science class, we used the Blue Pelican Java textbook. Here's a link to it in case you would like a formal book to read through and reference.

External Resources:

Main method

All Java programs start with what's called a "main method". See this example:

public class Example {

public static void main(String[] args) {
// This is the main method, which is where all Java programs start.

System.out.println("Hello world!");
}
}

When run, the above code will print Hello world!.

A basic "print" statement looks like this:

System.out.println("Let's print something to the console!");
System.out.print("This doesn't add a new line");
System.out.printf("There are " + 42 + " ducks in the lake.");

Variables

A variable is a container that holds a value during the execution of a Java program. Variables are declared with a data type, which specifies the type of value that the variable can hold. For example, the following code declares a variable called name of type String:

String name;

The value of a variable can be assigned using the assignment operator (=). For example, the following code assigns the value "John Doe" to the variable name:

name = "John Doe";

The value of a variable can be accessed using its name. For example, the following code prints the value of the variable name:

System.out.println(name);

You can also define and declare a variable on the same line:

String name = "John Doe";

Variables can be used to store all kinds of data, such as numbers, strings, and boolean values. Here are the basic ones:

  • boolean: can be either true or false
  • String: is a string of characters, such as "Hello"
  • int: is an Integer, positive or negative (-1, 0, 1, etc)
  • double: is a decimal value such as 0.5 or -10.5

Java also has char, float, and long variable types.

Here are some examples of declaring variables in Java:

String name = "Tom";
int timesSeen = 10;
double age = 20.5;
double heightInches = 12 * 5 + 6; // 5ft 6in
boolean isInCollege = true;
char grade = 'A';
final double PI = 3.14159; // constant variable

Operators

Common operators in Java:

// Arithmetic
int sum = 5 + 3; // Addition
int diff = 10 - 4; // Subtraction
int product = 6 * 7; // Multiplication
int quotient = 20 / 4; // Division
int remainder = 17 % 5; // Modulus (remainder)

// Comparison
boolean isEqual = (5 == 5); // true
boolean isNotEqual = (5 != 3); // true
boolean isGreater = (10 > 5); // true
boolean isLessOrEqual = (5 <= 5); // true

// Logical
boolean and = true && false; // false
boolean or = true || false; // true
boolean not = !true; // false

Conditionals

Control program flow with if-else statements:

int score = 85;

if (score >= 90) {
System.out.println("Grade: A");
} else if (score >= 80) {
System.out.println("Grade: B");
} else if (score >= 70) {
System.out.println("Grade: C");
} else {
System.out.println("Grade: F");
}

// Switch statement
char grade = 'B';
switch (grade) {
case 'A':
System.out.println("Excellent!");
break;
case 'B':
System.out.println("Good job!");
break;
default:
System.out.println("Keep trying!");
}

Loops

Repeat code with loops:

// For loop
for (int i = 0; i < 5; i++) {
System.out.println("Count: " + i);
}

// While loop
int count = 0;
while (count < 3) {
System.out.println("While count: " + count);
count++;
}

// Do-while loop
int num = 0;
do {
System.out.println("Do-while: " + num);
num++;
} while (num < 2);

Arrays

Fixed-size collections of elements:

// Declare and initialize
int[] numbers = {1, 2, 3, 4, 5};
String[] names = new String[3];

// Access elements
System.out.println(numbers[0]); // prints 1
names[0] = "Alice";

// Array length
System.out.println("Array length: " + numbers.length);

// Loop through array
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}

// Enhanced for loop
for (int num : numbers) {
System.out.println(num);
}

Functions

A function in Java is a block of code that performs a specific task. Functions are used to organize and reuse code, and they can make your code more readable.

public class Example {

public static String greet(String name) {
return "Hello, " + name + "!";
}

public static int add(int a, int b) {
return a + b;
}

public static void printInfo(String name, int age) {
System.out.println("Name: " + name + ", Age: " + age);
}

public static void main(String[] args) {
System.out.println(greet("Tom"));
System.out.println("Sum: " + add(5, 3));
printInfo("Alice", 25);
}
}

Classes

A class in Java is a blueprint for creating objects. It defines the properties and behaviors of an object. A class is defined using the class keyword.

Here is an example of a class in Java:

public class Person {

// This is a field. A field is a variable that is associated with a class.
private String name;
private int age;

// This is a constructor. A constructor is a special method that is used to create an object of a class.
public Person(String name, int age) {
this.name = name;
this.age = age;
}

// Getter methods
public String getName() {
return name;
}

public int getAge() {
return age;
}

// This is a method. A method is a block of code that performs a specific task.
public void sayHello() {
System.out.println("Hello, my name is " + name + " and I'm " + age + " years old.");
}

}

This code defines a class called Person. The class has fields called name and age, and methods for accessing and displaying information.

To create an object of the Person class, we use the new keyword:

Person p = new Person("Alice", 25);
p.sayHello(); // Output: Hello, my name is Alice and I'm 25 years old.

ArrayLists

An ArrayList in Java is a resizable array. It is a data structure that can store a collection of items whether that be strings, numbers, or plain objects.

import java.util.ArrayList;

// Create an ArrayList
ArrayList<String> myList = new ArrayList<>();

// Add elements
myList.add("Hello");
myList.add("World");

// Get size and elements
System.out.println("Size: " + myList.size());
System.out.println("First element: " + myList.get(0));

// Remove elements
myList.remove(0);

// Check if contains element
if (myList.contains("World")) {
System.out.println("Found World!");
}

We can iterate over the elements in the ArrayList using a for loop. For example, the following code iterates over the elements in the ArrayList myList and prints each element:

for (String element : myList) {
System.out.println(element);
}

HashMaps

A HashMap in Java is a data structure that maps keys to values. It is a very efficient way to store data, and it is often used to store key-value pairs, such as a user's name and their age, or a product's id and its price.

import java.util.HashMap;

// Create a HashMap
HashMap<String, Integer> grades = new HashMap<>();

// Add key-value pairs
grades.put("Alice", 95);
grades.put("Bob", 87);
grades.put("Charlie", 92);

// Get values
System.out.println("Alice's grade: " + grades.get("Alice"));

// Check if key exists
if (grades.containsKey("Bob")) {
System.out.println("Bob's grade found!");
}

// Remove key-value pair
grades.remove("Charlie");

// Get size
System.out.println("Number of students: " + grades.size());

We can iterate over the key-value pairs in the HashMap using a for loop. For example, the following code iterates over the key-value pairs in the HashMap grades and prints each key and value:

for (String key : grades.keySet()) {
System.out.println(key + " = " + grades.get(key));
}

Imports

Use imports to access classes from other packages:

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.util.*; // Import all classes from java.util

public class Example {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// ... rest of code
}
}

Exception Handling

Handle errors gracefully with try-catch blocks:

try {
int result = 10 / 0; // This will throw an exception
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("This always executes");
}

Input/Output

Read user input with Scanner:

import java.util.Scanner;

Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("Hello " + name + ", you are " + age + " years old.");