Java syntax quick-reference

PGSS Computer Science Core

In this document, words occurring in angle brackets (like <this>) are things that should be replaced with what you want the code to do.

Types

The basic types are char, int, and double.

Identifiers

Java variable names and function names can have be number of letters, digits, and underscores, but they should begin with a letter. Case of letters matters.

Comments

  // <stuffExplainingYourProgram>

Functions

  public static <returnValueType> <functionName>( <parameterList> ) {
    <variableDeclarations>

    <statementsToDo>
  }

Basic-type variable declarations

  <typeName> <variableName>;

Array variable declarations

  <typeName>[] <variableName> = new <typeName>[<arrayLengthExpression>];

return statement

  return <returnValueExpression>;

Assignment statement

  <variableToBeChanged> = <valueToGiveItExpression>;

if statements

  if( <condition> ) {
    <statementsToDoIfConditionTrue>
  }
  if( <condition> ) {
    <statementsToDoIfConditionTrue>
  } else {
    <statementsToDoIfConditionFalse>
  }
  if( <condition> ) {
    <statementsToDoIfConditionTrue>
  } else if( <otherCondition> ) {
    <statementsToDoIfOtherConditionTrue>
  } else {
    <statementsToDoIfNoneAreTrue>
  }

while statement

  while( <condition> ) {
    <statementsToDoWhileConditionTrue>
  }

for statement

  for( <initializeAssignment> ; <condition> ; <updateAssignment> ) {
    <statementsToDoWhileConditionTrue>
  }