Thesyntax of Javaisthe set of rulesdefining how aJavaprogram is written and interpreted.

A snippet of Java code with keywords highlighted in bold blue font

Thesyntaxis mostly derived fromCandC++.Unlike C++, Java has no global functions or variables, but has data members which are also regarded asglobal variables.All code belongs toclassesand all values areobjects.The only exception is theprimitive data types,which are not considered to be objects for performance reasons (though can be automatically converted to objects and vice versa viaautoboxing). Some features likeoperator overloadingorunsigned integerdata typesare omitted to simplify the language and avoid possible programming mistakes.

The Java syntax has been gradually extended in the course of numerous majorJDKreleases,and now supports abilities such asgeneric programmingandanonymous functions(function literals, called lambda expressions in Java). Since 2017, a new JDK version is released twice a year, with each release improving the language incrementally.

Basics

edit

Identifier

edit

Anidentifieris the name of an element in thecode.There are certain standardnaming conventionsto follow when selecting names for elements. Identifiers in Java arecase-sensitive.

An identifier can contain:

  • Any Unicode character that is a letter (including numeric letters likeRoman numerals) or digit.
  • Currency sign(such as ¥).
  • Connecting punctuation character (such as_).

An identifier cannot:

  • Start with a digit.
  • Be equal to a reserved keyword, null literal orBooleanliteral.

Keywords

edit
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static var
class finally long strictfp void
const float native super volatile
while

Literals

edit
Integers
binary(introduced in Java SE 7) 0b11110101(0bfollowed by a binary number)
octal 0365(0followed by an octal number)
hexadecimal 0xF5(0xfollowed by a hexadecimal number)
decimal 245(decimal number)
Floating-pointvalues
float 23.5F,.5f,1.72E3F(decimal fraction with an optional exponent indicator, followed byF)
0x.5FP0F,0x.5P-6f(0xfollowed by a hexadecimal fraction with a mandatory exponent indicator and a suffixF)
double 23.5D,.5,5.,1.72E3D(decimal fraction with an optional exponent indicator, followed by optionalD)
0x.5FP0,0x.5P-6D(0xfollowed by a hexadecimal fraction with a mandatory exponent indicator and an optional suffixD)
Character literals
char 'a','Z','\u0231'(character or a character escape, enclosed in single quotes)
Boolean literals
boolean true,false
null literal
null reference null
String literals
String "Hello, World"(sequence of characters and character escapes enclosed in double quotes)
Characters escapes in strings
Unicodecharacter \u3876(\ufollowed by the hexadecimal unicode code point up to U+FFFF)
Octalescape \352(octal number not exceeding 377, preceded by backslash)
Line feed \n
Carriage return \r
Form feed \f
Backslash \\
Single quote \'
Double quote \ "
Tab \t
Backspace \b

Integer literals are ofinttype by default unlesslongtype is specified by appendingLorlsuffix to the literal, e.g.367L.Since Java SE 7, it is possible to include underscores between the digits of a number to increase readability; for example, a number145608987can be written as145_608_987.

Variables

edit

Variablesare identifiers associated with values. They are declared by writing the variable's type and name, and are optionally initialized in the same statement by assigning a value.

intcount;//Declaring an uninitialized variable called 'count', of type 'int'
count=35;//Initializing the variable
intcount=35;//Declaring and initializing the variable at the same time

Multiple variables of the same type can be declared and initialized in one statement using comma as a delimiter.

inta,b;//Declaring multiple variables of the same type
inta=2,b=3;//Declaring and initializing multiple variables of the same type

Type inference

edit

Since Java 10, it has become possible toinfer typesfor the variables automatically by usingvar.

// stream will have the FileOutputStream type as inferred from its initializer
varstream=newFileOutputStream("file.txt");

// An equivalent declaration with an explicit type
FileOutputStreamstream=newFileOutputStream("file.txt");

Code blocks

edit

The separators{and}signify a code block and a new scope. Class members and the body of amethodare examples of what can live inside these braces in various contexts.

Inside of method bodies, braces may be used to create new scopes, as follows:

voiddoSomething(){
inta;

{
intb;
a=1;
}

a=2;
b=3;// Illegal because the variable b is declared in an inner scope..
}

Comments

edit

Java has three kinds ofcomments:traditional comments,end-of-line commentsanddocumentation comments.

Traditional comments, also known as block comments, start with/*and end with*/,they may span across multiple lines. This type of comment was derived from C and C++.

/* This is a multi-line comment.
It may occupy more than one line. */

End-of-line comments start with//and extend to the end of the current line. This comment type is also present in C++ and in modern C.

// This is an end-of-line comment

Documentation comments in the source files are processed by theJavadoctool to generate documentation. This type of comment is identical to traditional comments, except it starts with/**and follows conventions defined by the Javadoc tool. Technically, these comments are a special kind of traditional comment and they are not specifically defined in the language specification.

/**
* This is a documentation comment.
*
* @author John Doe
*/

Universal types

edit

Classes in the package java.lang are implicitly imported into every program, as long as no explicitly-imported types have the same names. Important ones include:

java.lang.Object

edit

java.lang.Objectis Java'stop type.Superclass of all classes that do not declare a parent class. All values can be converted to this type, although for primitive values this involvesautoboxing.

java.lang.String

edit

java.lang.Stringis Java's basic string type.Immutable.Some methods treat eachUTF-16code unit as a "character", but methods to convert to anint[]that is effectivelyUTF-32are also available.

java.lang.Throwable

edit

java.lang.Throwableis supertype of everything that can bethrown or caughtwith Java'sthrowandcatchstatements.

Program structure

edit

Java applications consist of collections of classes. Classes exist in packages but can also be nested inside other classes.

mainmethod

edit

Every Java application must have an entry point. This is true of both graphical interface applications and console applications. The entry point is themainmethod. There can be more than one class with amainmethod, but the main class is always defined externally (for example, in amanifest file). Themainmethod along with the main class must be declaredpublic.The method must bestaticand is passed command-line arguments as an array of strings. UnlikeC++orC#,it never returns a value and must returnvoid.

