B: Java Long Form - All Commands By Category#

Here are all the Java commands, in alphabetical order within each category.

Starting a File or Method#

class#

Every Java file must use class to be the container that holds the code. The name of the class must exactly match the name of the file, and this name is case-sensitive.

package#

This word is used to create a group of classes, a file directory. It is unnecessary when first learning Java but used later to organize files.

Modifiers - Access and Other#

abstract#

This word is used on either a class or a method.

An abstract class means that the class cannot be used as a data type, that is, no object of the class can be made. The class will be used as part of an inheritance structure and holds common code of the subclasses. If any class contains an abstract method, then that class must be an abstract class.

An abstract method is a method that is declared but not defined. Basically we write the first line of the method and end with a semi-colon. Here is an example:

public abstract double calcSalary(double hours);

Methods in an interface are abstract, by default.

final#

final may be used with a variable, a method, or a class.

A final variable can only have its value set once. This value may be set at run-time or statically by the programmer, but once set, can never be changed. final variables are used for constants. The convention is to name constants with uppercase letters separated by _. Here are some constants:

final int DAYS_IN_JANUARY = 31;

final double INTEREST_RATE = 0.025;

final int NUM_EMPLOYEES;
final EmpRecord[] EMPLOYEES:
System.out.println("Enter your number of employees: ");
NUM_EMPLOYEES = input.nextInt();  //Assuming input is a Scanner on standard input
EMPLOYEES = new EmpRecord[NUM_EMPLOYEES];

When a method is final, it cannot be overridden in any of its subclasses.

A class that is declared final cannot be extended, that is, have any subclasses.

private#

private is used for variables or methods, when they are members of a class, and restricts access to only inside that class. It is often used as a signal to other programmers that this method should not be called elsewhere; it is likely a helper method to a bigger set of logic.

Best practices indicates that we should use private versus public and protected, unless there is a reason not to.

protected#

protected is used for variables or methods, when they are members of a class, and restricts access to only inside that package, and if a subclass is in another package, it gets access too. It blocks access to any code outside of the package and outside of any subclasses.

public#

public is used for variables or methods of classes, or on classes directly, and access is given to any code anywhere. If no modifiers are used on a class member, then the member has access only from anywhere within the package. public gives a greater scope of access than omitting modifiers would.

static#

static means before run-time. Run-time could be considered as “dynamic” and is signified by the absence of static, not by a special reserved word.

The most common place you would use static in first year programming is as a modifier on methods, for example:

public static void main...

A static method is one that may be called directly, without first creating an object, in the file and by using the class path from other files. A method without the static modifier must be called by using dot notation to send the message to an object.

When static is used to modify a variable, then that variable will be in the same memory location for all objects of that class, that is, it is a shared variable. This is often used for communication between objects or for constants.

strictfp#

