Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Cheat Sheet

Java For Dummies

Call it Java "syntax" or Java "grammar" — when you write Java code statements, you have to know where to put the keywords, the parentheses, the semicolons, and all the other things. This cheat sheet summarizes those Java syntax rules, and gives you a bit of info about the use of each statement type.

How to Understand Java Statements

Most syntax summaries list the details of each statement type using formal, esoteric descriptions. However, these examples of each statement type give a brief, informal description of the statement type's purpose. This description of Java syntax is far from being comprehensive, but you should find it to be readable and useful.

A Java class:

class PreIncrementDemo {
 
}
What it means: "The stuff between the curly braces belongs to a class named PreIncrementDemo. This class is a blueprint for creating objects (instances of the PreIncrementDemo class)."

import declarations:

import java.util.Scanner;
import static java.lang.System.out;
What they mean: "When I use the name Scanner elsewhere in this .java file, take it to be an abbreviation for java.util.Scanner. That is, take the name Scanner to represent the Scanner class that's in the java.util package.
"When I use the name out elsewhere in this .java file, take it to be an abbreviation for java.lang.System.out. That is, take the name out to represent the static out field that's in the System class which, in turn, is in the java.lang package."

Variable declarations:

int numberOfBunnies = 27;
JFrame myFrame;
"The name numberOfBunnies stores an int value (a whole-number value, such as 42, 0, -289) and the starting value of numberOfBunnies is 27. The name myFrame will refer to an object created from the JFrame class. (That is, myFrame will refer to an instance of the JFrame class. The JFrame class is pre-declared in a package named javax.swing.) "

Assignment statements:

amountInAccount = 50.22;
amountInAccount *= 1.05;
amountInAccount = amountInAccount + 1000000.00;
"To the variable amountInAccount assign the value 50.22. Then, multiply the value of amountInAccount by 1.05. Then add 1000000.00 to the value of amountInAccount."

A method declaration:

int incrementBy(int amount) {
 
}
"I'm introducing (that is "declaring") a method named incrementBy. The incrementBy method takes, as its input (it's "parameter") an int value. Within the body of the method (that is, between the curly braces) that parameter value is known by the variable name amount. Execution of the incrementBy method returns a (possibly different) value, also of type int."

Method calls:

n = incrementBy(6);
System.out.println(incrementBy(10));
"Call the incrementBy method (that is, execute the statements in the body of the incrementBy method) giving the method's parameter the value 6. Take the value returned by the call to incrementBy, and assign that returned value to the variable n.
"Also, call the incrementBy method giving the method's parameter the value 10. Then, take the value returned by the call to incrementBy, and feed that returned value to another method -- Java's pre-declared System.out.println method."

A main method:

public static void main(String args[]) {
 
}
"Begin running the Java program by executing the statements in the body of the method named main."

A constructor call:

JFrame myFrame = new JFrame("This is my frame!");
"Create a new object using the definition of the JFrame class. (A JFrame is what you'd normally call a "window.") In the title bar of the new object, display the words This is my frame! Let the variable myFrame refer to the new object (the new instance of the JFrame class)."

An if statement:

if (inputNumber == randomNumber) {
 
} else {
 
}
"If the inputNumber equals the randomNumber, then execute one bunch of statements (the statements inside the first pair of curly braces). But, if the inputNumber doesn't equal the randomNumber, execute a different bunch of statements (the statements inside the second pair of curly braces -- the statements after the word else)."

A switch statement:

switch (verse) {
case 1:
 
    break;
case 2:
 
    break;
case 3:
 
    break;
default:
 
    break;
}
"If the value of verse is 1, execute the statements after case 1: and then break outside of the entire switch statement. If the value of verse is 2, execute the statements after case 2: and then break outside of the entire switch statement. Blah-blah-blah for verse being equal to 3. If, for some reason, the value of verse isn't any of the values 1, 2 or 3, execute the statements after default: and then break outside of the entire switch statement."

A while statement:

while (inputNumber != randomNumber) {
 
}
"Check to see if the inputNumber isn't equal to the randomNumber. If so (that is, if the two numbers aren't equal) then execute the statements between the curly braces. After executing the statements between the curly braces, then repeat the whole thing. (Check to see if the numbers aren't equal, and so on). If, during one of the repetitions, you find that inputNumber != randomNumber isn't true (that is, you find that the inputNumber is equal to the randomNumber) then stop repeating stuff and move on to execute whatever statement comes immediately after this while statement in your code."