publicstaticvoidmain(String[]args){
}

Packages

edit

Packages are a part of a class name and they are used to group and/or distinguish named entities from other ones. Another purpose of packages is to govern code access together with access modifiers. For example,java.io.InputStreamis a fully qualified class name for the classInputStreamwhich is located in the packagejava.io.

A package is declared at the start of the file with thepackagedeclaration:

packagemyapplication.mylibrary;

publicclassMyClass{
}

Classes with thepublicmodifier must be placed in the files with the same name andjavaextension and put into nested folders corresponding to the package name. The above classmyapplication.mylibrary.MyClasswill have the following path:myapplication/mylibrary/MyClass.java.

Import declaration

edit

Type import declaration

edit

A type import declaration allows a named type to be referred to by a simple name rather than the full name that includes the package. Import declarations can besingle type import declarationsorimport-on-demand declarations.Import declarations must be placed at the top of a code file after the package declaration.

packagemyPackage;

importjava.util.Random;// Single type declaration

publicclassImportsTest{
publicstaticvoidmain(String[]args){
/* The following line is equivalent to
* java.util.Random random = new java.util.Random();
* It would've been incorrect without the import.
*/
Randomrandom=newRandom();
}
}

Import-on-demand declarations are mentioned in the code. A "type import" imports all the types of the package. A "static import" imports members of the package.

importjava.util.*;/*This form of importing classes makes all classes
in package java.util available by name, could be used instead of the
import declaration in the previous example. */
importjava.*;/*This statement is legal, but does nothing, since there
are no classes directly in package java. All of them are in packages
within package java. This does not import all available classes.*/

Static import declaration

edit

This type of declaration has been available sinceJ2SE 5.0.Static importdeclarations allow access to static members defined in another class, interface, annotation, or enum; without specifying the class name:

import staticjava.lang.System.out;//'out' is a static field in java.lang.System

publicclassHelloWorld{
publicstaticvoidmain(String[]args){
/* The following line is equivalent to
System.out.println( "Hi World!" );
and would have been incorrect without the import declaration. */
out.println("Hello World!");
}
}

Import-on-demand declarations allow to import all the fields of the type:

import staticjava.lang.System.*;
/* This form of declaration makes all
fields in the java.lang.System class available by name, and may be used instead
of the import declaration in the previous example. */

Enum constants may also be used with static import. For example, this enum is in the package calledscreen:

publicenumColorName{
RED,BLUE,GREEN
};

It is possible to use static import declarations in another class to retrieve the enum constants:

importscreen.ColorName;
import staticscreen.ColorName.*;

publicclassDots{
/* The following line is equivalent to 'ColorName foo = ColorName.RED',
and it would have been incorrect without the static import. */
ColorNamefoo=RED;

voidshift(){
/* The following line is equivalent to
if (foo == ColorName.RED) foo = ColorName.BLUE; */
if(foo==RED)foo=BLUE;
}
}

Operators

edit

Operators in Java are similar to those inC++.However, there is nodeleteoperator due togarbage collectionmechanisms in Java, and there are no operations onpointerssince Java does not support them. Another difference is that Java has an unsigned right shift operator (>>>), while C's right shift operator's signedness is type-dependent. Operators in Java cannot beoverloaded.

Precedence Operator Description Associativity
1 () Method invocation Left-to-right
[] Array access
. Class member selection
2 ++-- Postfix increment and decrement[1]
3 ++-- Prefix increment and decrement Right-to-left
+- Unary plus and minus
!~ Logical NOT and bitwise NOT
(type) val Type cast
new Class instance or array creation
4 */% Multiplication, division, and modulus (remainder) Left-to-right
5 +- Addition and subtraction
+ String concatenation
6 <<>>>>> Bitwiseleft shift, signed right shift and unsigned right shift
7 <<= Relational"less than" and "less than or equal to"
>>= Relational "greater than" and "greater than or equal to"
instanceof Type comparison
8 ==!= Relational "equal to" and "not equal to"
9 & Bitwise and logical AND
10 ^ Bitwise and logical XOR (exclusive or)
11 | Bitwise and logical OR (inclusive or)
12 && Logical conditional-AND
13 || Logical conditional-OR
14 c?t:f Ternaryconditional (see?:) Right-to-left
15 = Simple assignment
+=-= Assignment by sum and difference
*=/=%= Assignment by product, quotient, and remainder
<<=>>=>>>= Assignment by bitwise left shift, signed right shift and unsigned right shift
&=^=|= Assignment by bitwise AND, XOR, and OR

Control structures

edit

Conditional statements

edit

ifstatement

edit

if statementsin Java are similar to those in C and use the same syntax:

if(i==3){
doSomething();
}

ifstatement may include optionalelseblock, in which case it becomes an if-then-else statement:

if(i==3){
doSomething();
}else{
doSomethingElse();
}

Like C, else-if construction does not involve any special keywords, it is formed as a sequence of separate if-then-else statements:

if(i==3){
doSomething();
}elseif(i==2){
doSomethingElse();
}else{
doSomethingDifferent();
}

Also, a?:operator can be used in place of simple if statement, for example

inta=1;
intb=2;
intminVal=(a<b)?a:b;

switchstatement

edit

Switch statementsin Java can usebyte,short,char,andint(notlong) primitive data types or their corresponding wrapper types. Starting with J2SE 5.0, it is possible to useenum types.Starting with Java SE 7, it is possible to use Strings.[2]Otherreference typescannot be used inswitchstatements.

Possible values are listed usingcaselabels. These labels in Java may contain only constants (including enum constants and string constants). Execution will start after the label corresponding to the expression inside the brackets. An optionaldefaultlabel may be present to declare that the code following it will be executed if none of the case labels correspond to the expression.

Code for each label ends with thebreakkeyword. It is possible to omit it causing the execution to proceed to the next label, however, a warning will usually be reported during compilation.

switch(ch){
case'A':
doSomething();// Triggered if ch == 'A'
break;
case'B':
case'C':
doSomethingElse();// Triggered if ch == 'B' or ch == 'C'
break;
default:
doSomethingDifferent();// Triggered in any other case
break;
}
switchexpressions
edit