Different computers have different hardware, and floating point operations are not as standard as many other operations. Using strictfp on a method, class or interface ensures that the [IEEE 754]{https://standards.ieee.org/ieee/754/6210/} standard is followed.

synchronized#

This is used in parallel programming to control the access of shared data.

transient#

Used in special programming where you need to serialize objects.

volatile#

Used typically in parallel programming when you want to control how a variable is handled by the cache. When a volatile variable changes value, all threads will “see” the new value.

Data Types#

Primitive Data Types#

boolean#

A variable declared as boolean can only hold either the value true or the value false.

byte#

An integer using 8 bits, representing \(-128\) to \(+127\). The programmer must be aware that overflows do not result in exceptions in Java. The program will just keep running and may produce incorrect results.

char#

A char variable holds Unicode 16-bit values, from \u0000 to \uffff. Normally we just assign a keyboard character or visible character to such a variable. For example:

char oneChar = 'A';
char secondChar = '☺';
char thirdChar = '\u263A'; //Another smiley

You can assign any character in the 16-bit most common subset of Unicode, by simply looking up the code.

double#

double provides a double-precision floating point number with 15 significant digits. The range in magnitude is from about \(4.9 X 10^-308\) to \(1.7 X 10^308\). This is not accurate enough for money, where other Java Library types should be imported.

float#

float provides a single-precision floating point number with 7 significant digits. The range in magnitude is from about \(1.4 X 10^-38\) to \(3.4 X 10^38\). This is not accurate enough for money, where other Java Library types should be imported.

int#

An int uses 32 bits and handles the range \(-2147483648\) to \(+2147483647\). The programmer must be aware that overflows do not result in exceptions in Java. The program will just keep running and may produce incorrect results.

long#

A long provides 64 bits for an integer, giving the range \(-9,223,372,036,854,775,808\) to \(+9,223,372,036,854,775,807\). The programmer must be aware that overflows do not result in exceptions in Java. The program will just keep running and may produce incorrect results.

short#

A short provides 16 bits for an integer, giving the range \(-32,768\) to \(+32,767\). The programmer must be aware that overflows do not result in exceptions in Java. The program will just keep running and may produce incorrect results.

Reference Data Types, Including User (= Programmer) Defined#

class#

The class word is used to create a new data type. Note that the file name and the class name must match.

enum#

This creates a new data type, which is an enumeration of constants to the integers 0, 1, 2, … This data type should be in its own file and again the name of the enum must match the name of the file. For example:

// In file Move.java
public enum Move {
    LEFT, 
    UP, 
    RIGHT, 
    DOWN {   @Override
             public Move next(){ //wrap to first move, LEFT
                return LEFT;
             }
          };

    public Move next() {
        //only for LEFT, UP and RIGHT.  DOWN has own such method, see above.
        return values()[ordinal() + 1];
    }
}

//In file with our main
Move x = Move.RIGHT;
for (int i = 0; i < 4; i++){
   System.out.println(x);
   x = x.next();
}
System.out.println(x);
RIGHT
DOWN
LEFT
UP
RIGHT

extends#

This word is used to create a hierarchical relationship between classes. Suppose we have the following two classes, ClassA and ClassB:

public class ClassA{
}

public class ClassB extends ClassA{
}

ClassA is the superclass of ClassB. ClassB is a subclass of ClassA.

implements#

Used with a class, to show that the features of the interface are present. For example:

public class XXX implements YYY{
      .
      .
      .
}

would mean that the new class XXX defined here matches the specification in the interface YYY.

instanceof#

instanceof is a binary operator, used to determine whether the item on the left is an instance of the data type (class) on the right. The value is either true or an exception is thrown. For example:

Integer x = 5;
System.out.println(x instanceof Integer);
System.out.println(x instanceof Float);
true
|   System.out.println(x instanceof Float);
incompatible types: java.lang.Integer cannot be converted to java.lang.Float

Please do not use instanceof when placing the code in the proper location (that is, in the proper class or subclass) will save creating a conditional structure. Saying this another way, I find that this command is not useful, and its existence may lead to poor programming containing more if and try statements, without proper code placement.

interface#

Similar to a class, but contains mainly declarations for data and methods that are required in a specification of a class. Normally a class is made to “implement” an interface. No data types of interfaces are created, but data types of corresponding classes are created and guaranteed to have the given signatures from the interface.

public interface YYY{
   //Put data and method declarations here
}

new#

new is used to make an object dynamically, on the heap, which is a special part of memory. new is used in front of the constructor to create these objects. Here is a normal creation of an object:

Integer x = new Integer(5); //`new` together with call to constructor.

Arrays, Strings, and wrappers are exceptions. These objects are made dynamically, however there is a special syntax that may be used. For example:

int[] intArray = new int[5]; //Makes an array with room for 5 ints.  Does not
                             //look like a call to a constructor.

String name = "Rosanna"; //Makes a String (an object) to which you can send messages.
                         //`new` is not used.

Integer x = 5; //Makes an integer with value of 5.  No `new` is used.

null#

null means “nothing”. If an object is null, it does not exist and we cannot send dot messages to it without getting an exception. We can compare to null to check for this condition.

super#

super is used to force traveling up the hierarchy, when classes are related by extends.

super() calls the constructor, one level up the hierarchy created by extends.

this#

this is used to reference attributes of the current object. It is particularly important when local names are the same as attribute names, and is used to make this distinction.

this() calls a constructor in the same class. It is good practice to write code for the most specific constructor, with the most parameters. All other constructors should use this() to call the most specific constructor.

Other#

false#

One of two values for a boolean.

true#

The other of two values for a boolean.

void#

void is considered a return type and means that nothing will be returned.

Operators#

Assignment#

= assigns the value on the right side to the memory name on the left side.

Arithmetic#

+ is a binary operator, that adds the two values together.

- is both a unary and a binary operator. As a unary operator, it makes a value negative. As a binary operator, it subtracts the right value from the left value.

* is a binary operator, that multiplies the two values together.

/ is a binary operator, that divides the left value by the right value. Note that type is maintained, so when dividing two integers the fractional component (if it exists) is dropped.

System.out.println(5 / 2);
System.out.println(5.0 / 2);
System.out.println(5 / 2.0);
System.out.println(5.0 / 2.0);
System.out.println(5.25 / 4.0);

% is a binary operator, that determines the remainder of the division, not the decimal portion of the division.

System.out.println(5 % 2);
System.out.println(5.0 % 2);
System.out.println(5 % 2.0);
System.out.println(5.0 % 2.0);
System.out.println(5.25 % 4.0);
1
1.0
1.0
1.0
1.25

++ is a unary operator, which increments the value by one. This operator may be placed on the left of its operand, meaning that the increment happens before other calculations. Otherwise, this operator may be placed on the right of its operand, meaning that the increment happens after other calculations. Too much use of this operator can make code quite unreadable, so it should be reversed for obvious cases where the only thing happening is the increment, for example, on a line by itself: i++;.

--

Bit-wise#

&#

Performs bit-wise logical and on the binary representation of the two operands.

|#

Performs bit-wise logical or on the binary representation of the two operands.

^#

Performs bit-wise logical exclusive or on the binary representation of the two operands.

<<#

Performs bit-wise shift to the left on the binary representation of the left operand. The right operand is how many bits to shift by. 0s are shifted into the right bits. The number essentially becomes bigger in magnitude. << is often used to do multiplication by a power of 2, since a bit-wise operation is much faster than actual multiplication. For example, x << 3 multiplies x by \(2^3 = 8\). Each left shift multiplies the number by 2. This is only meaningful in this sense for integers.

>>#

Performs bit-wise shift to the right on the binary representation of the left operand. The right operand is how many bits to shift by. The sign bit, either 0 or 1 is shifted into the leftmost bits. The number essentially becomes smaller in magnitude. >> is often used to divide by a power of 2, since a bit-wise operation is much faster than actual division. For example, x >> 3 divides x by \(2^3 = 8\). Each right shift divides the number by 2. This is only meaningful in this sense for integers.

Combination#

These operations are shortcuts for binary operations which will then have their result stored back to one of the operands. The shortcut is created by combining the assignment or bit-wise operator together with =.

+=#

x += 3 is the shortcut for x = x + 3

-=#

x -= 3 is the shortcut for x = x - 3

*=#

x *= 3 is the shortcut for x = x * 3

/=#

x /= 3 is the shortcut for x = x / 3

%=#

x %= 3 is the shortcut for x = x % 3

&=#

x &= 3 is the shortcut for x = x & 3

|=#

x |= 3 is the shortcut for x = x | 3

^=#

x ^= 3 is the shortcut for x = x ^ 3

<<=#

x <<= 3 is the shortcut for x = x << 3

>>=#

x >>= 3 is the shortcut for x = x >> 3

Comparison#

==#

Determines whether the two operands are the same, at the primitive level. For example,

int x = 5;
x = 5 * 5;
System.out.println(x == 25);
true

== should not normally be used when comparing objects, and .equals() should be used instead. For example,

String x = "Hi";
String y = new String("Hi");
System.out.println(x == y);
System.out.println(x.equals(y));
false
true

!=#

This is the not equals Boolean operator.

<#

Less than Boolean operator.

>#

Greater than Boolean operator.

<=#

Less than or equal to Boolean operator.

>=#

Greater than or equal to Boolean operator.

Logical#

&&#

Binary Boolean and operator, which is true if and only if both operands are true.

||#

Binary Boolean or operator, which is true if either or both of the operands are true.

!#

Unary Boolean not operator, which is true only if its operand is false.

Delineation#

{}#

For bodies of methods and control structures.

()#

For parameters of methods.

<>#

For generics.

Control Structures#

Conditional#

default#

default is used in a switch statement, as the last case, to handle what should be done when no other cases match.

else#

else is used with and if. When the specific Boolean expression at the if is false, controls moves to the body of code found at the else.

if#

if is used to create conditional control over the execution of code, with a Boolean expression to check. Only if the Boolean expression is true then the body of code associated with the if is executed.

double mark = 78.28;
//...
if (mark < 50.0){
   System.out.println("Please try again");
}
else if (mark < 60.0){
   System.out.println("D");
}
else if (mark < 70.0){
   System.out.println("C");
}
else if (mark < 84.0){
   System.out.println("B");
}
else{
   System.out.println("A");
}
B

switch#

This is a multi-way conditional, that can replace a long if-else if-else if-…-else chain with faster execution as the evaluation is done only once. A switch is used when the checking is for equality on byte, short, char, int, their wrappers, enumerated types, and Strings. Normally, breaks are used to ensure that only one particular block of code is executed, as the semantics state that execution continues through successive code until a break is encountered. Here is an example:

int month = 4;
//...
switch (month){
   case 1: 
   case 2:
      System.out.println("Winter");
      break;
   case 3:
      System.out.println("Spring begins");
      break;
   case 4:
   case 5:
      System.out.println("Spring");
      break;
   case 6:
      System.out.println("Summer begins");
      break;
   case 7:
   case 8:
      System.out.println("Summer");
      break;
   case 9:
      System.out.println("Autumn begins");
      break;
   case 10:
   case 11:
      System.out.println("Autumn");
      break;
   case 12:
      System.out.println("Winter begins");
      break;
   default:
      System.out.println("Invalid month");
}
Spring

Since Java 14, there is a new version of switch that uses -> syntax and does not use a break.

int month = 4;
//...
//
switch (month){
   case 1, 2 ->
      System.out.println("Winter");
   case 3 ->
      System.out.println("Spring begins");
   case 4, 5 ->
      System.out.println("Spring");
   case 6 ->
      System.out.println("Summer begins");
   case 7, 8 ->
      System.out.println("Summer");
   case 9 -> 
      System.out.println("Autumn begins");
   case 10, 11 ->
      System.out.println("Autumn");
   case 12 ->
      System.out.println("Winter begins");
   default ->
      System.out.println("Invalid month");
}
Spring

The new version of switch can both do things and return a value. Here is an example where the message is printed and the month is moved to the next.

int month = 12;
//...
month = switch (month){
   case 1, 2 ->{
      System.out.println("Winter");
      yield month + 1;
   }
   case 3 ->{
      System.out.println("Spring begins");
      yield 4;
   }
   case 4, 5 ->{
      System.out.println("Spring");
      yield month + 1;
   }
   case 6 ->{
      System.out.println("Summer begins");
      yield 7;
   }
   case 7, 8 ->{
      System.out.println("Summer");
      yield month + 1;
   }
   case 9 ->{
      System.out.println("Autumn begins");
      yield 10;
   }
   case 10, 11 ->{
      System.out.println("Autumn");
      yield month + 1;
   }
   case 12 ->{
      System.out.println("Winter begins");
      yield 0;
   }
   default ->{
      System.out.println("Invalid month");
      yield month;
   }
};  //NOTE ";" needed here to end the assignment statement

System.out.println("\n month is now: " + month);
Winter begins

 month is now: 0

yield#

Used with the new version of the switch statement (with the -> syntax), since Java 14, to return a value from a switch. This means that a switch may be used in an assignment statement or as part of a return statement.

Repetition#

do#

do together with while is used for repetition that happens at least once since the stopping condition is placed at the end of the loop body. Here are two examples of do-while loops, with the second one showing how at least one execution of the body will occur:

int x = 5;
do{
   System.out.println(x);
   x = x + 2;
}while (x < 20);

System.out.println("Now we are here");
x = 5;
do{
   System.out.println(x);
   x = x + 1;
}while (x < 5);
5
7
9
11
13
15
17
19
Now we are here
5

for#

Java has two kinds of for loops: the regular one and the for-each loop.

The regular for loop is syntactic sugar for a while loop, ensuring placement of the initialization statement, the continuation condition, and the increment statement all at the top of the loop body. Here is an example:

for (int i = 5; i < 20; i++){
   System.out.println(i);
}
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

The for-each loop relies on the iterator being defined for a data type. Using the for-each loop ensures that the body of the loop executes once for each item in a structure.

int[] myList = {1, 4, 6, 2, 8, 9};
for (int item : myList){
   System.out.println(item);
}
1
4
6
2
8
9

while#

while can be used with do to create a “do-while” loop or alone for a “while” loop. The format is simple, in that a Boolean expression is associated with the while and the loop body is executed 0 or more times, as long as the Boolean expression remains true. Note that the programmer must remember to initialize and change control variables. Here are two examples, with the second loop showing that sometimes the body never executes:

int x = 5;
while (x < 20){
   System.out.println(x);
   x = x + 2;
}

System.out.println("Now we are here");
x = 5;
while (x < 5){
   System.out.println(x);
   x = x + 2;
}
5
7
9
11
13
15
17
19
Now we are here

Stopping#

break#

break is used in Java to stop a loop or stop a code block in a switch. You should try to avoid using break in loops, and rather make your loop condition tighter. break, however, is essential as part of switch statements.

catch#

catch is used with try to list which exceptions will have special code executed.

continue#

continue is used in a loop and is similar to break but instead of stopping the loop completely, it moves the execution back to the top of the loop and executes the next change statement before deciding whether to continue with the loop body again.

finally#

finally is used with try-catch to contain code that should execute after the code for exceptions executes.

return#

return is used to exit a method, and may contain a return value along with the command. The type of the return value must match the return type of the method.

throw#

throw causes an exception to happen.

throws#

throws tells the CPU not to worry about that particular exception within the given code. A command in the code can throw that particular exception, but in your code, you do not want to catch it or do anything about it. Be very careful when passing exceptions onwards this way.

try#

try is used when you want to check whether a piece of code throws an exception, thus preventing your poor user from seeing a computer crash or a red message. Together with catch, you can write specific code that should execute when an exception is thrown. try is often used with input, so that mismatched data types may be handled gracefully.

Testing#

assert#

assert is used for checking whether an expected condition is true at run-time. If the condition is not true, then an AssertionError happens, stopping the program. For example, if you are writing a method, where correctness relies on the parameter being positive then you might write:

public static int myMethod(int value){
   assert value > 0;

   //now write the rest of the method...
}

You have forced a run-time error if value is not positive in this method, assuming that assertion testing is turned on.

Including Code from Elsewhere#

import#

This is used to include a library, typically from the Java Libraries, but could also be used with your own local library.

native#

This is used to give the declaration of a method that is defined in C/C++. Methods that are native cannot have bodies. This is used when there is already existing code, written in C/C++, that our Java program needs to access. Examples include system calls, legacy code, and hardware access.