Java Language: Difference between revisions
(202 intermediate revisions by the same user not shown) | |||
Line 1: | Line 1: | ||
=External= | |||
* https://docs.oracle.com/javase/specs/jls/se8/html/ | |||
=Internal= | =Internal= | ||
* [[Java#Language|Java]] | * [[Java#Language|Java]] | ||
= | =Lexical Structure= | ||
==<span id='synchronized_statement'></span>synchronized== | ==Keywords== | ||
Keywords cannot be used as [[#Identifier|identifiers]]. | |||
* <code>if</code> | |||
* <code>else</code> | |||
* <code>continue</code> | |||
* <code>break</code> | |||
* <code>for</code> | |||
* <code>do</code> | |||
* <code>while</code> | |||
* <code>switch</code> | |||
* <code>case</code> | |||
* <code>default</code> | |||
* <code>private</code> | |||
* <code>protected</code> | |||
* <code>public</code> | |||
* <code>import</code> | |||
* <code>package</code> | |||
* <code>abstract</code> | |||
* <code>implements</code> | |||
* <code>extends</code> | |||
* <code>interface</code> | |||
* <code>class</code> | |||
* <span id='static'></span><code>static</code> See [[#Class_Variable|class variables]]. | |||
* <code>final</code> | |||
* <code>return</code> | |||
* <code>transient</code> | |||
* <code>void</code> | |||
* <code>byte</code> | |||
* <code>short</code> | |||
* <code>int</code> | |||
* <code>long</code> | |||
* <code>char</code> | |||
* <code>float</code> | |||
* <code>double</code> | |||
* <code>boolean</code> | |||
* <code>try</code> | |||
* <code>catch</code> | |||
* <code>finally</code> | |||
* <code>throw</code> | |||
* <code>throws</code> | |||
* <code>new</code> | |||
* <code>this</code> | |||
* <code>super</code> | |||
* <code>instanceof</code> | |||
* <code>native</code> | |||
* <code>synchronized</code> See [[#synchronized_statement|<tt>synchronized</tt> statement]] and [[#synchronized_modifier|<tt>synchronized</tt> modifier]]. | |||
* <code>volatile</code> | |||
* <code>goto</code> No longer in use. | |||
* <code>const</code> No longer in use. | |||
* <code>strictfp</code>. Added in 1.2. | |||
* <code>[[Java assert Keyword|assert]]</code> Added in 1.4. | |||
* <code>enum</code> Added in 5.0. | |||
* <code>module</code> Added in 9.0. | |||
* <code>requires</code> Added in 9.0. | |||
* <code>transitive</code> Added in 9.0. | |||
* <code>exports to</code> Added in 9.0. | |||
* <code>uses</code> Added in 9.0. | |||
* <code>provides</code> Added in 9.0. | |||
* <code>with</code> Added in 9.0. | |||
* <code>opens to</code> Added in 9.0. | |||
* <code>var</code>. Special identifier added in Java 10. | |||
===Statements=== | |||
{{Internal|Programming_Languages_Concepts#Statement|Programming Languages Concepts | Statements}} | |||
====<span id='synchronized_statement'></span>synchronized==== | |||
The <tt>synchronized</tt> statement acquires a mutual-exclusion lock on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the log, no other thread may acquire the lock. | The <tt>synchronized</tt> statement acquires a mutual-exclusion lock on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the log, no other thread may acquire the lock. | ||
Line 13: | Line 84: | ||
The type of ''expression'' must be a reference type. | The type of ''expression'' must be a reference type. | ||
=Modifiers= | Also see: {{Internal|Java synchronized mechanism#Overview|'synchronized' mechanism}} | ||
====return==== | |||
Control-flow statement. | |||
===Modifiers=== | |||
====Method Modifiers==== | |||
=====<span id='synchronized_modifier'></span>synchronized===== | |||
A <tt>synchronized</tt> class method synchronizes on the monitor associated with the Class object of that class. | |||
A <tt>synchronized</tt> instance method synchronizes on the monitor associated with <tt>this</tt> - the object instance it is invoked onto. | |||
Also see: {{Internal|Java synchronized mechanism#Overview|'synchronized' mechanism}} | |||
=====default===== | |||
==Literals== | |||
===Reserved Words for Literal Values=== | |||
<code>true</code>, <code>false</code>, <code>null</code>. | |||
The reserved words for literal values cannot be used as [[#Identifier|identifiers]]. | |||
==Operators== | |||
===Unary Operators=== | |||
===Multiplicative Operators=== | |||
====Remainder Operator <tt>%</tt>==== | |||
The binary operator % produces the remainder of its operands from an implied division. The left-hand operand is the dividend and the right-hand operand is the divisor. It accepts integral and floating point operands. The remainder operation for operands that are integers after binary numeric promotion produces a value such that (a/b)*b + (a%b) is equal to a. | |||
<font color=darkgray>TODO: Document the difference between the remainder and modulo.</font> | |||
===Additive Operators=== | |||
===Shift Operators=== | |||
{{External|https://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19}} | |||
====Left Shift <tt><<</tt>==== | |||
<syntaxhighlight lang='java'> | |||
int a = 1; | |||
a << 1; | |||
assert a == 2; | |||
</syntaxhighlight> | |||
====Signed Right Shift <tt>>></tt>==== | |||
<syntaxhighlight lang='java'> | |||
int a = 2; | |||
a >>= 1; | |||
assert a == 1; | |||
</syntaxhighlight> | |||
====Unsigned Signed Right Shift <tt>>>></tt>==== | |||
===Relational Operators=== | |||
===Equality Operators=== | |||
===Bitwise and Logical Operators=== | |||
Both operands must be of primitive integral type. If both operands are of the same type, the result of the operation is of the same type. If the operands are of different primitive integral types, the smallest type is converted into the largest type via binary numeric promotion first, and the result if of the largest type. Also see: {{Internal|Bitwise Operations|Bitwise Operations}} | |||
====Integer Bitwise AND <tt>&</tt>==== | |||
<code>&</code> computes the bitwise AND between operands. Both operands must be primitive integral types. See [[#Bitwise_and_Logical_Operators|Bitwise and Logical Operators]] for more details on result type and promotions. | |||
====Integer Bitwise OR <tt>|</tt>==== | |||
<code>|</code> computes the bitwise OR between operands. Both operands must be primitive integral types. See [[#Bitwise_and_Logical_Operators|Bitwise and Logical Operators]] for more details on result type and promotions. | |||
====Integer Bitwise XOR <tt>^</tt>==== | |||
<code>^</code> computes the bitwise exclusive OR (XOR) between operands. Both operands must be primitive integral types. See [[#Bitwise_and_Logical_Operators|Bitwise and Logical Operators]] for more details on result type and promotions. Useful in calculating the [[Hamming_Distance#Hamming_Distance_between_Two_Integers_in_Java|Hamming distance]]. | |||
{| class="wikitable" style="text-align: left;" | |||
! A | |||
! B | |||
! XOR | |||
|- | |||
| 0 || 0 || 0 | |||
|- | |||
| 0 || 1 || 1 | |||
|- | |||
| 1 || 0 || 1 | |||
|- | |||
| 1 || 1 || 0 | |||
|- | |||
|} | |||
===Assignment Operators=== | |||
Assignment operators: <code>=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code>, <code>+=</code>, <code>-=</code>, <code><<=</code>, <code>>>=</code>, <code>>>>=</code>, <code>&=</code>, <code>^=</code>, <code>|=</code>. | |||
===Other Operators=== | |||
====Conditional-And <tt>&&</tt>==== | |||
====Conditional-Or <tt>||</tt>==== | |||
====Conditional Operator <tt>? :</tt>==== | |||
=Types= | |||
Java is a [[Programming_Languages_Concepts#Static_Typing_vs_Dynamic_Typing|statically typed]] language, which means that every [[#Variables|variable]] and every [[#Expressions|expression]] has a type that is known at compile time. | |||
Java is [[Programming_Languages_Concepts#Strong_Typing_vs_Loose_Typing|strongly typed]] language, because the types limit the values a variable can hold or that an expression can produce, limit the operations supported by those types and determine the meaning of operations. | |||
==null Type== | |||
==Primitive Types== | |||
The primitive types are <code>boolean</code> and the numeric types ([[#Integral_Primitive_Types|integral]] and [[#Floating_Point_Primitive_Types|floating point]]). | |||
The numeric types are the integral types <code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code> and <code>char</code>, and the floating-point types <code>float</code> and <code>double</code>. | |||
===boolean=== | |||
{{External|https://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.2.5}} | |||
The boolean type represents a logical quantity with two possible values, indicated by the literals <code>true</code> and <code>false</code>. Boolean primitive values are stored on <font color=darkgray>1 bit</font>. | |||
===Integral Primitive Types=== | |||
An integral data type is a data type whose values are integers. There are five integral primitive types in Java: [[#byte|byte]], [[#short|short]], [[#int|int]], [[#long|long]] and [[#char|char]]. Of those, the first four (<code>byte</code>, <code>short</code>, <code>int</code> and <code>long</code>) are signed, and <code>char</code> is unsigned. | |||
====byte==== | |||
<code>byte</code> represents an integral signed value on 1 byte (8 bit) in a two's complement representation. The rage is -2<sup>7</sup> -128 to 2<sup>7</sup>-1 127. More more details see [[Two%27s_Complement_Representation#byte_Representation|byte representation in two's complement]]. Unlike <code>int</code> and <code>long</code> literals (see below), there are no byte literals; however, any int literal within the byte range can be assigned to a byte variable. | |||
<code>int</code> or <code>long</code> variables cannot assigned to a <code>byte</code> variable without type casting. | |||
<code>byte</code> has a corresponding reference wrapper type [[Java_Autoboxing#java.lang.Byte|java.lang.Byte]]. | |||
====short==== | |||
2 bytes, signed (two's complement), -32,768 to 32,767. For more details see [[Two%27s_Complement_Representation#short_Representation|short representation in two's complement]]. | |||
====int==== | |||
<code>int</code> represents an integral signed value on 4 bytes (32 bit) in a two's complement representation. The range is -2,147,483,648 to 2,147,483,647. For more details see [[Two%27s_Complement_Representation#int_Representation|int representation in two's complement]]. Like all numeric types ints may be cast into other numeric types ([[#byte|byte]], [[#short|short]], [[#long|long]], [[#float|float]], [[#double|double]]). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type. | |||
All whole numbers in the -2<sup>31</sup> to 2<sup>31</sup>-1 are known as integer literals, or integer constants. An integer literal can be assigned to an int variable: | |||
<syntaxhighlight lang='java'> | |||
int i = 57; | |||
</syntaxhighlight> | |||
<code>int</code> has a corresponding reference wrapper type [[Java_Autoboxing#java.lang.Integer|java.lang.Integer]]. | |||
====long==== | |||
<code>long</code> represents an integral signed value on 8 bytes (64 bit) in a two's complement representation. The range is from -2<sup>63</sup> -9,223,372,036,854,775,808 to 2<sup>63</sup>-1 9,223,372,036,854,775,807. For more details see [[Two%27s_Complement_Representation#long_Representation|long representation in two's complement]]. | |||
All whole numbers in the -2<sup>63</sup> to 2<sup>63</sup>-1 are known as integer literals of long type. An integer literal of long type ends with "L" or "l": | |||
<syntaxhighlight lang='java'> | |||
long l = 57L; | |||
</syntaxhighlight> | |||
Even if the value stored in a <code>long</code> variable is well within the range of the <code>int</code> data type, the assignment from <code>long</code> to <code>int</code> is not allowed without explicit type casting. If casting is not performed, a compilation error occurs. | |||
<code>long</code> has a corresponding reference wrapper type [[Java_Autoboxing#java.lang.Long|java.lang.Long]]. | |||
====char==== | |||
Contains an 2-byte (16 bit) (0x0000 - 0xFFFF, 0 - 65,535) unsigned Unicode [[Character_Encoding#Code_Point|code point]]. For a detailed discussion on Unicode representation in Java see: {{Internal|Java and Unicode#Overview|Java and Unicode}} | |||
A character literal represents the value of the <code>char</code> data type. | |||
<syntaxhighlight lang='java'> | |||
char c = 'A'; | |||
</syntaxhighlight> | |||
A character literal can also be expressed as a character escape sequence, which starts with a backslash immediately followed by a character, and bot h are enclosed in single quotes. There are eight predefined character escape sequences: | |||
{| | |||
| Character escape sequence || Description | |||
|- | |||
| '\n' || Linefeed | |||
|- | |||
| '\r' || Carriage return | |||
|- | |||
| '\f' || Form feed | |||
|- | |||
| '\b' || Backspace | |||
|- | |||
| '\t' || Tab | |||
|- | |||
| '\\' || Backslash | |||
|- | |||
| '\"' || Double quote | |||
|- | |||
| '\'' || Single quote | |||
|} | |||
===Floating Point Primitive Types=== | |||
Java uses a floating point format to represent real numbers. Floating point representations are slower and less accurate compared to fixed-point representations. However, floating point representations can handle a larger range of numbers with the same computer memory. | |||
====float==== | |||
{{External|https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3}} | |||
4 bytes, IEEE 754, named "single-precision floating-point number". Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and the conversion is done modulo the length of the smaller type. | |||
[[File:float.png]] | |||
All real numbers that end with "f" or "F" are called float literals. | |||
<syntaxhighlight lang='java'> | |||
float f = 1.2F; | |||
</syntaxhighlight> | |||
The float data type defines a positive infinity, negative infinity and a not-a-number (NaN). | |||
====double==== | |||
{{External|https://docs.oracle.com/javase/specs/jls/se7/html/jls-4.html#jls-4.2.3}} | |||
8 bytes, IEEE 754, named "double-precision floating-point number". Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). | |||
All real numbers are called double literals. A double literal may optionally end with 'd' or 'D'. However, these suffixes are optional. | |||
==Reference Types== | |||
Java does not use pointers. | |||
There are four kinds of reference types: [[#Class_Types|class types]], [[#Interface_Types|interface types]], [[#Type_Variables|type variables]] and [[#Array_Types|array types]]. | |||
===Class Types=== | |||
===Interface Types=== | |||
===Type Variables=== | |||
===Array Types=== | |||
In Java arrays are treated as objects with an '''array type'''. An object of an array type has all its [[Java_Arrays#Array_Component|components]] initialized with 0 or null upon initialization. For more details on Java arrays, see: {{Internal|Java Arrays|Java Arrays}} | |||
===Reference Type Value=== | |||
The value of a [[#Reference_Types|reference type]] is a references to an object instance. | |||
Also see: {{Internal|Variables,_Parameters,_Arguments#Reference|Variables, Parameters, Arguments | Reference}} | |||
=Values= | |||
For reference type values, see [[#Reference_Type_Value|above]]. | |||
In case of a [[Java_8_Lambda_Expressions#Lambda_Expression|lambda expressions]], the value of the lambda expression is the reference to a [[Java_8_Lambda_Expressions#Functional_Interface|functional interface]] instance. | |||
=Identifier= | |||
{{External|https://docs.oracle.com/javase/specs/jls/se8/html/jls-3.html#jls-Identifier}} | |||
An identifier is the name of a class, [[#Variable_Name|variable]], method, etc. | |||
An identifier cannot be a [[#Keywords|keyword]], a [[#Reserved_Words_for_Literal_Values|boolean literal or a null literal]]. Identifier cannot start with a number. They can start with $, but the $ sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems. | |||
=Variables= | |||
A variable is a ''storage location'' and has an associated type - the compile-time type - that is either a [[#Primitive_Types|primitive type]] or a [[#Reference_Types|reference type]]. | |||
The value of a variable is changed by an assignment or by a prefix/postfix increment/decrement operators. | |||
<font color=darkgray>A variable cannot be used before it was initialized</font>. | |||
Also see: {{Internal|Variables,_Parameters,_Arguments#Variable|Variables, Parameters, Arguments}} | |||
==Variable Name== | |||
A variable name is an [[#Identifier|identifier]]. | |||
==Variable Initializer== | |||
==Variable Types== | |||
There are eight kinds of variables: | |||
===Class Variable=== | |||
A ''class variable'' is a field declared using the keyword [[#static|static]] within a class declaration, or with or without the keyword [[#static|static]] within an interface declaration. | |||
===<span id='Field2'></span>Instance Variable=== | |||
An ''instance variable'' is a field declared within a class declaration without using the keyword [[#static|static]]. An instance variable is also referred to as [[#Field|field]]. | |||
Instance variables are stored on the heap, within the heap representation of the instance. | |||
===Array Component=== | |||
''Array components'' are unnamed variables that are created and initialized to default values whenever a new object that is an array is created. | |||
===Method Parameter=== | |||
'''Method parameters''' name argument values passed to a method when the method is invoked. The function declaration has parameters, the function is invoked with '''arguments'''. For every parameter declared in a method declaration, a new '''parameter variable''' is created each time that method is invoked. The new variable is initialized with the corresponding argument from the method invocation. | |||
Also see: {{Internal|Variables,_Parameters,_Arguments#Parameter|Variables, Parameters, Arguments}} | |||
===Constructor Parameter=== | |||
''Constructor parameters'' name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression or explicit constructor invocation invokes that constructor. The new variable is initialized with the corresponding argument from the creation expression or constructor invocation. | |||
===Lambda Parameter=== | |||
A ''lambda parameter'' name argument values passed to a [[Java 8 Lambda Expressions#Overview|lambda expression]] body. For every parameter declared in a lambda expression, a new parameter variable is created each time a method implemented by the lambda body is invoked, and initialized with the corresponding argument value from the invocation. | |||
===Exception Parameter=== | |||
An ''exception parameter'' is created each time an exception is caught by a [[#catch|catch]] clause of a [[#try|try]] statement. | |||
===Local Variable=== | |||
''Local variables'' are declared by local variable declaration statements. The local variables are created whenever the flow of control enters a block of a [[#for|for]] statement. | |||
Local variable are allocated on the stack. | |||
==Final Variables== | |||
A final variable may be assigned to once. | |||
===Java 8 Effectively Final Variable=== | |||
A non-final local variable or method parameter whose value is never changed after initialization is known as ''effectively final''. Lambda expression [[Java_8_Lambda_Expressions#Variable_Capture|capture]] and use these variables. | |||
=Expressions= | |||
{{Internal|Programming_Languages_Concepts#Expression|Programming - Expressions}} | |||
=Interface= | |||
An ''interface'' groups related methods together into a contract. | |||
All methods on an interface are implicitly public and abstract (https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.4). "Every method declaration in the body of an interface is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface." | |||
=Class= | |||
<syntaxhighlight lang='groovy'> | |||
package <package-name>; | |||
import <package-name>.<class-name>; | |||
<access-modifier> class <ClassName> { | |||
<access-modifier> <variable-definition>; | |||
<access-modifier> <method-definition>; | |||
} | |||
</syntaxhighlight> | |||
==Anonymous Class== | |||
Can be used for [[Functional_Programming#Behavior_Parameterization|behavior parameterization]]. | |||
==Abstract Class== | |||
==Class Instance== | |||
===Field=== | |||
See [[#Field2|Instance Variable]]. | |||
====Field Modifiers==== | |||
=====<tt>volatile</tt>===== | |||
{{External|https://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.3.1.4}} | |||
If a field is declared <tt>volatile</tt>, the java memory model ensures that all threads see a consistent value for the variable. | |||
=Package= | |||
==Package Name== | |||
A package consists in identifiers separated by ".". The identifiers must not be a keyword, boolean literal or null literal and must contain only identifier characters. The first character must be a letter, and the following characters can be letters or digits. | |||
Upper cases and lower cases are allowed and treated distinctly. | |||
=Access Modifiers= | |||
Access modifiers express the visibility of classes, methods and variables. | |||
==<tt>public</tt>== | |||
Declares the class/method/variable visible to any other class. | |||
==<tt>protected</tt>== | |||
Declares the class/method/variable visible to classes from the same package and subclasses. | |||
==default (package private)== | |||
No access modifier is explicitly set. Designates the class/method/variable visible to classes from the same package but not subclases. | |||
==<tt>private</tt>== | |||
Declares the class/method/variable visible only within the class. | |||
==< | =The <tt>main()</tt> Method= | ||
<syntaxhighlight lang='java'> | |||
package some.package; | |||
public class SomeClass { | |||
public static void main(String[] args) { | |||
... | |||
} | |||
} | |||
</syntaxhighlight> |
Latest revision as of 00:12, 29 September 2023
External
Internal
Lexical Structure
Keywords
Keywords cannot be used as identifiers.
if
else
continue
break
for
do
while
switch
case
default
private
protected
public
import
package
abstract
implements
extends
interface
class
static
See class variables.final
return
transient
void
byte
short
int
long
char
float
double
boolean
try
catch
finally
throw
throws
new
this
super
instanceof
native
synchronized
See synchronized statement and synchronized modifier.volatile
goto
No longer in use.const
No longer in use.strictfp
. Added in 1.2.assert
Added in 1.4.enum
Added in 5.0.module
Added in 9.0.requires
Added in 9.0.transitive
Added in 9.0.exports to
Added in 9.0.uses
Added in 9.0.provides
Added in 9.0.with
Added in 9.0.opens to
Added in 9.0.var
. Special identifier added in Java 10.
Statements
synchronized
The synchronized statement acquires a mutual-exclusion lock on behalf of the executing thread, executes a block, then releases the lock. While the executing thread owns the log, no other thread may acquire the lock.
synchronized (expression) block
The type of expression must be a reference type.
Also see:
return
Control-flow statement.
Modifiers
Method Modifiers
synchronized
A synchronized class method synchronizes on the monitor associated with the Class object of that class.
A synchronized instance method synchronizes on the monitor associated with this - the object instance it is invoked onto.
Also see:
default
Literals
Reserved Words for Literal Values
true
, false
, null
.
The reserved words for literal values cannot be used as identifiers.
Operators
Unary Operators
Multiplicative Operators
Remainder Operator %
The binary operator % produces the remainder of its operands from an implied division. The left-hand operand is the dividend and the right-hand operand is the divisor. It accepts integral and floating point operands. The remainder operation for operands that are integers after binary numeric promotion produces a value such that (a/b)*b + (a%b) is equal to a.
TODO: Document the difference between the remainder and modulo.
Additive Operators
Shift Operators
Left Shift <<
int a = 1;
a << 1;
assert a == 2;
Signed Right Shift >>
int a = 2;
a >>= 1;
assert a == 1;
Unsigned Signed Right Shift >>>
Relational Operators
Equality Operators
Bitwise and Logical Operators
Both operands must be of primitive integral type. If both operands are of the same type, the result of the operation is of the same type. If the operands are of different primitive integral types, the smallest type is converted into the largest type via binary numeric promotion first, and the result if of the largest type. Also see:
Integer Bitwise AND &
&
computes the bitwise AND between operands. Both operands must be primitive integral types. See Bitwise and Logical Operators for more details on result type and promotions.
Integer Bitwise OR |
|
computes the bitwise OR between operands. Both operands must be primitive integral types. See Bitwise and Logical Operators for more details on result type and promotions.
Integer Bitwise XOR ^
^
computes the bitwise exclusive OR (XOR) between operands. Both operands must be primitive integral types. See Bitwise and Logical Operators for more details on result type and promotions. Useful in calculating the Hamming distance.
A | B | XOR |
---|---|---|
0 | 0 | 0 |
0 | 1 | 1 |
1 | 0 | 1 |
1 | 1 | 0 |
Assignment Operators
Assignment operators: =
, *=
, /=
, %=
, +=
, -=
, <<=
, >>=
, >>>=
, &=
, ^=
, |=
.
Other Operators
Conditional-And &&
Conditional-Or ||
Conditional Operator ? :
Types
Java is a statically typed language, which means that every variable and every expression has a type that is known at compile time.
Java is strongly typed language, because the types limit the values a variable can hold or that an expression can produce, limit the operations supported by those types and determine the meaning of operations.
null Type
Primitive Types
The primitive types are boolean
and the numeric types (integral and floating point).
The numeric types are the integral types byte
, short
, int
, long
and char
, and the floating-point types float
and double
.
boolean
The boolean type represents a logical quantity with two possible values, indicated by the literals true
and false
. Boolean primitive values are stored on 1 bit.
Integral Primitive Types
An integral data type is a data type whose values are integers. There are five integral primitive types in Java: byte, short, int, long and char. Of those, the first four (byte
, short
, int
and long
) are signed, and char
is unsigned.
byte
byte
represents an integral signed value on 1 byte (8 bit) in a two's complement representation. The rage is -27 -128 to 27-1 127. More more details see byte representation in two's complement. Unlike int
and long
literals (see below), there are no byte literals; however, any int literal within the byte range can be assigned to a byte variable.
int
or long
variables cannot assigned to a byte
variable without type casting.
byte
has a corresponding reference wrapper type java.lang.Byte.
short
2 bytes, signed (two's complement), -32,768 to 32,767. For more details see short representation in two's complement.
int
int
represents an integral signed value on 4 bytes (32 bit) in a two's complement representation. The range is -2,147,483,648 to 2,147,483,647. For more details see int representation in two's complement. Like all numeric types ints may be cast into other numeric types (byte, short, long, float, double). When lossy casts are done (e.g. int to byte) the conversion is done modulo the length of the smaller type.
All whole numbers in the -231 to 231-1 are known as integer literals, or integer constants. An integer literal can be assigned to an int variable:
int i = 57;
int
has a corresponding reference wrapper type java.lang.Integer.
long
long
represents an integral signed value on 8 bytes (64 bit) in a two's complement representation. The range is from -263 -9,223,372,036,854,775,808 to 263-1 9,223,372,036,854,775,807. For more details see long representation in two's complement.
All whole numbers in the -263 to 263-1 are known as integer literals of long type. An integer literal of long type ends with "L" or "l":
long l = 57L;
Even if the value stored in a long
variable is well within the range of the int
data type, the assignment from long
to int
is not allowed without explicit type casting. If casting is not performed, a compilation error occurs.
long
has a corresponding reference wrapper type java.lang.Long.
char
Contains an 2-byte (16 bit) (0x0000 - 0xFFFF, 0 - 65,535) unsigned Unicode code point. For a detailed discussion on Unicode representation in Java see:
A character literal represents the value of the char
data type.
char c = 'A';
A character literal can also be expressed as a character escape sequence, which starts with a backslash immediately followed by a character, and bot h are enclosed in single quotes. There are eight predefined character escape sequences:
Character escape sequence | Description |
'\n' | Linefeed |
'\r' | Carriage return |
'\f' | Form feed |
'\b' | Backspace |
'\t' | Tab |
'\\' | Backslash |
'\"' | Double quote |
'\'' | Single quote |
Floating Point Primitive Types
Java uses a floating point format to represent real numbers. Floating point representations are slower and less accurate compared to fixed-point representations. However, floating point representations can handle a larger range of numbers with the same computer memory.
float
4 bytes, IEEE 754, named "single-precision floating-point number". Covers a range from 1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Like all numeric types floats may be cast into other numeric types (byte, short, long, int, double). When lossy casts to integer types are done (e.g. float to short) the fractional part is truncated and the conversion is done modulo the length of the smaller type.
All real numbers that end with "f" or "F" are called float literals.
float f = 1.2F;
The float data type defines a positive infinity, negative infinity and a not-a-number (NaN).
double
8 bytes, IEEE 754, named "double-precision floating-point number". Covers a range from 4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative).
All real numbers are called double literals. A double literal may optionally end with 'd' or 'D'. However, these suffixes are optional.
Reference Types
Java does not use pointers.
There are four kinds of reference types: class types, interface types, type variables and array types.
Class Types
Interface Types
Type Variables
Array Types
In Java arrays are treated as objects with an array type. An object of an array type has all its components initialized with 0 or null upon initialization. For more details on Java arrays, see:
Reference Type Value
The value of a reference type is a references to an object instance.
Also see:
Values
For reference type values, see above.
In case of a lambda expressions, the value of the lambda expression is the reference to a functional interface instance.
Identifier
An identifier is the name of a class, variable, method, etc.
An identifier cannot be a keyword, a boolean literal or a null literal. Identifier cannot start with a number. They can start with $, but the $ sign should be used only in mechanically generated source code or, rarely, to access pre-existing names on legacy systems.
Variables
A variable is a storage location and has an associated type - the compile-time type - that is either a primitive type or a reference type.
The value of a variable is changed by an assignment or by a prefix/postfix increment/decrement operators.
A variable cannot be used before it was initialized.
Also see:
Variable Name
A variable name is an identifier.
Variable Initializer
Variable Types
There are eight kinds of variables:
Class Variable
A class variable is a field declared using the keyword static within a class declaration, or with or without the keyword static within an interface declaration.
Instance Variable
An instance variable is a field declared within a class declaration without using the keyword static. An instance variable is also referred to as field.
Instance variables are stored on the heap, within the heap representation of the instance.
Array Component
Array components are unnamed variables that are created and initialized to default values whenever a new object that is an array is created.
Method Parameter
Method parameters name argument values passed to a method when the method is invoked. The function declaration has parameters, the function is invoked with arguments. For every parameter declared in a method declaration, a new parameter variable is created each time that method is invoked. The new variable is initialized with the corresponding argument from the method invocation.
Also see:
Constructor Parameter
Constructor parameters name argument values passed to a constructor. For every parameter declared in a constructor declaration, a new parameter variable is created each time a class instance creation expression or explicit constructor invocation invokes that constructor. The new variable is initialized with the corresponding argument from the creation expression or constructor invocation.
Lambda Parameter
A lambda parameter name argument values passed to a lambda expression body. For every parameter declared in a lambda expression, a new parameter variable is created each time a method implemented by the lambda body is invoked, and initialized with the corresponding argument value from the invocation.
Exception Parameter
An exception parameter is created each time an exception is caught by a catch clause of a try statement.
Local Variable
Local variables are declared by local variable declaration statements. The local variables are created whenever the flow of control enters a block of a for statement.
Local variable are allocated on the stack.
Final Variables
A final variable may be assigned to once.
Java 8 Effectively Final Variable
A non-final local variable or method parameter whose value is never changed after initialization is known as effectively final. Lambda expression capture and use these variables.
Expressions
Interface
An interface groups related methods together into a contract.
All methods on an interface are implicitly public and abstract (https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.4). "Every method declaration in the body of an interface is implicitly public. It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface."
Class
package <package-name>;
import <package-name>.<class-name>;
<access-modifier> class <ClassName> {
<access-modifier> <variable-definition>;
<access-modifier> <method-definition>;
}
Anonymous Class
Can be used for behavior parameterization.
Abstract Class
Class Instance
Field
See Instance Variable.
Field Modifiers
volatile
If a field is declared volatile, the java memory model ensures that all threads see a consistent value for the variable.
Package
Package Name
A package consists in identifiers separated by ".". The identifiers must not be a keyword, boolean literal or null literal and must contain only identifier characters. The first character must be a letter, and the following characters can be letters or digits.
Upper cases and lower cases are allowed and treated distinctly.
Access Modifiers
Access modifiers express the visibility of classes, methods and variables.
public
Declares the class/method/variable visible to any other class.
protected
Declares the class/method/variable visible to classes from the same package and subclasses.
default (package private)
No access modifier is explicitly set. Designates the class/method/variable visible to classes from the same package but not subclases.
private
Declares the class/method/variable visible only within the class.
The main() Method
package some.package;
public class SomeClass {
public static void main(String[] args) {
...
}
}