Since Java 14 it has become possible to use switch expressions, which use the new arrow syntax:

varresult=switch(ch){
case'A'->Result.GREAT;
case'B','C'->Result.FINE;
default->thrownewThisIsNoGoodException();
};

Alternatively, there is a possibility to express the same with theyieldstatement, although it is recommended to prefer the arrow syntax because it avoids the problem of accidental fall throughs.

varresult=switch(ch){
case'A':
yieldResult.GREAT;
case'B':
case'C':
yieldResult.FINE;
default:
thrownewThisIsNoGoodException();
};

Iteration statements

edit

Iteration statements are statements that are repeatedly executed when a given condition is evaluated as true. SinceJ2SE 5.0,Java has four forms of such statements. The condition must have type boolean or Boolean, meaning C's

while(1){
doSomething();
}

results in a compilation error.

whileloop

edit

In thewhileloop, the test is done before each iteration.

while(i<10){
doSomething();
}

do... whileloop

edit

In thedo... whileloop, the test is done after each iteration. Consequently, the code is always executed at least once.

// doSomething() is called at least once
do{
doSomething();
}while(i<10);

forloop

edit

forloops in Java include an initializer, a condition and a counter expression. It is possible to include several expressions of the same kind using comma as delimiter (except in the condition). However, unlike C, the comma is just a delimiter and not an operator.

for(inti=0;i<10;i++){
doSomething();
}

// A more complex loop using two variables
for(inti=0,j=9;i<10;i++,j-=3){
doSomething();
}

Like C, all three expressions are optional. The following loop is infinite:

for(;;){
doSomething();
}

Enhancedforloop

edit

Enhancedforloopshave been available sinceJ2SE 5.0.This type of loop uses built-in iterators over arrays and collections to return each item in the given collection. Every element is returned and reachable in the context of the code block. When the block is executed, the next item is returned until there are no items remaining. UnlikeC#,this kind of loop does not involve a special keyword, but instead uses a different notation style.

for(inti:intArray){
doSomething(i);
}

Jump statements

edit

Labels

edit

Labels are given points in code used bybreakandcontinuestatements. The Javagotokeyword cannot be used to jump to specific points in code.

start:
someMethod();

breakstatement

edit

Thebreakstatement breaks out of the closest loop orswitchstatement. Execution continues in the statement after the terminated statement, if any.

for(inti=0;i<10;i++){
while(true){
break;
}
// Will break to this point
}

It is possible to break out of the outer loop using labels:

outer:
for(inti=0;i<10;i++){
while(true){
breakouter;
}
}
// Will break to this point

continuestatement

edit

Thecontinuestatement discontinues the current iteration of the current control statement and begins the next iteration. The followingwhileloop in the code below reads characters by callinggetChar(),skipping the statements in the body of the loop if the characters are spaces:

intch;
while(ch==getChar()){
if(ch==' '){
continue;// Skips the rest of the while-loop
}

// Rest of the while-loop, will not be reached if ch == ' '
doSomething();
}

Labels can be specified incontinuestatements andbreakstatements:

outer:
for(Stringstr:stringsArr){
char[]strChars=str.toCharArray();
for(charch:strChars){
if(ch==' '){
/* Continues the outer cycle and the next
string is retrieved from stringsArr */
continueouter;
}
doSomething(ch);
}
}

returnstatement

edit

Thereturnstatement is used to end method execution and to return a value. A value returned by the method is written after thereturnkeyword. If the method returns anything butvoid,it must use thereturnstatement to return some value.

voiddoSomething(booleanstreamClosed){
// If streamClosed is true, execution is stopped
if(streamClosed){
return;
}
readFromStream();
}

intcalculateSum(inta,intb){
intresult=a+b;
returnresult;
}

returnstatement ends execution immediately, except for one case: if the statement is encountered within atryblock and it is complemented by afinally,control is passed to thefinallyblock.

voiddoSomething(booleanstreamClosed){
try{
if(streamClosed){
return;
}
readFromStream();
}finally{
/* Will be called last even if
readFromStream() was not called */
freeResources();
}
}

Exception handling statements

edit

try-catch-finallystatements

edit

Exceptions are managed withintry...catchblocks.

try{
// Statements that may throw exceptions
methodThrowingExceptions();
}catch(Exceptionex){
// Exception caught and handled here
reportException(ex);
}finally{
// Statements always executed after the try/catch blocks
freeResources();
}

The statements within thetryblock are executed, and if any of them throws an exception, execution of the block is discontinued and the exception is handled by thecatchblock. There may be multiplecatchblocks, in which case the first block with an exception variable whose type matches the type of the thrown exception is executed.

Java SE 7 also introduced multi-catch clauses besides uni-catch clauses. This type of catch clauses allows Java to handle different types of exceptions in a single block provided they are not subclasses of each other.

try{
methodThrowingExceptions();
}catch(IOException|IllegalArgumentExceptionex){
//Both IOException and IllegalArgumentException will be caught and handled here
reportException(ex);
}

If nocatchblock matches the type of the thrown exception, the execution of the outer block (or method) containing thetry...catchstatement is discontinued, and the exception is passed up and outside the containing block (or method). The exception is propagated upwards through thecall stackuntil a matchingcatchblock is found within one of the currently active methods. If the exception propagates all the way up to the top-mostmainmethod without a matchingcatchblock being found, a textual description of the exception is written to the standard output stream.

The statements within thefinallyblock are always executed after thetryandcatchblocks, whether or not an exception was thrown and even if areturnstatement was reached. Such blocks are useful for providing clean-up code that is guaranteed to always be executed.

Thecatchandfinallyblocks are optional, but at least one or the other must be present following thetryblock.

try-with-resources statements

edit

try-with-resources statements are a special type oftry-catch-finallystatements introduced as an implementation of thedispose patternin Java SE 7. In atry-with-resources statement thetrykeyword is followed by initialization of one or more resources that are released automatically when thetryblock execution is finished. Resources must implementjava.lang.AutoCloseable.try-with-resources statements are not required to have acatchorfinallyblock unlike normaltry-catch-finallystatements.

