Data types and Control Statements
Data types and Control Statements
You know, the Java programming language has over 50 reserved keywords which have
special meaning for the compiler and cannot be used as variable names. Following is
a list of Java keywords in alphabetical order. You can click on an individual
keyword to see its description and usage example.
Flow control:
yield
Enumeration: enum
continued..
# abstract
An abstract method:
# assert
The assert keyword is used in assertion statement which is a feature of the Java
programming language since Java 1.4. Assertion enables developers to test
assumptions in their programs as a way to defect and fix bugs.
1. Syntax of assert statement
Syntax of an assert statement is as follow (short version):
assert expression1;
or (full version):
assertexpression1 : expression2;
Where:
Assertion can be enabled or disable specifically for named classes or packages. For
more information on how to enable and disable assertion, read this article.
System.out.println("Pass");
}
}
When running the program above with this command:
at AssertionExample.main(AssertionExample.java:6)
But the program will continue and print out “Pass” if we pass a number less than
10, in this command:
And the following example is using the full version of assert statement:
System.out.println("OK");
}
}
When running the program above with this command:
at AssertionExample2.main(AssertionExample2.java:6)
Generally, assertion is enabled during development time to defect and fix bugs, and
is disabled at deployment or production to increase performance.
# continue
the continue keyword is used to stop execution of a current iteration in a for loop
or a while loop, then advance to the next iteration. The statements after the
continue keyword won’t be executed. The syntax is as follows:
for/while (expressions) {
// statemenst 1...
if (condition) {
continue;
}
// statements 2...
}
The following example uses continue keyword to skip the even value of the variable
i, thus the for loop will print out all the odd numbers from 1 to 100:
int count = 1;
while (count <= 100) {
if (count % 2 != 0) {
count++;
continue;
}
System.out.println(count);
count++;
}
# default
Basically, there are 3 places you can use the default keyword in Java:
In the following method, the default keyword is used in as switch case statement to
return the default value for other cases:
In the following example, the default keyword is used to declare default value for
a method in a custom annotation class:
}
}
The purpose of default method is to add new methods to an interface that will not
break the existing subtypes of that interface.
# enum
the enum keyword is used to declare a new enumeration type. This keyword has been
introduced since Java 5. The declaration syntax for an enum type is as follows:
enum <name> {
<enum_constant_1>,
<enum_constant_2>,
...
<enum_constant_n>
<enum_constructor>
// other variables & methods as usual
}
An enum constant can be declared as follows:
class Foo {
enum DayOfWeek {MON, TUE, WED, THU, FRI, SAT, SUN};
}
A simple enum type declared in a separate Java file:
enum Day {
MON(1), TUE(2), WED(3), THU(4), FRI(5), SAT(6), SUN(7);
Day(int dayNumber) {
this.dayNumber = dayNumber;
}
enum Priority {
LOW {
int getPriorityNumber() {
return 0;
}
},
NORMAL {
int getPriorityNumber() {
return 1;
}
},
HIGH {
int getPriorityNumber() {
return 2;
}
},
SEVERE {
int getPriorityNumber() {
return 3;
}
};
# instanceof
The instanceof operation returns true if the variable is of type (or subtype) of
the specified calss. The above code will give the output "A String" because msg is
of type String.
return false;
}
}
# native
the return keyword is used to stop execution of a method and return a value for the
caller. Usage of this keyword is as following:
return value;
String getName() {
return "Peter";
}
int getAge() {
int myAge = 29;
return myAge;
}
Object getObject() {
Object myObject = new Object();
// do something with my object...
return myObject;
}
The return keyword can also be used to stop execution of a void method and return
to the caller, for example:
void doSomething() {
// do something
if (condition) {
return;
}
}
# static
the static keyword can be applied for inner classes, methods and variables.
- Static methods and variables are shared among all instances of a class. They can
be invoked and accessed without creating new instances of the class. The following
example shows a class contains a static variable, a static method and a regular
method:
public class Car {
static String color;
void brake() {
// stop
}
}
The static variable color and static method beep() can be accessed like this:
Car.color = "Red";
Car.beep();
whereas the regular method brake() must be called on an instance of Car class:
# strictfp
The strictfp keyword is used to force the precision of floating point calculations
(float or double) in Java conform to IEEE’s 754 standard, explicitly. Without using
strictfp keyword, the floating point precision depends on target platform’s
hardware, i.e. CPU’s floating point processing capability. In other words, using
strictfp ensures result of floating point computations is always same on all
platforms.
The strictfp keyword can be applied for classes, interfaces and methods.
class StrictFPMethod {
strictfp double computeTotal(double x, double y) {
return x + y;
}
}
# switch
switch (expression) {
case constant_1:
// statement 1
break;
case constant_2:
// statement 2
break;
case constant_3:
// statement 3
break;
//...
case constant_n:
// statement n
break;
default:
// if all the cases do not match
}
int number = 3;
switch (number) {
case 1:
text = "One";
break;
case 2:
text = "Two";
break;
case 3:
text = "Three";
break;
default:
text = "Other number";
}
The following example shows a switch statement that tests for a String variable,
without a default block. It will output: The distance from earth to Jupiter is: 4
long distanceFromEarth = 0;
switch (planet) {
case "Mars":
distanceFromEarth = 3;
break;
case "Saturn":
distanceFromEarth = 5;
break;
case "Jupiter":
distanceFromEarth = 4;
break;
case "Venus":
distanceFromEarth = 1;
break;
}
The following example shows a switch statement that tests for an enum
type, Priority. It will output the result: Task priority: 3
int taskPriority = 0;
switch (priority) {
case LOW:
taskPriority = 1;
break;
case NORMAL:
taskPriority = 2;
break;
case HIGH:
taskPriority = 3;
break;
case SEVERE:
taskPriority = 4;
break;
}
1
public enum Priority { LOW, NORMAL, HIGH, SEVERE }
From Java 14, you can use switch block as an expression. For example:
# synchronized
The synchronized keyword is used for code blocks and methods where thread-safe
matters and for multi-threaded (concurrent) programming. A synchronized method or a
synchronized statement can be executed by only one thread at a time.
synchronized (expression) {
// synchronized code block
}
- The current executing thread will try to acquire a lock before executes
the synchronized code block:
For synchronized statement: the monitor associates with the object returns by the
expression.
For synchronized method:
If the method is static, the lock associates with the Class object of the class in
which the method is declared.
If the method is non-static, the lock associates with this – the object for which
the method is invoked.
- If the lock is not acquired by any thread, the current executing thread
will own the lock and execute the synchronized code block.
- While the current executing thread owns the lock, no other threads can
acquire that lock.
- When the synchronized code block completes, the current executing thread
releases the lock.
class Counter {
private static int count;
static synchronized void increase() {
count++;
}
}
class BankAccount {
private double balance;
synchronized void withdraw(double amount) {
this.balance -= amount;
}
synchronized void deposit(double amount) {
this.balance += amount;
}
}
The following code example shows a synchronized statement is applied for a code
block, not a method:
Object lock = new Object();
synchronized (lock) {
System.out.println("Synchronized statement");
}
# transient
the transient keyword is used to mark a member variable (field) not a part of the
persistent state of an object, i.e. the field will not be persisted when its parent
object is serialized.
class Rectangle {
int width;
int height;
transient long area;
}
When an object of Rectangle class is being serialized, the fields width and height
will be persisted, but the field area.
The transient keyword can be only applied for member variable, not for class,
method and local variable.
# volatile
The volatile keyword can be applied for only member variables (fields). When a
volatile variable is accessed concurrently by threads, its value is updated
consistently among threads. In some cases, using volatile can be an alternative to
using synchronized code.
Example:
class VolatileExample {
volatile int x;
}
Rules:
The volatile keyword cannot be applied for class, method and local
variable.
A final variable cannot be declared volatile.
# var
var keyword is added to the Java language since Java 10 (JDK 10), supporting a new
feature called local variable type inference, in which Java compiler guesses the
type of the variables based on the surround context – allowing programmers to not
declare the type explicitly.
// return a map
}
Without using var, you have to specify the type explicitly when calling the foo()
method like this:
You can use var only for local variables (in methods). It cannot be used for
instance variables (at class level).
You cannot use var in Lambda expressions.
You cannot use var for method signatures (in return types and parameters).
And remember, you cannot use var to declare a variable without explicit
initialization, hence the following:
var x;
is not allowed, since local variable declaration requires initialization on the
right side. That also means this declaration is not valid:
var x = null;
# record
the record keyword is used to declare a special class type that acts as a “data
carrier” i.e. model class or POJO class. This keyword is added to the Java language
since JDK 14.
Consider an example:
The Java compiler will generate appropriate constructor, getters and setters for
all fields, equals(), hashCode() and toString() methods for a record type. The
record type Point above is equivalent to code the following class:
The record type feature is under review in JDK 14 (preview) and it will be
finalized in future JDK releases.
# yield
The yield keyword is added to the Java language since Java 14, for implementing
switch expression.
If the switch block is used with new form of switch label “case L ->”, the yield
keyword is used to return a value in a case arm that is a block of code. For
example:
};
Note that the code after yield can be an expression that returns a value. For
example:
case 4, 6, 9:
yield foo();
case 2:
yield (year % 4 == 0 ? 29 : 28);
default:
throw new IllegalArgumentException();
};