Please enable JavaScript to use CodeHS

Java Documentation

Basics

Printing to Console

System.out.println(str);
System.out.print(str);

// Example:
System.out.println("Hello world.");

// Printing without a new line:
System.out.print("Hello world. ");
System.out.print("How are you?");

Variables

// Declare a variable
int myVarName;

// Initialize a variable
int myVarName = 5;

// Assign to an existing variable
myVarName = 10;

// Print a variable
System.out.println(myVarName);
System.out.println("The value is: " + myValue);

Methods

// Methods can take in values, called parameters.
// The method below takes in a parameter called
// 'input' and prints it.
private void printText(String input)
{
  System.out.println(input);
}

// Methods can also return a value.
// The method below takes in a value,
// adds two to it, and returns it.
private int addTwo(int number)
{
    return number + 2;
}

User Input

// Read a string
String str = readLine(prompt);

// Read an integer
int num = readInt(prompt);

// Read a double
double myDouble = readDouble(prompt);

// Read a boolean
boolean bool = readBoolean(prompt);

// You should replace the word prompt with
// the question you'd like to ask. For example:
String name = readLine("What is your name? ");
int age = readInt("What is your age? ");
boolean finishedWork = readBoolean("Is your work done? ");

Comparison Operators

// Comparison operators return booleans (true/false values)

x == y         // is x equal to y
x != y      // is x not equal to y
x > y         // is x greater than y
x >= y         // is x greater than or equal to y
x < y         // is x less than y
x <= y         // is x less than or equal to y

// Comparison operators in if statements
if (x == y)
{
  System.out.println("x and y are equal");
}

if (x > 5)
{
  System.out.println("x is greater than 5.");
}

Math

// Operators:
+    Addition
-    Subtraction
*    Multiplication
/    Division
%    Modulus (Remainder)
() Parentheses (For order of operations)

// Examples
int z = x + y;
int w = x * y;

//Increment (add one)
x++

//Decrement (subtract one)
x--

//Shortcuts
x = x + y;        x += y;
x = x - y;        x -= y;
x = x * y;        x *= y;
x = x / y;        x /= y;

Randomizer


// The Randomizer class provides methods for creating random values

// Examples

// Random integer between low and high
int low = 1;
int high = 6;
int roll = Randomizer.nextInt(low, high);

// Random boolean value
boolean coinFlip = Randomizer.nextBoolean();

// Random boolean with a probability chance of being true
// probability must be between 0 and 1

// This coin flip has an 80% chance of being true
double probability = 0.8;
boolean coinFlip = Randomizer.nextBoolean(probability);

// Random double value between 0 and 1
double chanceOfRain = Randomizer.nextDouble();

// Random double value between low and high
double low = 2.0;
double high = 5.0;
double randomValue = Randomizer.nextDouble(low, high);

// Methods
Randomizer.nextInt(int low, int high)
Randomizer.nextBoolean()
Randomizer.nextBoolean(double probability)
Randomizer.nextDouble()
Randomizer.nextDouble(double low, double high)

Note: To use the Randomizer class, Randomizer.java must be included in your program's files. If it isn't already there, make a new file called Randomizer.java, and copy / paste in the code for the Randomizer class from the CodeHS Java Library.

Control Structures

Booleans

// A boolean is either true or false
boolean myBoolean = true;

boolean anotherBoolean = false;

boolean result = readBoolean("Question? ");

// Not Operator
boolean x = !y;     // x gets the opposite of y

// And Operator
boolean andExp = x && y;

// Or Operator
boolean orExp = x || y;

// You can combine many booleans!
boolean boolExp = x && (y || z);

If Statements, If/Else, If/Else If/Else

if (BOOLEAN_EXPRESSION)
{
    // code to execute if true
}

if (BOOLEAN_EXPRESSION)
{
    // code if true
}
else
{
    // code if false
}

if (x < 0)
{
  System.out.println("x is negative.");
}

if (color.equals("red") || color.equals("blue") || color.equals("yellow"))
{
  System.out.println("Primary color.");
}
else
{
  System.out.println("Not a primary color.");
}