try(FileOutputStreamfos=newFileOutputStream("filename");
XMLEncoderxEnc=newXMLEncoder(fos)){
xEnc.writeObject(object);
}catch(IOExceptionex){
Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE,null,ex);
}

Since Java 9 it is possible to use already declared variables:

FileOutputStreamfos=newFileOutputStream("filename");
XMLEncoderxEnc=newXMLEncoder(fos);
try(fos;xEnc){
xEnc.writeObject(object);
}catch(IOExceptionex){
Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE,null,ex);
}

throwstatement

edit

Thethrowstatement is used to throw an exception and end the execution of the block or method. The thrown exception instance is written after thethrowstatement.

voidmethodThrowingExceptions(Objectobj){
if(obj==null){
// Throws exception of NullPointerException type
thrownewNullPointerException();
}
// Will not be called, if object is null
doSomethingWithObject(obj);
}

Thread concurrency control

edit

Java has built-in tools formulti-thread programming.For the purposes of threadsynchronizationthesynchronizedstatement is included in Java language.

To make a code block synchronized, it is preceded by thesynchronizedkeyword followed by the lock object inside the brackets. When the executing thread reaches the synchronized block, it acquires amutual exclusionlock, executes the block, then releases the lock. No threads may enter this block until the lock is released. Any non-null reference type may be used as the lock.

/* Acquires lock on someObject. It must be of
a reference type and must be non-null */
synchronized(someObject){
// Synchronized statements
}

assertstatement

edit

assertstatements have been available sinceJ2SE 1.4.These types of statements are used to makeassertionsin the source code, which can be turned on and off during execution for specific classes or packages. To declare an assertion theassertkeyword is used followed by a conditional expression. If it evaluates tofalsewhen the statement is executed, an exception is thrown. This statement can include a colon followed by another expression, which will act as the exception's detail message.

// If n equals 0, AssertionError is thrown
assertn!=0;
/* If n equals 0, AssertionError will be thrown
with the message after the colon */
assertn!=0:"n was equal to zero";

Primitive types

edit

Primitive types in Java include integer types, floating-point numbers,UTF-16code units and a Boolean type. There are no unsigned types in Java exceptchartype, which is used to represent UTF-16 code units. The lack of unsigned types is offset by introducing unsigned right shift operation (>>>), which is not present in C++. Nevertheless, criticisms have been leveled about the lack of compatibility with C and C++ this causes.[3]

Primitive Types
Type Name Wrapper class Value Range Size Default Value
byte java.lang.Byte integer −128 through +127 8-bit (1-byte) 0
short java.lang.Short integer −32,768 through +32,767 16-bit (2-byte) 0
int java.lang.Integer integer −2,147,483,648 through +2,147,483,647 32-bit (4-byte) 0
long java.lang.Long integer −9,223,372,036,854,775,808 through
+9,223,372,036,854,775,807
64-bit (8-byte) 0
float java.lang.Float floating point number ±1.401298E−45 through ±3.402823E+38 32-bit (4-byte) 0.0f[4]
double java.lang.Double floating point number ±4.94065645841246E−324 through
±1.79769313486232E+308
64-bit (8-byte) 0.0
boolean java.lang.Boolean Boolean trueorfalse 1-bit (1-bit) false
char java.lang.Character UTF-16code unit (BMPcharacter
or a part of a surrogate pair)
'\u0000'through'\uFFFF' 16-bit (2-byte) '\u0000'

chardoes not necessarily correspond to a single character. It may represent a part of asurrogate pair,in which case Unicode code point is represented by a sequence of twocharvalues.

Boxing and unboxing

edit

This language feature was introduced inJ2SE 5.0.Boxingis the operation of converting a value of a primitive type into a value of a corresponding reference type, which serves as a wrapper for this particular primitive type.Unboxingis the reverse operation of converting a value of a reference type (previously boxed) into a value of a corresponding primitive type. Neither operation requires an explicit conversion.

Example:

intfoo=42;// Primitive type
Integerbar=foo;/* foo is boxed to bar, bar is of Integer type,
which serves as a wrapper for int */
intfoo2=bar;// Unboxed back to primitive type

Reference types

edit

Reference types include class types, interface types, and array types. When the constructor is called, an object is created on the heap and a reference is assigned to the variable. When a variable of an object gets out of scope, the reference is broken and when there are no references left, the object gets marked as garbage. The garbage collector then collects and destroys it some time afterwards.

A reference variable isnullwhen it does not reference any object.

Arrays

edit

Arrays in Java are created at runtime, just like class instances. Array length is defined at creation and cannot be changed.

int[]numbers=newint[5];
numbers[0]=2;
numbers[1]=5;
intx=numbers[0];

Initializers

edit
// Long syntax
int[]numbers=newint[]{20,1,42,15,34};
// Short syntax
int[]numbers2={20,1,42,15,34};

Multi-dimensional arrays

edit

In Java, multi-dimensional arrays are represented as arrays of arrays. Technically, they are represented by arrays of references to other arrays.

int[][]numbers=newint[3][3];
numbers[1][2]=2;

int[][]numbers2={{2,3,2},{1,2,6},{2,4,5}};

Due to the nature of the multi-dimensional arrays, sub-arrays can vary in length, so multi-dimensional arrays are not bound to be rectangular unlike C:

int[][]numbers=newint[2][];//Initialization of the first dimension only

numbers[0]=newint[3];
numbers[1]=newint[2];

Classes

edit

Classesare fundamentals of an object-oriented language such as Java. They contain members that store and manipulate data. Classes are divided intotop-levelandnested.Nested classes are classes placed inside another class that may access the private members of the enclosing class. Nested classes includemember classes(which may be defined with thestaticmodifier for simple nesting or without it for inner classes),local classesandanonymous classes.

Declaration

