Please enable JavaScript to use CodeHS

Java Documentation - Basics

By Zach Galant

Co-Founder of CodeHS

Printing to the console

Given a string str you can print to the console using System.out.println or System.out.print

// Prints a line and ends with a new line
System.out.println(str);

// Prints a line but doesn't end the line. the next call to print or println will continue on the same line
System.out.print(str);
Java

Variables

You can create an integer variable with the keyword int like so

// Creates a variable with no value yet
int myVariable;

// Creates a variable with a value
int myOtherVariable = 5;
Java

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);
}
Java

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;
}
Java

User Input

You can collect user input in programs with a Scanner

Initializing a Scanner

import java.util.Scanner;
Scanner scanner = new Scanner(System.in);
Java

Read a string

String str = scanner.nextLine();
Java

Read an integer

int num = scanner.nextInt();
Java

Read a double

double myDouble = scanner.nextDouble();
Java

Read a boolean

boolean bool = scanner.nextBoolean();
Java

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
Java

Comparison operators in if statements

if (x == y)
{
    System.out.println("x and y are equal");
}
Java
if (x > 5)
{
    System.out.println("x is greater than 5.");
}
Java

Math

Operators

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

Examples

int z = x + y;
int w = x * y;
Java

Increment (add one)

x++
Java

Decrement (subtract one)

x--
Java

Shortcuts

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