// You can use else if if you have multiple
// conditions, but only one should happen.
if(condition_1)
{

}
else if (condition_2)
{

}
else if (condition_3)
{

}
else
{

}


// You can always write these using nested
// if/else. For example:
if (condition_1)
{
    // this code runs if condition 1 is true
}
else
{

    // this code runs if condition 1 is false

    if (condition_2)
    {
        // this code runs if condition 2 is true
    }
    else
    {
        // this code runs if condition 2 is false
    }
}

For Loops

int COUNT = 5;

for (int i = 0; i < COUNT; i++)
{
    /* Repeat code between the brackets 5 times,
     * as the COUNT variable is 5. */
}

// Print numbers 0-9
for (int i = 0; i < 10; i++)
{
    System.out.println(i);
}

For-Each Loops

int[] nums = {7, 8, 9, 10};

    for (int element : nums)
    {
        /* Repeat code between the brackets for
         * each element in the array. Each time
         * through, element has a different value
         * from the array. */
    }

    // Print each number in the array
    for (int num : nums)
    {
        System.out.println(num);
    }

While Loops

while (boolean expression)
{
    /* Repeat code between brackets while
     * 'boolean expression' is true */
}

// Countdown from 15 to 10
int i = 15;
while (i > 10)
{
    System.out.println(i);
    i--;
}
// This is a loop and a half format
while (true)
{
    // code
    if (condition)
    {
        break;
    }
}

Data Structures

Arrays

// Create an array of size 5
int[] arr = new int[5];

// Create an array that is initialized with values
int[] arr = {7, 8, 9, 10};
// to access a given index in an array
// you can use the following syntax
arr[i]

// for example, to print out the 5th element in the array:
System.out.println(arr[4])
// remember that arrays start with 0!

// to loop through an array, you can use a standard
// for loop, given an array of n elements arr
for (int i = 0; i < arr.length; i++)
{
    System.out.println(arr[i])
}
// this will print each element in a list on its own line

Array Methods

Go To Full Java Reference

Static Methods

// You'll need to import Arrays to use these methods
import java.util.Arrays;

// Sort the given array into ascending order
int[] arr = {18, 5, 9, 8, 1, 3}
Arrays.sort(arr)  // arr is now [1, 3, 5, 8, 9, 18]

ArrayList

// Don't forget to import ArrayList!
import java.util.ArrayList;

// Create a general ArrayList
ArrayList<T> arrList = new ArrayList<T>();
// where T represents a type (Object or primitive)

// Create an ArrayList of ints and add some.
ArrayList<Integer> arrList = new ArrayList<Integer>();
// ArrayLists contain objects, so instead of using primitive types
// like int, we use their Object forms, like Integer.
arrList.add(1);
arrList.add(2);
arrList.add(3);
arrList.add(4)
// to access a given index in an ArrayList
// you can use the following syntax
arrList.get(i);
// this can also be saved to a variable
int arrListElem = arrList.get(2); // arrListElem = 3

// for example, to print out the 3rd element in the ArrayList:
System.out.println(arrList.get(2))
// Like arrays, ArrayLists are indexed at 0.

// you can remove in a similar way
arrList.remove(i);

// to loop through an ArrayList, you can use a standard
// for loop, given an ArrayList of n elements arrList
for (int i = 0; i < arrList.size(); i++)
{
    System.out.println(arrList.get(i))
}
// this will print each element in a list on its own line

// you can also use a 'foreach' loop
for (Integer i : arrList)
{
    System.out.println(i);
}

// for more documentation, check out the
// official Oracle Documentation here.

2D Arrays

// you can represent tables, grids, and matrices

// make a 3x4 grid of ints
int[][] grid = new int[3][4];

// make a 3x3 grid of chars
char[][] grid = new int[3][3];

// make a 10 x 3 grid of Strings
String[][] grid = new String[10][3];

// initialize a list
int[][] grid = {
    {1,2,3,4},
    {5,6,7,8}
};

// get a row
int[] row = grid[1]

// get an element
int elem = grid[1][2];