edit
Top-level class
classFoo{
// Class members
}
Inner class
classFoo{// Top-level class
classBar{// Inner class
}
}
Nested class
classFoo{// Top-level class
staticclassBar{// Nested class
}
}
Local class
classFoo{
voidbar(){
classFoobar{// Local class within a method
}
}
}
Anonymous class
classFoo{
voidbar(){
newObject(){// Creation of a new anonymous class extending Object
};
}
}

Instantiation

edit

Non-static members of a class define the types of theinstance variablesand methods, which are related to the objects created from that class. To create these objects, the class must be instantiated by using thenewoperator and calling the class constructor.

Foofoo=newFoo();

Accessing members

edit

Members of both instances and static classes are accessed with the.(dot) operator.

Accessing an instance member
Instance members can be accessed through the name of a variable.

Stringfoo="Hello";
Stringbar=foo.toUpperCase();

Accessing a static class member
Static members are accessed by using the name of the class or any other type. This does not require the creation of a class instance. Static members are declared using thestaticmodifier.

publicclassFoo{
publicstaticvoiddoSomething(){
}
}

// Calling the static method
Foo.doSomething();

Modifiers

edit

Modifiers are keywords used to modify declarations of types and type members. Most notably there is a sub-group containing the access modifiers.

  • abstract- Specifies that a class only serves as a base class and cannot be instantiated.
  • static- Used only for member classes, specifies that the member class does not belong to a specific instance of the containing class.
  • final- Classes marked asfinalcannot be extended from and cannot have any subclasses.
  • strictfp- Specifies that all floating-point operations must be carried out conforming toIEEE 754and forbids using enhanced precision to store intermediate results.
Abstract class
edit

By default, all methods in all classes are concrete, unless the abstract keyword is used. An abstract class may include abstract methods, which have no implementation. By default, all methods in all interfaces are abstract, unless the default keyword is used. The default keyword can be used to specify a concrete method in an interface.

//By default, all methods in all classes are concrete, unless the abstract keyword is used.
publicabstractclassDemo{
// An abstract class may include abstract methods, which have no implementation.
publicabstractintsum(intx,inty);

// An abstract class may also include concrete methods.
publicintproduct(intx,inty){
returnx*y;
}
}

//By default, all methods in all interfaces are abstract, unless the default keyword is used.
interfaceDemoInterface{
intgetLength();//The abstract keyword can be used here, though is completely useless

//The default keyword can be used in this context to specify a concrete method in an interface
defaultintproduct(intx,inty){
returnx*y;
}
}
Final class
edit

A finalclasscannot be subclassed. As doing this can confer security and efficiency benefits, many of the Java standard library classes are final, such asjava.lang.Systemandjava.lang.String.

Example:

publicfinalclassMyFinalClass{...}

publicclassThisIsWrongextendsMyFinalClass{...}// forbidden
Access modifiers
edit

Theaccess modifiers,orinheritance modifiers,set the accessibility of classes, methods, and other members. Members marked aspubliccan be reached from anywhere. If a class or its member does not have any modifiers, default access is assumed.

publicclassFoo{
intgo(){
return0;
}

privateclassBar{
}
}

The following table shows whether code within a class has access to the class or method depending on the accessing class location and the modifier for the accessed class or class member:

Modifier Same class or nested class Other class inside the same package Extended Class inside another package Non-extended inside another package
private yes no no no
default (package private) yes yes no no
protected yes yes yes no
public yes yes yes yes
This image describes the class member scope within classes and packages.

Constructors and initializers

edit

Aconstructoris a special method called when an object is initialized. Its purpose is to initialize the members of the object. The main differences between constructors and ordinary methods are that constructors are called only when an instance of the class is created and never return anything. Constructors are declared as common methods, but they are named after the class and no return type is specified:

classFoo{
Stringstr;

Foo(){// Constructor with no arguments

// Initialization
}

Foo(Stringstr){// Constructor with one argument
this.str=str;
}
}

Initializers are blocks of code that are executed when a class or an instance of a class is created. There are two kinds of initializers,static initializersandinstance initializers.

Static initializers initialize static fields when the class is created. They are declared using thestatickeyword:

classFoo{
static{
// Initialization
}
}

A class is created only once. Therefore, static initializers are not called more than once. On the contrary, instance initializers are automatically called before the call to a constructor every time an instance of the class is created. Unlike constructors instance initializers cannot take any arguments and generally they cannot throw anychecked exceptions(except in several special cases). Instance initializers are declared in a block without any keywords:

classFoo{
{
// Initialization
}
}

Since Java has a garbage collection mechanism, there are nodestructors.However, every object has afinalize()method called prior to garbage collection, which can beoverriddento implement finalization.

Methods

edit

All the statements in Java must reside withinmethods.Methods are similar to functions except they belong to classes. A method has a return value, a name and usually some parameters initialized when it is called with some arguments. Similar to C++, methods returning nothing have return type declared asvoid.Unlike in C++, methods in Java are not allowed to havedefault argumentvalues and methods are usually overloaded instead.

classFoo{
intbar(inta,intb){
return(a*2)+b;
}

/* Overloaded method with the same name but different set of arguments */
intbar(inta){
returna*2;
}
}

A method is called using.notation on an object, or in the case of a static method, also on the name of a class.

Foofoo=newFoo();
intresult=foo.bar(7,2);// Non-static method is called on foo

intfinalResult=Math.abs(result);// Static method call

Thethrowskeyword indicates that a method throws an exception. All checked exceptions must be listed in a comma-separated list.

voidopenStream()throwsIOException,myException{// Indicates that IOException may be thrown
}
Modifiers
edit
  • abstract-Abstract methodscan be present only inabstract classes,such methods have no body and must be overridden in a subclass unless it is abstract itself.
  • static- Makes the method static and accessible without creation of a class instance. However static methods cannot access non-static members in the same class.
  • final- Declares that the method cannot be overridden in a subclass.
  • native- Indicates that this method is implemented throughJNIin platform-dependent code. Actual implementation happens outside Java code, and such methods have no body.
  • strictfp- Declares strict conformance toIEEE 754in carrying out floating-point operations.
  • synchronized- Declares that a thread executing this method must acquire monitor. Forsynchronizedmethods the monitor is the class instance orjava.lang.Classif the method is static.
  • Access modifiers - Identical to those used with classes.