A for statement:

for (int count = 1; count <= 10; count++) {
 
}
"Start with 1 for the value of count. Check to make sure that count is less than 10. (Of course, in this example, count starts out being less than 10.) Because count is less than 10, execute the statements inside the curly braces. When you're finished executing the statements inside the braces, do the count++ business (that is, add 1 to the value of count).
"Go back and check to see if count is still less than 10. (Yes, in this example, count is now 2.) Because count is less than 10, execute the statements inside the curly braces, and then add 1 to the value of count.
"If, at the start of a repetition, you find that count <= 10 isn't true, then stop repeating stuff and move on to execute whatever statement comes immediately after this for statement in your code."

A do...while statement:

do {
 
} while (reply != 'y' && reply != 'n');
"At first, don't check anything. Start by executing the statements between the curly braces, and then checking to see if reply isn't equal to 'y' and reply isn't equal to 'n'. (That is, check to see if reply is neither 'y' nor 'n'.) If reply is neither 'y' nor 'n', then repeat the whole thing. (Execute the statements between the curly braces, and then check again.) If, at the end of one of the repetitions, you find that the reply is either 'y' or 'n', then stop repeating and execute the statement immediately after this do…while statement."

An enum declaration:

enum Room {ballroom, kitchen, diningRoom,
           lounge, hall, study, library,
           billiardRoom, conservatory};
Room sceneOfTheCrime = Room.study;
"Any variable that's declared to be of type Room will store one of the following values: Room.ballroom, Room.kitchen, Room.diningRoom, Room.lounge, and so on. In this example, the variable sceneOfTheCrime is declared to be of type Room. The variable sceneOfTheCrime starts off storing the value Room.study."

An enhanced for statement:

for (Room myRoom : Room.values()) {
 
}
"Execute the statements inside the curly braces several times -- once for each of the Room enum's values. Execute the statements once with myRoom equal to Room.ballroom. Then execute the statements again with myRoom equal to Room.kitchen. And so on."

Extending an existing class:

class FullTimeEmployee extends Employee {
 
}
"A FullTimeEmployee is an Employee with certain additional features; namely, the features described between the curly braces."
In this example FullTimeEmployee is a subclass (a.k.a. child class) of the Employee class, and the Employee class is a superclass (a.k.a. parent class) of the FullTimeEmployee class.

A throws clause:

void doStuff() throws IOException {
 
  Scanner diskScanner =
    new Scanner(new File("EmployeeInfo.txt"));
"The execution of some code inside the doStuff method might throw an IOException."
When you try to create a new instance of the File class, things can go wrong. Java insists that you acknowledge the possible calamity by announcing that your method can/may throw an IOException. Whenever you execute code that can throw an IOException, you must acknowledge the exception in your code. An exception that must be acknowledged (such as IOException) is called a checked exception.

Constructors:

class Temperature {
    private double number;
    private ScaleName scale;
 
    public Temperature() {
        number = 0.0;
        scale = ScaleName.fahrenheit;
    }
 
    public Temperature(double number, ScaleName scale) {
        this.number = number;
        this.scale = scale;
    }
"You can create a Temperature object (an instance of the Temperature class) by calling new Temperature() with nothing between the parentheses. You can also create a Temperature object by calling new Temperature(70.0, ScaleName.fahrenheit), or new Temperature(0.0, ScaleName.celsius), or with some other number and some other scale name.
A constructor declaration looks like a method declaration, but a constructor's name is the same as the corresponding class's name, and a constructor declaration has no return type (not even void).

Calling a superclass's constructor:

class TemperatureNice extends Temperature {
 
    public TemperatureNice() {
        super();
    }
 
    public TemperatureNice(double number) {
        super(number);
    }
"Whenever the program executes new TemperatureNice() (calling the parameterless TemperatureNice constructor), have the program call super(). In this example, calling super() means calling new Temperature() (calling the parameterless Temperature constructor.)
"Whenever the program executes new TemperatureNice(70.0) (calling a one-parameter TemperatureNice constructor), have the program call super(70.0). In this example, calling super(70.0) means calling new Temperature(70.0) (calling a one-parameter Temperature constructor.)"

Working with arrays (Part 1):

int guests[] = new int[10];
"Create a variable named guests. The variable guests will refer to an array of int values. Make space for an array of ten int values. Let guests refer to that array space."

Working with arrays (Part 2):

for (int roomNum = 0; roomNum < 10; roomNum++) {
    guests[roomNum] = 0;
}
"Store 0 in each of the ten guest array locations."

Working with arrays (Part 3):

int capacities[] = {4, 4, 2, 4, 2, 2, 4, 2, 0, 2};
"Create a variable named capacities. The variable capacities will refer to an array of int values. Make space for an array of int values. Store the numbers 4, 4, 2 (and so on) in the array locations. Let capacities refer to that array space."

Working with arrays (Part 4):

Room rooms[] = new Room[10];
"Create a variable named rooms. The variable rooms will refer to an array of Rooms. Make space for an array of Rooms. Let rooms refer to that array space."

Working with arrays (Part 5):

for (int roomNum = 0; roomNum < 10; roomNum++) {
    rooms[roomNum] = new Room();
}
"Make space for ten Room objects. Make each element of the rooms array refer to one of those Room objects."

Using generics:

ArrayList<String> people = new ArrayList<String>();
"Create a variable named people. The variable people will refer to a collection of Strings (that is, an ArrayList of Strings). Make space for an ArrayList of Strings. Let people refer to that ArrayList."

A try...catch statement:

try {
 
} catch (NumberFormatException e) {
 
} finally {
 
}
"Attempt to execute the statements inside the first pair of curly braces. If nothing goes wrong (that is, if the execution doesn't throw any exceptions) then bypass the catch clause (the statements inside the second pair of curly braces).
"But if something goes wrong (that is, if the execution throws an exception) then jump immediately from the offending statement to the catch clause. Cross your fingers and hope that the offending statement threw a NumberFormatException. If so, then execute the statements inside the catch clause, and then move on to execute the statements that come after the catch clause.
"Alas, if the offending statement threw an exception that's not a NumberFormatException, then return prematurely from the method that you're currently executing (the method containing this try…catch statement). Return to whatever method called this current method, and hope that the calling method can deal sensibly with the nasty exception.
"One way or another (exception or no exception, returning prematurely or not), execute the statements inside the finally clause (the third set of curly braces)."

Using access modifiers (Part 1):

package com.allmycode.utilities;
 
public class First {
 
}
 
class Second {
 
}
"The code in this file belongs to a package named com.allmycode.utilities. The class First is available to any Java code. The class Second is available to Java code only if that code is also in the com.allmycode.utilities package."

Using access modifiers (Part 2):

package com.allmycode.utilities;
 
class Third {
    public amountInAccount = 50.22;
    int numOfThings = 22;
    private int stuff = 10;
    protected int x = 40;
"The code in this file belongs to a package named com.allmycode.utilities. The variable amountInAccount is available to any Java code. (Any Java code can make reference to the name amountInAccount.) The variable numOfThings is available to Java code only if that code is also in the com.allmycode.utilities package. The variable stuff isn't available to any code outside the Third class. The variable x is available to Java code only if that code is either in the com.allmycode.utilities package or that code is in a subclass of the Third class."

Implementing an interface:

class GameFrame extends JFrame
    implements ActionListener, ItemListener {
 
}
"I (the GameFrame programmer) agree to provide bodies (implementations) for any bodiless methods declared in the ActionListener and ItemListener interfaces."

A lambda expression:

(customer) -> customer.name.equals("Burd")
"Return true if the customer's name is "Burd"; return false otherwise."
customerList.stream()
   .filter((customer) -> customer.name.equals("Burd"))
"Take the objects in the customerList. Using the stream method, send those objects, one-by-one, to a filter method. The filter method applies the lambda expression to each object, getting true for customers whose name is "Burd", and false for all the other customers. As a result, the filter method sends all and only the customers whose name is "Burd" to whatever method comes next in the assembly line."

A method reference:

Customer::isBurd
"Execute the statements in the body of the Customer class's isBurd method."
class Customer {
  String name;
  
  public boolean isBurd() {
    return name.equals("Burd");
  }
 
  // More code goes here
}
 
customerList.stream().filter(Customer::isBurd)
"Take the objects in the customerList. Using the stream method, send those objects, one-by-one, to a filter method. The filter method applies the Customer class's isBurd method to each object, getting true for customers whose name is "Burd", and false for all the other customers. As a result, the filter method sends all and only the customers whose name is "Burd" to whatever method comes next in the assembly line."
  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win $500. Easy.