Hashmap

// used to store key, value mappings

// create a map
HashMap<String, String> phonebook = new HashMap<String, String>();

// put things in the map
phonebook.put("Alan Turing", "312-423-1234");

// figure out if a key is in the map
boolean hasKey1 = phonebook.containsKey("Alan Turing")
boolean hasKey2 = phonebook.containsKey("Karel the Dog");
System.out.println(hasKey1);  // this will print true
System.out.println(hasKey2);  // this will print false

// get things from a map
String alansNumber = phonebook.get("Alan Turing");

// looping over a map
System.out.println("The Full Phonebook");
for(String key: phonebook.keySet())
{
    String number = phonebook.get(key);
    System.out.println(key + ": " + number);
}

Classes

ConsoleProgram

// ConsoleProgram allows you to read easily from the console.
// Extend ConsoleProgram in order to use these helpful methods.

readLine(String prompt);
String name = readLine("What is your name? ");

readBoolean(String prompt);
boolean likesIceCream = readBoolean("Do you like ice cream? ");

readDouble(String prompt);
double gpa = readDouble("What is your GPA? ");

readInt(String prompt);
int age = readInt("How old are you? ");

Character Methods

Go To Full Java Reference
// The Character class allows for advanced
// manipulations of characters in java.

// These methods are static, which means they are called on the
// Character class level, rather than on a specific Character object
// To use these methods, simply call them on the class Character

// For example
static boolean isUpperCase(char ch)
// Usage
Character.isUpperCase('A') // returns true

// Methods
static boolean isUpperCase(char ch)
    returns true if ch is an uppercase character,
    false otherwise

static boolean isLowerCase(char ch)
    returns true if ch is a lowerspace character,
    false otherwise

static boolean isDigit(char ch)
    returns true if ch is a digit (a number),
    false otherwise

static boolean isLetter(char ch)
    returns true if ch is a letter, false otherwise

static boolean isLetterOrDigit(char ch)
    returns true if ch is either a letter or a digit,
    false otherwise

static boolean isWhitespace(char ch)
    returns true if ch is a whitespace character
    (i.e. space or new line), false otherwise

static char toUpperCase(char ch)
    returns the uppercase version of ch

static char toLowerCase(char ch)
    returns the lowercase version of ch

// learn more at the full reference linked above!

Character Examples

Go To Full Java Reference
// The Character class allows for advanced
// manipulations of characters in java.

// Examples

// isUpperCase
char ch = 'd';
boolean upper = Character.isUpperCase(ch);  // upper is false
upper = Character.isUpperCase('D');         // upper is true
upper = Character.isUpperCase(' ');         // upper is false
upper = Character.isUpperCase('1');         // upper is false

// isLowerCase
char ch = 'd';
boolean lower = Character.isLowerCase(ch);  // lower is true
lower = Character.isLowerCase('D');         // lower is false
lower = Character.isLowerCase(' ');         // lower is false
lower = Character.isLowerCase('1');         // lower is false

// Checking for letter or digit
// isLetter, isDigit, isLetterOrDigit
char ch = 'd';
boolean isLetter = Character.isLetter(ch);  // isLetter is true
boolean isDigit = Character.isDigit(ch);    // isDigit is false
boolean either = Character.isLetterOrDigit(ch); // either is true

isDigit = Character.isDigit(' ');           // isDigit is false
isDigit = Character.isDigit('9');           // isDigit is true

either = Character.isLetterOrDigit('9');    // either is true
either = Character.isLetterOrDigit(' ');    // either is false

// Checking for whitespace like space ' ' or new line '\n'
// isWhitespace
char space = ' ';
boolean whiteSpace = Character.isWhitespace(space); // whitespace is true

whiteSpace = Character.isWhitespace('\n'); // whitespace is true
whiteSpace = Character.isWhitespace('8');  // whitespace is false
whiteSpace = Character.isWhitespace('A');  // whitespace is false

// toUpperCase and toLowerCase
char lowerD = 'd';
char upper = Character.toUpperCase(lowerD);  // upper is 'D'
char lower = Character.toLowerCase(upper);   // lower is 'd'