Final methods
edit

A finalmethodcannot beoverriddenor hidden by subclasses.[5]This is used to prevent unexpected behavior from a subclass altering a method that may be crucial to the function or consistency of the class.[6]

Example:

publicclassBase
{
publicvoidm1(){...}
publicfinalvoidm2(){...}

publicstaticvoidm3(){...}
publicstaticfinalvoidm4(){...}
}

publicclassDerivedextendsBase
{
publicvoidm1(){...}// OK, overriding Base#m1()
publicvoidm2(){...}// forbidden

publicstaticvoidm3(){...}// OK, hiding Base#m3()
publicstaticvoidm4(){...}// forbidden
}

A common misconception is that declaring a method asfinalimproves efficiency by allowing the compiler to directly insert the method wherever it is called (seeinline expansion). Because the method is loaded atruntime,compilers are unable to do this. Only the runtime environment andJITcompiler know exactly which classes have been loaded, and so only they are able to make decisions about when to inline, whether or not the method is final.[7]

Machine code compilers that generate directly executable, platform-specificmachine code,are an exception. When usingstatic linking,the compiler can safely assume that methods and variables computable atcompile-timemay be inlined.
Varargs
edit

This language feature was introduced inJ2SE 5.0.The last argument of the method may be declared as a variable arity parameter, in which case the method becomes a variable arity method (as opposed to fixed arity methods) or simplyvarargsmethod. This allows one to pass a variable number of values, of the declared type, to the method as parameters - including no parameters. These values will be available inside the method as an array.

voidprintReport(Stringheader,int...numbers){//numbers represents varargs
System.out.println(header);
for(intnum:numbers){
System.out.println(num);
}
}

// Calling varargs method
printReport("Report data",74,83,25,96);

Fields

edit

Fields, orclass variables,can be declared inside the class body to store data.

classFoo{
doublebar;
}

Fields can be initialized directly when declared.

classFoo{
doublebar=2.3;
}
Modifiers
edit
  • static- Makes the field a static member.
  • final- Allows the field to be initialized only once in a constructor or inside initialization block or during its declaration, whichever is earlier.
  • transient- Indicates that this field will not be stored duringserialization.
  • volatile- If a field is declaredvolatile,it is ensured that all threads see a consistent value for the variable.

Inheritance

edit

Classes in Java can onlyinheritfromoneclass. A class can be derived from any class that is not marked asfinal.Inheritance is declared using theextendskeyword. A class can reference itself using thethiskeyword and its direct superclass using thesuperkeyword.

classFoo{

}

classFoobarextendsFoo{

}

If a class does not specify its superclass, it implicitly inherits fromjava.lang.Objectclass. Thus all classes in Java are subclasses ofObjectclass.

If the superclass does not have a constructor without parameters the subclass must specify in its constructors what constructor of the superclass to use. For example:

classFoo{
publicFoo(intn){
// Do something with n
}
}

classFoobarextendsFoo{
privateintnumber;
// Superclass does not have constructor without parameters
// so we have to specify what constructor of our superclass to use and how

publicFoobar(intnumber){
super(number);
this.number=number;
}
}
Overriding methods
edit

Unlike C++, all non-finalmethods in Java arevirtualand can be overridden by the inheriting classes.

classOperation{
publicintdoSomething(){
return0;
}
}

classNewOperationextendsOperation{
@Override
publicintdoSomething(){
return1;
}
}
Abstract classes
edit

AnAbstract Classis a class that is incomplete, or is to be considered incomplete, so cannot be instantiated.

A class C has abstract methods if any of the following is true:

  • C explicitly contains a declaration of an abstract method.
  • Any of C's superclasses has an abstract method and C neither declares nor inherits a method that implements it.
  • A direct superinterface of C declares or inherits a method (which is therefore necessarily abstract) and C neither declares nor inherits a method that implements it.
  • A subclass of an abstract class that is not itself abstract may be instantiated, resulting in the execution of a constructor for the abstract class and, therefore, the execution of the field initializers for instance variables of that class.
packageorg.dwwwp.test;

/**
* @author jcrypto
*/
publicclassAbstractClass{
privatestaticfinalStringhello;

static{
System.out.println(AbstractClass.class.getName()+":static block runtime");
hello="hello from"+AbstractClass.class.getName();
}

{
System.out.println(AbstractClass.class.getName()+":instance block runtime");
}

publicAbstractClass(){
System.out.println(AbstractClass.class.getName()+":constructor runtime");
}

publicstaticvoidhello(){
System.out.println(hello);
}
}
packageorg.dwwwp.test;

/**
* @author jcrypto
*/
publicclassCustomClassextendsAbstractClass{

static{
System.out.println(CustomClass.class.getName()+":static block runtime");
}

{
System.out.println(CustomClass.class.getName()+":instance block runtime");
}

publicCustomClass(){
System.out.println(CustomClass.class.getName()+":constructor runtime");
}

publicstaticvoidmain(String[]args){
CustomClassnc=newCustomClass();
hello();
//AbstractClass.hello();//also valid
}
}

Output:

org.dwwwp.test.AbstractClass: static block runtime
org.dwwwp.test.CustomClass: static block runtime
org.dwwwp.test.AbstractClass: instance block runtime
org.dwwwp.test.AbstractClass: constructor runtime
org.dwwwp.test.CustomClass: instance block runtime
org.dwwwp.test.CustomClass: constructor runtime
hello from org.dwwwp.test.AbstractClass

Enumerations

edit

This language feature was introduced inJ2SE 5.0.Technically enumerations are a kind of class containing enum constants in its body. Each enum constant defines an instance of the enum type. Enumeration classes cannot be instantiated anywhere except in the enumeration class itself.

enumSeason{
WINTER,SPRING,SUMMER,AUTUMN
}

Enum constants are allowed to have constructors, which are called when the class is loaded:

publicenumSeason{
WINTER("Cold"),SPRING("Warmer"),SUMMER("Hot"),AUTUMN("Cooler");

Season(Stringdescription){
this.description=description;
}

privatefinalStringdescription;

publicStringgetDescription(){
returndescription;
}
}

Enumerations can have class bodies, in which case they are treated like anonymous classes extending the enum class:

publicenumSeason{
WINTER{
StringgetDescription(){return"cold";}
},
SPRING{
StringgetDescription(){return"warmer";}
},
SUMMER{
StringgetDescription(){return"hot";}
},
FALL{
StringgetDescription(){return"cooler";}
};
}

Interfaces

edit

Interfacesare types which contain no fields and usually define a number of methods without an actual implementation. They are useful to define a contract with any number of different implementations. Every interface is implicitly abstract. Interface methods are allowed to have a subset of access modifiers depending on the language version,strictfp,which has the same effect as for classes, and alsostaticsince Java SE 8.

interfaceActionListener{
intACTION_ADD=0;
intACTION_REMOVE=1;

voidactionSelected(intaction);
}

Implementing an interface

edit

An interface is implemented by a class using theimplementskeyword. It is allowed to implement more than one interface, in which case they are written afterimplementskeyword in a comma-separated list. A class implementing an interface must override all its methods, otherwise it must be declared as abstract.

interfaceRequestListener{
intrequestReceived();
}

classActionHandlerimplementsActionListener,RequestListener{
publicvoidactionSelected(intaction){
}

publicintrequestReceived(){
}
}

//Calling method defined by interface
RequestListenerlistener=newActionHandler();/*ActionHandler can be
represented as RequestListener...*/
listener.requestReceived();/*...and thus is known to implement
requestReceived() method*/

Functional interfaces and lambda expressions

edit

These features were introduced with the release of Java SE 8. An interface automatically becomes a functional interface if it defines only one method. In this case an implementation can be represented as a lambda expression instead of implementing it in a new class, thus greatly simplifying writing code in thefunctional style.Functional interfaces can optionally be annotated with the@FunctionalInterfaceannotation, which will tell the compiler to check whether the interface actually conforms to a definition of a functional interface.

// A functional interface
@FunctionalInterface
interfaceCalculation{
intcalculate(intsomeNumber,intsomeOtherNumber);
}

// A method which accepts this interface as a parameter
intrunCalculation(Calculationcalculation){
returncalculation.calculate(1,2);
}

// Using a lambda to call the method
runCalculation((number,otherNumber)->number+otherNumber);

// Equivalent code which uses an anonymous class instead
runCalculation(newCalculation(){
@Override
publicintcalculate(intsomeNumber,intsomeOtherNumber){
returnsomeNumber+someOtherNumber;
}
})

Lambda's parameters types don't have to be fully specified and can be inferred from the interface it implements. Lambda's body can be written without a body block and areturnstatement if it is only an expression. Also, for those interfaces which only have a single parameter in the method, round brackets can be omitted.[8]

// Same call as above, but with fully specified types and a body block
runCalculation((intnumber,intotherNumber)->{
returnnumber+otherNumber;
});

// A functional interface with a method which has only a single parameter
interfaceStringExtender{
StringextendString(Stringinput);
}

// Initializing a variable of this type by using a lambda
StringExtenderextender=input->input+"Extended";

Method references

edit

It is not necessary to use lambdas when there already is a named method compatible with the interface. This method can be passed instead of a lambda using a method reference. There are several types of method references:

Reference type Example Equivalent lambda
Static Integer::sum (number, otherNumber) -> number + otherNumber
Bound "LongString"::substring index -> "LongString".substring(index)
Unbound String::isEmpty string -> string.isEmpty()
Class constructor ArrayList<String>::new capacity -> new ArrayList<String>(capacity)
Array constructor String[]::new size -> new String[size]

The code above which callsrunCalculationcould be replaced with the following using the method references:

runCalculation(Integer::sum);

Inheritance

edit

Interfaces can inherit from other interfaces just like classes. Unlike classes it is allowed to inherit from multiple interfaces. However, it is possible that several interfaces have a field with the same name, in which case it becomes a single ambiguous member, which cannot be accessed.

/* Class implementing this interface must implement methods of both
ActionListener and RequestListener */
interfaceEventListenerextendsActionListener,RequestListener{
}

Default methods

edit

Java SE 8 introduced default methods to interfaces which allows developers to add new methods to existing interfaces without breaking compatibility with the classes already implementing the interface. Unlike regular interface methods, default methods have a body which will get called in the case if the implementing class doesn't override it.

interfaceStringManipulator{
StringextendString(Stringinput);

// A method which is optional to implement
defaultStringshortenString(Stringinput){
returninput.substring(1);
}
}

// This is a valid class despite not implementing all the methods
classPartialStringManipulatorimplementsStringManipulator{
@Override
publicStringextendString(Stringinput){
returninput+"Extended";
}
}

Static methods

edit

Static methods is another language feature introduced in Java SE 8. They behave in exactly the same way as in the classes.

interfaceStringUtils{
staticStringshortenByOneSymbol(Stringinput){
returninput.substring(1);
}
}

StringUtils.shortenByOneSymbol("Test");

Private methods

edit

Private methods were added in the Java 9 release. An interface can have a method with a body marked as private, in which case it will not be visible to inheriting classes. It can be called from default methods for the purposes of code reuse.

interfaceLogger{
defaultvoidlogError(){
log(Level.ERROR);
}

defaultvoidlogInfo(){
log(Level.INFO);
}

privatevoidlog(Levellevel){
SystemLogger.log(level.id);
}
}

Annotations

edit

Annotations in Java are a way to embedmetadatainto code. This language feature was introduced inJ2SE 5.0.

Annotation types
edit

Java has a set of predefined annotation types, but it is allowed to define new ones. An annotation type declaration is a special type of an interface declaration. They are declared in the same way as the interfaces, except theinterfacekeyword is preceded by the@sign. All annotations are implicitly extended fromjava.lang.annotation.Annotationand cannot be extended from anything else.

@interfaceBlockingOperations{
}

Annotations may have the same declarations in the body as the common interfaces, in addition they are allowed to include enums and annotations. The main difference is that abstract method declarations must not have any parameters or throw any exceptions. Also they may have a default value, which is declared using thedefaultkeyword after the method name:

@interfaceBlockingOperations{
booleanfileSystemOperations();
booleannetworkOperations()defaultfalse;
}
Usage of annotations
edit

Annotations may be used in any kind of declaration, whether it is package, class (including enums), interface (including annotations), field, method, parameter, constructor, or local variable. Also they can be used with enum constants. Annotations are declared using the@sign preceding annotation type name, after which element-value pairs are written inside brackets. All elements with no default value must be assigned a value.

@BlockingOperations(/*mandatory*/fileSystemOperations,
/*optional*/networkOperations=true)
voidopenOutputStream(){//Annotated method
}

Besides the generic form, there are two other forms to declare an annotation, which are shorthands.Marker annotationis a short form, it is used when no values are assigned to elements:

@Unused// Shorthand for @Unused()
voidtravelToJupiter(){
}

The other short form is calledsingle element annotation.It is used with annotations types containing only one element or in the case when multiple elements are present, but only one elements lacks a default value. In single element annotation form the element name is omitted and only value is written instead:

/* Equivalent for @BlockingOperations(fileSystemOperations = true).
networkOperations has a default value and
does not have to be assigned a value */

@BlockingOperations(true)
voidopenOutputStream(){
}

Generics

edit

Generics,or parameterized types, orparametric polymorphism,is one of the major features introduced inJ2SE 5.0.Before generics were introduced, it was required to declare all the types explicitly. With generics, it became possible to work in a similar manner with different types without declaring the exact types. The main purpose of generics is to ensure type safety and to detect runtime errors during compilation. Unlike C#, information on the used parameters is not available at runtime due totype erasure.[9]

Generic classes

edit

Classes can be parameterized by adding a type variable inside angle brackets (<and>) following the class name. It makes possible the use of this type variable in class members instead of actual types. There can be more than one type variable, in which case they are declared in a comma-separated list.

It is possible to limit a type variable to a subtype of some specific class or declare an interface that must be implemented by the type. In this case the type variable is appended by theextendskeyword followed by a name of the class or the interface. If the variable is constrained by both class and interface or if there are several interfaces, the class name is written first, followed by interface names with&sign used as the delimiter.

/* This class has two type variables, T and V. T must be
a subtype of ArrayList and implement Formattable interface */
publicclassMapper<TextendsArrayList&Formattable,V>{
publicvoidadd(Tarray,Vitem){
// array has add method because it is an ArrayList subclass
array.add(item);
}
}

When a variable of a parameterized type is declared or an instance is created, its type is written exactly in the same format as in the class header, except the actual type is written in the place of the type variable declaration.

/* Mapper is created with CustomList as T and Integer as V.
CustomList must be a subclass of ArrayList and implement Formattable */
Mapper<CustomList,Integer>mapper=newMapper<CustomList,Integer>();

Since Java SE 7, it is possible to use a diamond (<>) in place of type arguments, in which case the latter will be inferred. The following code in Java SE 7 is equivalent to the code in the previous example:

Mapper<CustomList,Integer>mapper=newMapper<>();

When declaring a variable for a parameterized type, it is possible to use wildcards instead of explicit type names. Wildcards are expressed by writing?sign instead of the actual type. It is possible to limit possible types to the subclasses or superclasses of some specific class by writing theextendskeyword or thesuperkeyword correspondingly followed by the class name.

/* Any Mapper instance with CustomList as the first parameter
may be used regardless of the second one.*/
Mapper<CustomList,?>mapper;
mapper=newMapper<CustomList,Boolean>();
mapper=newMapper<CustomList,Integer>();

/* Will not accept types that use anything but
a subclass of Number as the second parameter */
voidaddMapper(Mapper<?,?extendsNumber>mapper){
}

Generic methods and constructors

edit

Usage of generics may be limited to some particular methods, this concept applies to constructors as well. To declare a parameterized method, type variables are written before the return type of the method in the same format as for the generic classes. In the case of constructor, type variables are declared before the constructor name.

classMapper{
// The class itself is not generic, the constructor is
<T,V>Mapper(Tarray,Vitem){
}
}

/* This method will accept only arrays of the same type as
the searched item type or its subtype*/
static<T,VextendsT>booleancontains(Titem,V[]arr){
for(TcurrentItem:arr){
if(item.equals(currentItem)){
returntrue;
}
}
returnfalse;
}

Generic interfaces

edit

Interfaces can be parameterized in the similar manner as the classes.

interfaceExpandable<TextendsNumber>{
voidaddItem(Titem);
}

// This class is parameterized
classArray<TextendsNumber>implementsExpandable<T>{
voidaddItem(Titem){
}
}

// And this is not and uses an explicit type instead
classIntegerArrayimplementsExpandable<Integer>{
voidaddItem(Integeritem){
}
}

See also

edit

References

edit
  1. ^"Operators (The Java™ Tutorials > Learning the Java Language > Language Basics)".docs.oracle.com.Oracle and/or its affiliates.Retrieved2015-06-16.
  2. ^"The switch Statement (The Java™ Tutorials > Learning the Java Language > Language Basics)".docs.oracle.com.Retrieved2021-08-15.
  3. ^Owens, Sean."Java and unsigned int, unsigned short, unsigned byte, unsigned long, etc. (Or rather, the lack thereof)".
  4. ^"Primitive Data Types".
  5. ^"Chapter 8. Classes".docs.oracle.com.Retrieved2024-04-25.
  6. ^"Writing Final Classes and Methods".docs.oracle.com.Retrieved2024-04-25.
  7. ^"Java theory and practice: Is that your final answer?".developer.ibm.com.Archived fromthe originalon 2009-02-08.Retrieved2024-04-25.
  8. ^"Lambda Expressions (The Java™ Tutorials > Learning the Java Language > Classes and Objects)".docs.oracle.com.Retrieved2021-08-08.
  9. ^Generics in the Run Time (C# Programming Guide)
edit