// learn more at the full reference linked above!

Math Methods

Go To Full Java Reference
// The Math class allows for advanced
// calculations in java.

// These methods are static, which means they are called on the
// Math class level, rather than on a specific Math object
// To use these methods, simply call them on the class Math

// For example
static double abs(double a)
// Usage
double result = Math.abs(-14);  // result is 14

// Methods
static int abs(int a)
static double abs(double a)
    returns the absolute value of a

static long round(double a)
static int(float a)
    returns the closest number, with ties (1.5) rounding up

static int max(int a, int b)
static double max(double a, double b)
    returns the greater of two values a and b

static int min(int a, int b)
static double min(double a, double b)
    returns the lower of two values a and b

static double pow(double a, double b)
    returns a raised to the power of b

static double sqrt(double a)
    returns the square root of a

static double floor(double a)
    returns the greatest value less than
    or equal to a

static double ceil(double a)
    returns the lowest value greater than
    or equal to a

// learn more at the full reference linked above!

Math Examples

Go To Full Java Reference
// The Math class allows for advanced
// calculations in java.

// Examples

// Absolute value
// abs
double val = -5.5;
double abs = Math.abs(val); // abs is 5.5

int num = 5;
int abs = Math.abs(num);    // abs is 5

// Rounding
double x = 1.3;
int roundedX = (int) Math.round(x); // 1

double y = 1.5;
int roundedY = (int) Math.round(y); // 2

double z = 1.7;
int roundedZ = (int) Math.round(z); // 2

// Maximum of two values
// max
int max = Math.max(4, 5);   // max is 5
max = Math.max(-4, -5);     // max is -4

double max = Math.max(3.0, -2.1);   // max is 3.0
max = Math.max(-2.2, -10.2);        // max is -2.2

// Minimum of two values
// min
int min = Math.min(10, 1);  // min is 1
min = Math.min(-10, -11);   // min is -11

double min = Math.min(9.4, 11.1);   // min is 9.4
min = Math.min(2.2, -9.5);          // min is -9.5

// Exponents (a raised to the power of b)
// pow
double base = 4;
double exp = 2;
double power = Math.pow(base, exp);  // power is 16.0 (4 * 4 = 16)

power = Math.pow(1, 4);  // power is 1.0 (1 * 1 * 1 * 1 = 1)

// Square root
// sqrt
double root = Math.sqrt(25);        // root is 5.0
root = Math.sqrt(16);               // root is 4.0
root = Math.sqrt(root);             // root is 2.0

// Floor -- Greatest value lower than the parameter
// floor
double floor = Math.floor(8.323);   // floor is 8.0
floor = Math.floor(-8.323);         // floor is -9.0

// Ceiling -- Lowest value greater than the parameter
// ceil
double ceiling = Math.ceil(8.323);  // ceiling is 9.0
ceiling = Math.ceil(-8.323);        // ceiling is -8.0

// learn more at the full reference linked above!

String Methods

Go To Full Java Reference
// The String class allows for advanced
// manipulations of Strings in Java.

// Methods
char charAt(int index)
    returns the character in the String
    at the specified index.

boolean equals(String other)
    returns whether this string is equal
    to a different String other

boolean equalsIgnoreCase(String other)
    returns whether this string is equal
    to a different String other, ignoring
    differences in upper and lower case

int indexOf(char ch)
    returns the index within this String
    of the first occurance of the specified
    character ch. If ch does not exist in
    this String, -1 is returned

int indexOf(String str)
    returns the index within this String
    of the first occurance of the specified
    substring str. If str does not exist
    inside this String, -1 is returned

int length()
    returns the length of this String

String substring(int beginIndex)
    returns the substring of this String
    starting at the specified beginIndex
    and ending at the end of the string

String substring(int beginIndex, int endIndex)
    returns the substring of this String
    starting at the specified beginIndex
    and ending at the specified endIndex.
    The substring includes the character
    at beginIndex, but does not include
    the character at endIndex.

boolean startsWith(String str)
    returns true if this String starts
    with the specified String str,
    false otherwise

boolean endsWith(String str)
    returns true if this String ends
    with the specified String str,
    false otherwise

String toLowerCase()
    returns a new String containing
    the same characters as this String
    converted to lower case

String toUpperCase()
    returns a new String containing
    the same characters as this String
    converted to upper case

// learn more at the full reference linked above!

String Examples

Go To Full Java Reference
// The String class allows for advanced
// manipulations of Strings in Java.

// Examples

// Creating Strings
String hello = "hello";
String empty = "";
String sentece = "The quick brown fox jumps over the lazy dog.";

// Accessing characters in a String
// charAt
String str = "Hello World!";

char first = str.charAt(0);  // first is 'H'
char middle = str.charAt(6);  // middle is 'W'

// Checking for equality
// equals and equalsIgnoreCase
String str = "CodeHS";
String lower = "codehs";

boolean isEqual = str.equals("CodeHS"); // isEqual is true
isEqual = str.equals(lower);         // isEqual is false

boolean similar = str.equalsIgnoreCase(lower); // similar is true

// Finding characters and substrings
// indexOf
String str = "Hello World!";

int index = str.indexOf('H'); // index is 0
index = str.indexOf('o');     // index is 4
index = str.indexOf("World"); // index is 6
index = str.indexOf("Hello"); // index is 0

// Getting the length of a String
// length
String str = "Hello";
int length = str.length();  // length is 5

str = "A";
length = str.length();      // length is 1

str = "";
length = str.length();      // length is 0

// Getting substrings of a String
// substring
String str = "CodeHS";

String sub = str.substring(4); // sub is "HS"
sub = str.substring(1);        // sub is "odeHS"
sub = str.substring(1, 4);     // sub is "ode"
sub = str.substring(0, 1);     // sub is "C"

// Checking for beginnings and endings of a String
// startsWith and endsWith
String str = "CodeHS";

boolean codeStart = str.startsWith("Code"); // codeStart is true
boolean hsStart = str.startsWith("HS");     // hsStart false

boolean codeEnd = str.endsWith("Code");     // codeEnd is false
boolean hsEnd = str.endsWith("HS");         // hsEnd is true

// Converting the case of characters in a String
// toLowerCase and toUpperCase
String str = "CodeHS";
String hello = "Hello World!";

String lower = str.toLowerCase();   // lower is "codehs"
String upper = lower.toUpperCase(); // upper is "CODEHS"

upper = hello.toUpperCase();        // upper is "HELLO WORLD!"
lower = upper.toLowerCase();        // lower is "hello world!"

// learn more at the full reference linked above!

Extending Classes

// using extends in Java means that one class inherits
// from another.

// for example, a Jet class could extend Plane
public class Jet extends Plane
{
    // Jet specific code here
}

// sometimes you will need to call a method from the
// class you inherited from, known as the parent class.

super.fly(); // this will class the parent class' fly method

Implementing Interfaces

// implementing in Java is similar to using a blueprint.
// an Interface gives methods classes must implement.
public interface Blueprint
{
    public String address = "10 Downing Street"
    public void printAddress();
}

public class Building implements Blueprint {
    // we have to declare a method with the same
    // signature as the interface.
    public void printAddress()
    {
        // you can use interface variables like static variables
        System.out.println(Blueprint.address);
    }
}

Comparable Interface

// A class can implement Comparable and then take advantage of other
// utilities to help order objects of the class (useful for sorting)

// Compares the current instance to the other object and return
// a number indicating ordering. You should return 0 if they are
// equal and a negative or positive number depending on ordering
public int compareTo(Object o)

// For purposes of ordering circles
public int compareTo(Circle other)
{
    double diff = gerRadius() - other.getRadius();
    return (int)Math.signum(diff);
}

List Interface

// Defines methods classes can implement in order to
// represent an ordered List
// List is an interface that defines abstract method signatures

// Some important methods of List interface:

// Returns the number of elements in a list
int size()

// Adds the given element to the end of the list
boolean add(E elem)

// Adds the given element at the specified index, shifts the subsequent
// elements up one index
void add(int index, E elem)

// Returns the element at the specified index
E get(int index)

// Replaces the element at the given index with the elem
// provided. Returns the old element that was replaced
E set(int index, E elem)

// Classes can implement List
ArrayList<E> implements List<E>

List<String> strList = new ArrayList<String>();
List<MyClass> myList = new ArrayList<MyClass>();

// How to use List
public void printOddIndices (List<integer> list)
{
    // Can use methods like list.add(4), list.size(), etc.
}

Graphics

Circle

// To make a circle
Circle circle = new Circle(radius);

// To set the location of the center of the circle
circle.setPosition(x, y);

// Example, red circle with 50px radius with center at (100, 200)
Circle circle = new Circle(50);
circle.setPosition(100, 200);
circle.setColor(Color.red);

// Get the radius
circle.getRadius();                 // returns 50
double curRadius = circle.getRadius(); // store in variable

// Change the radius
circle.setRadius(100);

// Get the position of the center of the circle
double x = circle.getX();  // x is 100
double y = circle.getY();  // y is 200

// Change the location of the circle
double x = getWidth() / 2;
double y = getHeight() / 2;
circle.setPosition(x, y);   // circle center is in the center of the screen

// Add to screen
add(circle);

// Move the circle dx horizontally and dy vertically
circle.move(dx, dy);

Rectangle

// To make a rectangle
Rectangle rect = new Rectangle(width, height);

// To set location of the upper left corner of rectangle
rect.setPosition(x, y);

// Example, 200x50 blue rectangle with upper left corner at (100, 200)
Rectangle rect = new Rectangle(200, 50);
rect.setPosition(100, 200);
rect.setColor(Color.blue);

// Get location of the upper left corner of the rectangle
double x = rect.getX(); // x is 100
double y = rect.getY(); // y is 200

// Change location of the rectangle
double x = getWidth() / 2;
double y = getHeight() / 2;
rect.setPosition(x, y)  // upper left corner is at center of screen

// Add to screen
add(rect);

// Move the rect dx horizontally and dy vertically
rect.move(dx, dy);

Line

// To draw a line from (x1, y1) to (x2, y2)
Line line = new Line(x1, y1, x2, y2);

// Set the line color to green
line.setColor(Color.green);

// Set the line width to 10 pixels
line.setLineWidth(10);

// Add to screen
add(line);

// Change the starting point of the line to (x1, y1)
line.setPosition(x1, y1);

// Change the end point of the line to (x2, y2)
line.setEndpoint(x2, y2);

//Get the starting point of the line
double x = line.getX();    // x has same value as x1
double y = line.getY();    // y has same value as y1

//Get the ending point of the line
double endX = line.getEndX();    // x has same value as x2
double endY = line.getEndY();    // y has same value as y2

// Move the line dx horizontally and dy vertically
line.move(dx, dy);

Text

// To make a graphical text object
Text txt = new Text(label, font);

// To set the position of the lower left corner of the text
txt.setPosition(x, y);

// Example
Text txt = new Text("Hello, world!", "30pt Arial");
txt.setPosition(100, 200);
txt.setColor(Color.blue);

// Change what the text says
txt.setText("Goodbye!");

// Get the location of the lower left corner of text
double x = txt.getX(); // x is 100
double y = txt.getY(); // y is 200

// Add to screen
add(txt);

// Move the text dx horizontally and dy vertically
txt.move(dx, dy);

Color

// There are many color constants. You can set an objects
// color like
obj.setColor(color);

// Specifically,
obj.setColor(Color.RED);

// List of available colors:
Color.RED
Color.GREEN
Color.BLUE
Color.YELLOW
Color.CYAN
Color.ORANGE
Color.WHITE
Color.BLACK
Color.GRAY
Color.PURPLE

// Another way to set the color of an object is to use a
// string with the hexadecimal color value with setColor.
// For example, to set a rect object to be pink:
rect.setColor("#FF66CC");

// Get a random color from the randomizer
String color = Randomizer.nextColor();