Diferență între revizuiri ale paginii „Java Syntax; A Program's Lexical Structure”
(Nu s-au afișat 55 de versiuni intermediare efectuate de alți 2 utilizatori) | |||
Linia 87: | Linia 87: | ||
//... | //... | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | || [[Fișier: | + | || [[Fișier:references.png|Reference type variables example]] |
|} | |} | ||
==== Character Strings in Java - Class String ==== | ==== Character Strings in Java - Class String ==== | ||
− | + | In Java, character strings are implemented by class [http://docs.oracle.com/javase/7/docs/api/java/lang/String.html String]: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | String | + | String _name; |
− | + | _name = "George"; | |
− | // | + | //the following two lines are equivalent |
− | String | + | String _firstName = "Vasile"; |
− | String | + | String _firstName2 = new String("Vasile"); |
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | The only overloaded operator in the Java language is the operator +, used for concatenating character strings. If operator + is used for concatenating a '''String''' with a primitive value, or reference, then the latter is first automatically converted to a String, by using '''String.valueOf()''' method. | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | String | + | String _name; |
− | + | _name= "George"; | |
− | String | + | String _firstName = "Vasile"; |
− | String | + | String _fullName= _name + " " + _firstName ; |
String _title = "I am number " + 7; | String _title = "I am number " + 7; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> Comparing objects of type '''String''' is done by using the method '''equals()'''. The comparison operator '''==''' compare references in order to check if reference the same object, not if the objects contain the same data.</div> |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | String | + | String _firstName = "Vasile"; |
− | String | + | String _firstName2 = new String("Vasile"); |
− | if( | + | if(_firstName2 == _firstName ){ |
− | System.out.println(" | + | System.out.println("Equal references"); |
}else{ | }else{ | ||
− | System.out.println(" | + | System.out.println("Different references"); |
} | } | ||
− | if( | + | if(_firstName2 .equals(_firstName )){ |
− | System.out.println(" | + | System.out.println("Equal strings"); |
}else{ | }else{ | ||
− | System.out.println(" | + | System.out.println("Different strings"); |
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Displaying a '''String''' in the standard output stream, in a console, is done by using the methods "print" or "println" of the field ''out'' of type '''PrintSteam''' in the '''System''' class: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
Linia 141: | Linia 141: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | ==== | + | ==== Multi-dimensional Arrays ==== |
− | + | Arrays are treated as objects in Java, as in there are reference type variables which identify the memory area allocated for the array. | |
− | ''' | + | '''Attention''': In the case of reference array instantiation (where each location is a reference, and not a primitive type), the '''new''' operator only allocate memory for the array, not each of the array's locations. |
− | ''' | + | '''Attention''': Just like in C, the counting of the elements start from 0. Thus, for an array of 5 elements, the valid positions are 0, 1, 2, 3 and 4. |
{| class="wikitable" | {| class="wikitable" | ||
|- bgcolor="#ddeeff" align="center" | |- bgcolor="#ddeeff" align="center" | ||
− | !''' | + | !'''Program example''' !! '''Diagram''' |
|- bgcolor="#ddffdd" align="center" | |- bgcolor="#ddffdd" align="center" | ||
| | | | ||
Linia 164: | Linia 164: | ||
char[][][] _array4; | char[][][] _array4; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | || [[Fișier: | + | || [[Fișier:vectors.png|Example of reference type variables - arrays]] |
|} | |} | ||
− | + | All arrays have a field called '''length''' which holds the number of locations in the array. This field is read-only. | |
+ | |||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
int[] _array1 = new int[5]; | int[] _array1 = new int[5]; | ||
− | System.out.println(_array1.length); // | + | System.out.println(_array1.length); //"5" will be displayed |
int[][] _array2 = new int[5][9]; | int[][] _array2 = new int[5][9]; | ||
− | System.out.println(_array2.length); // | + | System.out.println(_array2.length); //"5" will be displayed |
− | System.out.println(_array2[0].length); // | + | System.out.println(_array2[0].length); //"9" will be displayed |
</syntaxhighlight> | </syntaxhighlight> | ||
− | == | + | == The Java Class == |
+ | |||
+ | The class is the base type in Java, as in any other object oriented language. | ||
− | + | <div class="regula"><font color="#ff0000">Rule:</font>Nothing can exist outside a class or interface, except for package and import directives.</div> | |
− | |||
+ | <div class="regula"><font color="#ff0000">Rule:</font> Any file can contain only one regular class.</div> | ||
− | + | The keyword that define a class is '''class''', being always followed by the class name and its implementation, between curly brackets. | |
− | |||
− | <div class="conventie"><font color="#0000ff"> | + | <div class="conventie"><font color="#0000ff">Convention:</font> Any class or interface name starts with an uppercase letter.</div> |
Linia 196: | Linia 198: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | The implementation of a class is made of field (property) definitions and method definitions and implementations. The fields represent the data contained by the class and the methods represent its functionality, meaning the functions that modify the field values. | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> The operator used to access a class member (field or method) is ".".</div> |
− | === | + | === Java Packets === |
− | + | Classes of a Java application are structured in a hierarchy similar to the file system: files and directories (folders), with the classes being similar to files and packages to directories. The separator used between package names and classes is ".". | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> A Java package can contain classes, interfaces and other packages.</div> |
− | + | The keyword specifying the package that contains the class/ interface is '''package'''. If this directive is missing, the class is placed implicitly in the root of the package hierarchy. | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> In order to use a class in an application, that class needs to be imported in any other class that uses it, with two exceptions: the classes in the package '''java.lang''' which are automatically imported, and the classes that are in the same package which are implicitly visible.</div> |
Linia 237: | Linia 239: | ||
} | } | ||
− | |||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === Field Definition === |
− | + | Fields, like any other variable, may be of primitive or reference type. They are declared inside the class, but outside any method. | |
− | <div class="conventie"><font color="#0000ff"> | + | <div class="conventie"><font color="#0000ff">Convention:</font> Field names start with a lowercase letter.</div> |
− | <div class="conventie"><font color="#0000ff"> | + | <div class="conventie"><font color="#0000ff">Convention:</font> In order to distinguish easily between fields and local variables, the latter ones will have names starting with the underscore character ("_").</div> |
Linia 262: | Linia 263: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | ''' | + | '''Attention''': Fields have different values for each instance of the class, meaning each object. |
{| class="wikitable" | {| class="wikitable" | ||
|- bgcolor="#ddeeff" align="center" | |- bgcolor="#ddeeff" align="center" | ||
− | !''' | + | !'''Program example''' !! '''Diagram''' |
|- bgcolor="#ddffdd" align="center" | |- bgcolor="#ddffdd" align="center" | ||
| | | | ||
Linia 273: | Linia 274: | ||
public static void main(String[] _args){ | public static void main(String[] _args){ | ||
− | SomeClass _obj1 = new SomeClass(); // | + | SomeClass _obj1 = new SomeClass(); //we name this object ID1 |
− | SomeClass _obj2 = new SomeClass(); // | + | SomeClass _obj2 = new SomeClass(); //we name this object ID2 |
_obj1.somePrimitiveField = 5; | _obj1.somePrimitiveField = 5; | ||
_obj2.somePrimitiveField = 10; | _obj2.somePrimitiveField = 10; | ||
Linia 289: | Linia 290: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | || [[Fișier:objects.png|600px| | + | || [[Fișier:objects.png|600px|Fields in objects example]] |
|} | |} | ||
− | === | + | === Method Definition === |
− | + | Methods can be defined and implemented exclusively inside a class. Methods change the state of the object by changing the values of the fields. Just like in C, methods are declared using the following template: | |
− | * zero | + | * zero or more modifiers; |
− | * | + | * returned type (or '''void''' if the method does not return a value) - attention, constructors does not have a return type, not even '''void'''; |
− | * | + | * method name |
− | * | + | * between parentheses, the list of arguments, defined by type and name, separated by commas (this list can be empty) |
− | * | + | * between curly brackets, the method body (implementation). |
− | <div class="conventie"><font color="#0000ff"> | + | <div class="conventie"><font color="#0000ff">Convention:</font> With the exception of constructors, the method names begin with a lowercase letter.</div> |
Linia 336: | Linia 337: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | Primitive or reference type variables declared inside a method, or as an argument of a method, are called local variables and are not class fields. | |
− | <div class="conventie"><font color="#0000ff"> | + | <div class="conventie"><font color="#0000ff">Convention:</font> In order to distinguish easily between fields and local variables, the latter ones will have names starting with the underscore character ("_").</div> |
− | ==== | + | ==== Class Constructors ==== |
− | + | Constructors are special methods of a class that are called automatically when an object is instantiated. Constructors have two specific properties: | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> Constructors have the exact same name with the class they belong to.</div> |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> Constructors don't have a return type (not even '''void''').</div> |
− | + | Example of constructors for class SomeClass: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
class SomeClass{ | class SomeClass{ | ||
Linia 401: | Linia 402: | ||
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> If a class does have a constructor defined, then the Java compiler will automatically define a default compiler, with no arguments. However, if there is even one constructor defined, the default constructor will not be automatically inserted anymore.</div> |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> When instantiating an object (but not arrays), after the '''new''' operator, the next element is always a constructor call.</div> |
− | + | Example of constructor calling: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
class MainClass{ | class MainClass{ | ||
Linia 421: | Linia 422: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | ==== | + | ==== ''this'' and ''super'' Keywords ==== |
− | + | Keyword '''this''' can be used in two ways: | |
− | * | + | * as a call to a constructor from another constructor of the same class; |
− | * | + | * as a reference to the current object as an instance of the current class; |
− | + | Example if using keyword '''this''': | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
import java.util.ArrayList; | import java.util.ArrayList; | ||
Linia 495: | Linia 496: | ||
− | + | Keyword ''super'' can be used in two ways (vezi [[Advanced Notions About Object Oriented Programming#Class Hierarchies|class hierarchies]]) | |
− | * | + | * as a call to a super-class constructor from a constructor in the current class; |
− | * | + | * as a reference to the current object, as an instance of the super-class. |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
Linia 586: | Linia 587: | ||
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> Any constructor must start with a call to another constructor (by using either '''super''' or '''this'''). If this is not explicitly specified, then a '''super()''' call is implicitly added by the compiler. In this case, compilation errors may occur, if the super-class does not have a constructor with no arguments defined. To avoid this, an explicit constructor call must be added.</div> |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> Any constructor call done by using '''super''' or '''this''' must be the first statement in a constructor.</div> |
− | === | + | === Static Members === |
− | + | Static members of a class represent the members which do not change their value or behavior for each distinct object, meaning they are exist in the class context, not the object, or instance context. | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
Linia 612: | Linia 613: | ||
{| class="wikitable" | {| class="wikitable" | ||
|- bgcolor="#ddeeff" align="center" | |- bgcolor="#ddeeff" align="center" | ||
− | !''' | + | !'''Program Example''' !! '''Block Diagram''' |
|- bgcolor="#ddffdd" align="center" | |- bgcolor="#ddffdd" align="center" | ||
| | | | ||
Linia 638: | Linia 639: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | || [[Fișier:static_members.png|600px| | + | || [[Fișier:static_members.png|600px|Example of static fields in objects]] |
|} | |} | ||
− | <div class="sfat"><font color="darkgreen"> | + | <div class="sfat"><font color="darkgreen">Advice:</font> All methods that only access static fields of the class or no fields at all, should be also declared static.</div> |
− | <div class=" | + | <div class="conventie"><font color="blue">Convention:</font> Access to static members of a class is done by using the class name, not object references.</div> |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> Only fields, methods and inner-classes can be declared static, and not regular classes.</div> |
− | === | + | === Special Modifiers === |
− | ==== | + | ==== Access Modifiers ==== |
{| class="wikitable" | {| class="wikitable" | ||
|- bgcolor="#ddeeff" align="center" | |- bgcolor="#ddeeff" align="center" | ||
− | !''' | + | !'''Modifier''' !! '''Current Class''' !! '''Package''' !! '''Derived Class''' !! '''Outside Package''' |
|- bgcolor="#ddffdd" align="center" | |- bgcolor="#ddffdd" align="center" | ||
− | | public || <font color="green"> | + | | public || <font color="green">Yes</font> || <font color="green">Yes</font> || <font color="green">Yes</font> || <font color="green">Yes</font> |
|- bgcolor="#ddffdd" align="center" | |- bgcolor="#ddffdd" align="center" | ||
− | | protected || <font color="green"> | + | | protected || <font color="green">Yes</font> || <font color="green">Yes</font> || <font color="green">Yes</font> || <font color="red">No</font> |
|- bgcolor="#ddffdd" align="center" | |- bgcolor="#ddffdd" align="center" | ||
− | | | + | | default(no specifier) || <font color="green">Yes</font> || <font color="green">Yes</font> || <font color="red">No</font> || <font color="red">No</font> |
|- bgcolor="#ddffdd" align="center" | |- bgcolor="#ddffdd" align="center" | ||
− | | private || <font color="green"> | + | | private || <font color="green">Yes</font> || <font color="red">No</font> || <font color="red">No</font> || <font color="red">No</font> |
|} | |} | ||
Linia 753: | Linia 754: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | |||
− | ===== public ===== | + | <div class="sfat"><font color="darkgreen">Advice:</font> Usually, fields are declared private (see [[Advanced Notions About Object Oriented Programming#Encapsulation|encapsulation]]), and ''getters'' and ''setters'' methods and constructors are declared public. There are, of course, exceptions.</div> |
+ | |||
+ | |||
+ | ===== The <span style="color:maroon">public</span> modifier ===== | ||
− | + | A public class or member can be accessed from any other class. | |
− | ===== protected ===== | + | ===== The <span style="color:maroon">protected</span> modifier ===== |
− | + | A protected field or method is accessible for the classes defined in the same package and for derived classes. | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> A regular class can't have the '''protected''' access modifier.</div> |
− | ===== | + | ===== The default modifier (not explicit) ===== |
− | + | The lack of an access specifier means that the element is accessible from the current class or classes from the same package, but not other classes. | |
− | ===== private ===== | + | ===== The <span style="color:maroon">private</span> modifier ===== |
− | + | A '''private''' field or method can only be accessed from the defining class. | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> A regular class can't have the '''private''' access modifier.</div> |
− | ==== | + | ==== The <span style="color:maroon">final</span> modifier ==== |
− | + | The '''final''' modifier can be applied to: | |
− | * | + | * a class - the class can't be extended; |
− | * | + | * an interface - the interface can't be extended; |
− | * | + | * a method - the method can't be overridden; |
− | * | + | * a field - the field can only take one value and it will remain constant throughout of the object's lifetime; |
− | + | A field which is both '''static''' and '''final''' is called a class constant. | |
− | ==== | + | ==== The <span style="color:maroon">abstract</span> modifier ==== |
− | + | Any method without body (without implementation) is an abstract method | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font>If a class contains at least one abstarct method, that class must be declared abstract, too.</div> |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font>An abstract class cannot be instantiated, but you may extend it. Any class derived from an abstract class must implement the inherited abstract methods, or be also declared abstract.</div> |
− | + | Example: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
abstract class Sorter{ | abstract class Sorter{ | ||
Linia 844: | Linia 847: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | ==== | + | ==== The <span style="color:maroon">volatile</span> modifier ==== |
− | + | A field is declared '''volatile''' when that field for some object is accesed by more than one thread, and you want any update to be propagated into the main memory. When a thread writes into a volatile field, any other thread that access that field will see its updated value. Otherwise, the update might stay in the thread's local cache while the other threads continue to use the old value from their local caches. | |
− | + | The volatile fields allow threads to communicate without employing the synchronization mechanism, but this is possible only if there is no any risk to run into ''race conditions''. More details in [[Concurrent Programming - Threads]]. | |
− | ==== | + | ==== The <span style="color:maroon">transient</span> modifier ==== |
− | + | A class field is declared '''transient''' if you do not want it's value to be serialized together with the other object's fields when the object is serialized. It's value will be the default value after the object is deserialized (see [[Serialization]]). | |
− | ==== | + | ==== The <span style="color:maroon">synchronized</span> modifier ==== |
− | + | A '''synchronized''' method or block of statements cannot be executed by more than one thread at a time. If two threads need to call such a method, or execute such a block, one of them must wait for the other to return from the method or to exit the block. | |
+ | <br> | ||
+ | Example: | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
import java.util.ArrayList; | import java.util.ArrayList; | ||
Linia 883: | Linia 888: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | More about ''threads'' and their synchronization in [[Concurrent Programming - Threads]]. | |
− | ==== | + | ==== The <span style="color:maroon">native</span> modifier ==== |
− | + | It may be the case that a certain system function or a library function (.dll or .so for example) cannot be called from Java. In that case, the Java application must rely on some functions that are compiled in the native language of the real machine (C or C++ for example), not in the JVM's language. These functions are marked '''native'''. The Jana Native Interface [http://docs.oracle.com/javase/7/docs/technotes/guides/jni/index.html JNI] allows you to call such functions from a Java program, and also to call Java functions from a native language program. | |
− | + | More about native methods implemntation at [http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html Oracle's site]. | |
− | <div class="sfat"><font color="darkgreen"> | + | <div class="sfat"><font color="darkgreen">Advice:</font> Try to avoid using native methods because they are not portable.</div> |
− | === | + | === Class Constants === |
− | + | A field declared at the same time ''static'' and ''final'' is called a class constant. | |
− | === | + | === Class Extension === |
− | + | The Java language supports simple inheritance (see [[Advanced Notions About Object Oriented Programming#Class Hierarchies|class hierarchies]] and [[Advanced Notions About Object Oriented Programming#Polymorphism|polymorphism]]). The keyword use for extending a class is '''extends'''. | |
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> A Java class extends exactly one other class (if this is not specified, then the base class is ''Object'').</div> |
− | + | Example: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
//--------------------------------------------------- | //--------------------------------------------------- | ||
Linia 939: | Linia 944: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === Generic classes === |
+ | There are situations where a particular instance of a class works exclusively with a particular type of data. In this case, if the class is designed to use data of some base type (for example of '''Object''' type), then additional and time consuming steps must be taken to down-cast the base data type (the '''Object''' type data) to the particular type in order to use them. More than that, these down-cast operations are checked only at runtime, increasing the risk of inserting programming errors that are not detectable at compile time. As an example, we describe below a '''Stack''' class that stores references of '''Object''' type, and another class, '''StringStacker''', that uses this stack exclusively for String objects:: | ||
− | |||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
public class Stack{ | public class Stack{ | ||
Linia 972: | Linia 977: | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | <br> | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
public class StringStacker{ | public class StringStacker{ | ||
Linia 979: | Linia 984: | ||
Stack _stack = new Stack(10); | Stack _stack = new Stack(10); | ||
try{ | try{ | ||
− | // String is automatically | + | // String is automatically up-cast to Object |
// we could just as well push any kind of reference | // we could just as well push any kind of reference | ||
// on this stack, by mistake, and reading and trying | // on this stack, by mistake, and reading and trying | ||
− | // to | + | // to down-cast it to String will throw a runtime ClassCastException |
_stack.push("Hello world!"); | _stack.push("Hello world!"); | ||
_stack.push("Byebye world"); | _stack.push("Byebye world"); | ||
− | // Object must be manually | + | // Object must be manually down-cast to String |
// every time, even if it's obvious that all | // every time, even if it's obvious that all | ||
// objects on the stack are Strings | // objects on the stack are Strings | ||
Linia 1.001: | Linia 1.006: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | This example may be solved elegantly with a generic '''Stack class'''. The '''StringStacker''' needs not downcast the data. | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
public class Stack <GenericType>{ | public class Stack <GenericType>{ | ||
Linia 1.033: | Linia 1.038: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | <br> | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
public class StringStacker{ | public class StringStacker{ | ||
Linia 1.063: | Linia 1.068: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | More about generics in this [http://docs.oracle.com/javase/tutorial/java/generics/ tutorial] from Oracle. | |
− | == | + | == Java Interfaces== |
− | + | The Java interface is a structure equivalent to an abstract class without variables and whose methods are all abstract. The only fields that interfaces may have are static constants. Unlike class inheritance, that allows a class to inherit only one base class (simple inheritance), a class may implement any number of interfaces. | |
− | <div class="sfat"><font color="darkgreen"> | + | <div class="sfat"><font color="darkgreen">Hint:</font> Avoid fields in interfaces. Conflicts may appear when a class implements two interfaces with the same name for some constants.</div> |
Linia 1.101: | Linia 1.106: | ||
− | <div class="regula"><font color="#ff0000"> | + | <div class="regula"><font color="#ff0000">Rule:</font> If a class implements an interface, then it must implement all methods declared in the interface, otherwise it must be declared an abstract class, that defers the implementation of some methods to its subclasses.</div> |
− | + | More about interfaces in [[Advanced Notions About Object Oriented Programming#Class Hierarchies|Hierarchies]] and [[Advanced Notions About Object Oriented Programming#Polymorphism|Polymorphism]]. | |
− | == | + | == Iterative Constructs == |
− | === | + | === The <span style="color:maroon">for</span> statement === |
− | + | The '''for''' statement has two variants. One of them is identical to the C '''for''' statement: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | for( | + | for (initializations; condition; updates) { |
//... | //... | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | * '' | + | * ''initializations'' - statements that are executed only once, at the beginning of the first iteration; |
− | * '' | + | * ''condition'' - an expression that controls the loop. It is evaluated prior to entering an iteration. Enter the iteration if the condition is true, otherwise exit the loop. If the condition is missing, it is assumed to be always true. |
− | * '' | + | * ''updates'' - statements that are executed at the end of each iteration; |
− | + | <br> | |
− | + | Example 1: a loop that displays all elements of an array. | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
int[] someArray = getArray(); | int[] someArray = getArray(); | ||
− | for(int i=0; i<someArray.length; i++){ | + | for (int i=0; i < someArray.length; i++) { |
System.out.println(someArray[i]); | System.out.println(someArray[i]); | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | <br> | |
− | + | Example 2: a loop that iterates through a list: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
Node firstNode = getList(); | Node firstNode = getList(); | ||
− | for(Node _eachNode = firstNode; _eachNode != null; _eachNode = _eachNode.getNextNode()){ | + | for (Node _eachNode = firstNode; _eachNode != null; _eachNode = _eachNode.getNextNode()) { |
System.out.println(_eachNode); | System.out.println(_eachNode); | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | <br> | |
− | + | Example 3: an infinite '''for''' loop (don't do that!): | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | for(;;){ | + | for ( ; ; ) { |
System.out.println("Freedom!"); | System.out.println("Freedom!"); | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <br> | ||
+ | The other variant of the '''for''' statement is used to iterate through an array, and uses a reference that directly points to the elements of the array.<br> | ||
+ | Its syntax is: | ||
+ | <syntaxhighlight lang="java"> | ||
+ | for (declaration; array) { | ||
+ | //... | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | * ''declaration'' - declares a reference whose type is that of the elements of the array; | |
+ | * ''array'' - the name of the array. The loop starts with the reference pointing to the first element of the array. At the end of each iteration the reference is moved to the next element. The loop ends after its iteration for the last element of the array or if a '''break''' or '''return''' statement is encountered within some iteration. | ||
+ | <br> | ||
+ | Example 4: a '''for''' loop that behaves exactly as the loop from Example 1: | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
int[] someArray = getArray(); | int[] someArray = getArray(); | ||
Linia 1.154: | Linia 1.170: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === The <span style="color:maroon">while</span> statement === |
− | + | The '''while''' statement has the same syntax as in C: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | while( | + | while (condition){ |
//... something | //... something | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | * '' | + | * ''condition'' - an expression evaluated at the ''beginning'' of each iteration. If true, the loop continues. If false, exit the loop. |
− | + | <br> | |
+ | Example 5: At each iteration a is incremented while b is decremented. The loop ends when a becomes greater than b. | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | int a = | + | int a = 3; |
− | int b = | + | int b = 13; |
− | while(a | + | while (a < b) { |
a++; | a++; | ||
b--; | b--; | ||
Linia 1.176: | Linia 1.193: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === The <span style="color:maroon">do</span>-<span style="color:maroon">while</span> statement === |
− | + | This statement is also written as in C: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | do{ | + | do { |
//... something | //... something | ||
− | }while( | + | } while (condition); |
</syntaxhighlight> | </syntaxhighlight> | ||
− | * '' | + | * ''condition'' - an expression evaluated at the ''end'' of each iteration. If true, the loop goes to the another iteration. If false, exit the loop. |
− | + | <br> | |
+ | Example 6: runs exactly as the previous one. | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | int a = | + | int a = 3; |
− | int b = | + | int b = 13; |
do{ | do{ | ||
a++; | a++; | ||
b--; | b--; | ||
System.out.println(a * b); | System.out.println(a * b); | ||
− | }while(a | + | } while (a < b); |
</syntaxhighlight> | </syntaxhighlight> | ||
+ | <br> | ||
+ | The difference between '''while''' and '''do'''-'''while''' loops is in the way the condition is evaluated. For '''while''' loops it is evaluated at the ''beginning'' of each iteration, whereas for '''do'''-'''while''' loops it's evaluated at the ''end'' of each iteration. A '''do'''-'''while''' loop executes at least one iteration, whereas a '''while''' loop may not be entered at all if its condition is false upon entering the loop. | ||
− | === | + | === The <span style="color:maroon">break</span> and <span style="color:maroon">continue</span> statements === |
− | + | The '''break''' and '''continue''' statements behaves exactly as in C/C++, and they are used to exit a loop ('''break''') or to jump to the end of the current iteration ('''continue'''). | |
− | + | Example 7: search after the first element of an unsorted array of numbers whose value is greater than 100. If the number is odd, jump to the next number. If the number is even and greater than 100, exit the loop: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
int search(int[] someArray){ | int search(int[] someArray){ | ||
int result = 0; | int result = 0; | ||
− | for(int element: someArray){ | + | for (int element: someArray) { |
− | if(element % 2 != 0){ | + | if (element % 2 != 0) { |
continue; | continue; | ||
} | } | ||
− | if(element > 100){ | + | if (element > 100) { |
result = element; | result = element; | ||
break; | break; | ||
Linia 1.219: | Linia 1.239: | ||
return result; | return result; | ||
} | } | ||
− | |||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | <br> | ||
+ | The '''for''', '''while''' and '''do'''-'''while''' loops may be nested one within another. | ||
+ | <div class="regula"><font color="#ff0000">Rule:</font> '''break''' and '''continue''' statements affect only the most inner '''for''', '''while''' or '''do-while''' loop in which they reside.</div> | ||
− | + | == Conditional Constructs == | |
− | == | + | === Conditional operator (the <span style="color:maroon">?</span> operator) === |
− | + | The conditional operator is written and works as in C: | |
− | |||
− | |||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | ( | + | (evaluation_expression ? expression_for_true : expression_for_false) |
</syntaxhighlight> | </syntaxhighlight> | ||
− | + | The value of this conditional operation depends on the logic value of the ''evaluation_expression''. If it's true, the conditional operation takes the value of the ''expression_for_true'', otherwise it takes the value of ''expression_for_false''. | |
− | + | <br> | |
− | + | <br> | |
− | + | Example 8: the static method '''max''' returns the greatest value of a pair of numbers. The reurn value, either the value of a, or the value of b, depends on how the ''evaluation_expression'', a > b, is evaluated. | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
public class Utils{ | public class Utils{ | ||
Linia 1.258: | Linia 1.278: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === The <span style="color:maroon">if</span> - <span style="color:maroon">else</span> statements === |
− | + | The '''if''' - '''else''' statements are the standard conditional statements, and their syntax is exactly as in C: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | if( | + | if (condition) { |
− | // | + | // statements_if_true |
− | }else{ | + | } else { |
− | // | + | // statements_if_false |
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | * '' | + | * ''condition'' - a logic expression. If it evaluates to true, the statements from ''statements_if_true'' block are executed, otherwise the statements of the '''else''' block, ''statements_if_false'', are executed. |
− | + | <br> | |
− | + | Example 9: returns the maximum number from a pair. | |
− | |||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
− | |||
public static float max(float a, float b){ | public static float max(float a, float b){ | ||
float _result = 0; | float _result = 0; | ||
− | if(a > b){ | + | if (a > b) { |
result = a; | result = a; | ||
− | }else{ | + | } else { |
result = b; | result = b; | ||
} | } | ||
return result; | return result; | ||
+ | } | ||
+ | </syntaxhighlight> | ||
+ | <br> | ||
+ | The '''if''' - '''else''' statements may be nested as in the example below. | ||
+ | <br> | ||
+ | <br> | ||
+ | Example 10: limit the range of an input value to [lowLimit, highLimit]. | ||
+ | <syntaxhighlight lang="java"> | ||
+ | public static float clamp(float value, float lowLimit, float highLimit){ | ||
+ | float _result = 0; | ||
+ | if (_value < _lowLimit) { | ||
+ | return lowLimit; | ||
+ | } else if (_value > _highLimit) { | ||
+ | return highLimit; | ||
+ | } else { | ||
+ | return value; | ||
+ | } | ||
} | } | ||
− | + | </syntaxhighlight> | |
+ | <br> | ||
+ | The '''else''' block may be missing. The '''if''' block is executed only if ''condition'' is true. | ||
+ | <br> | ||
+ | <br> | ||
+ | Example 11: compute the absolute value of a number. | ||
+ | <syntaxhighlight lang="java"> | ||
public static float abs(float a){ | public static float abs(float a){ | ||
− | if(a < 0){ | + | if( a < 0) { |
a = -a; | a = -a; | ||
} | } | ||
− | |||
return a; | return a; | ||
− | |||
− | |||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | === | + | === The <span style="color:maroon">switch</span> statement === |
− | + | It is also written as in C. It is useful when there are more than two possible branches from a point in your program: | |
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | switch( | + | switch (expression) { |
− | case | + | case Value_1: |
− | // | + | // branch_1 |
− | + | break; | |
− | case | + | case Value_2: |
− | // | + | // branch_2 |
− | + | break; | |
− | case | + | case Value_3: |
− | // | + | // branch_3 |
− | + | break; | |
default: | default: | ||
− | // | + | // branch_default |
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | * '' | + | * ''expression'' - an expression that evaluates to an integer; |
− | * '' | + | * If ''expression'' evaluates to ''Value_i'' the program jumps to ''branch_i''. ''Value_i'' is an integer constant (of type '''byte''', '''short''', '''int''' or '''long'''). |
− | * '''default''' | + | * If ''expression'' evaluates to a value other than any of the ''Value_i'' constants, the program jumps to the ''branch_default'' block, or if '''default''' keyword is missing, to the first instruction after the whole '''switch''' block. |
− | + | * The '''break''' statement may be written only at the end of branches, and it forces the program to exit the '''switch''' block. | |
− | <div class="regula"><font color="#ff0000"> | + | <br> |
− | + | <div class="regula"><font color="#ff0000">Be careful:</font> If the '''break''' statements is missing from some branch the program enters the next branch! The statements are executed branch after branch until a '''break''' statement is encountered, or until the end of the whole '''switch''' block.</div> | |
− | + | <br> | |
+ | Example 12: | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
− | public String intToString(int _value){ | + | public String intToString(int _value) { |
String _result = ""; | String _result = ""; | ||
− | switch(_value){ | + | switch (_value){ |
case 0: _result = "zero"; break; | case 0: _result = "zero"; break; | ||
case 1: _result = "one"; break; | case 1: _result = "one"; break; | ||
Linia 1.357: | Linia 1.378: | ||
default: _result = "more than nine"; break; | default: _result = "more than nine"; break; | ||
} | } | ||
− | |||
return _result; | return _result; | ||
} | } | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | <br> | ||
+ | Starting from JDK 1.7 strings are also accepted for evaluation. If you use a String object as ''expression'', all ''Value_i'' constants must be literal strings; | ||
− | == | + | == Keywords Related to Exceptions == |
− | |||
− | |||
+ | * '''throw''' - used to generate an exception. The '''throw''' keyword is followed by a reference to the exception object to be thrown, or by an explicit instantiation of that exception object. | ||
+ | * '''throws''' - appears in the declaration of a method that does not handle some types of exception. The '''throws''' keyword is followed by a coma-separated list of that exception types (their order is not important). | ||
+ | * '''try''' and '''catch''' - used if you want to handle locally the exception. The '''try''' keyword is attached to a block of statements that is prone to throw exceptions. The '''catch''' keyword precedes a block of statements designed to handle a particular exception. A '''try''' block may be followed by multiple '''catch''' blocks, each designed to handle a particular type of exception (the order of '''catch''' blocks is critical: derived exceptions must precede the basic ones). | ||
+ | <br> | ||
+ | Example 13: | ||
<syntaxhighlight lang="java"> | <syntaxhighlight lang="java"> | ||
public class TestClass{ | public class TestClass{ | ||
Linia 1.402: | Linia 1.427: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
+ | More about exceptions and how they are handled in [[Exception Handling]]. | ||
− | + | == Operators == | |
− | + | The complete list of Java operators: | |
− | |||
− | |||
{| class="wikitable" | {| class="wikitable" | ||
|- | |- | ||
− | ! style="text-align: center" | | + | ! style="text-align: center" | Precedence |
! style="text-align: center" | Operator | ! style="text-align: center" | Operator | ||
− | ! style="text-align: center" | | + | ! style="text-align: center" | Description |
− | ! style="text-align: center" | | + | ! style="text-align: center" | Associativity |
|- | |- | ||
! rowspan=3| 1 | ! rowspan=3| 1 | ||
| style="border-bottom-style: none; border-top-style: none" | <code>()</code> | | style="border-bottom-style: none; border-top-style: none" | <code>()</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | method call |
− | | style="vertical-align: center" rowspan="4" | | + | | style="vertical-align: center" rowspan="4" | from left to right |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>[]</code> | | style="border-bottom-style: none; border-top-style: none" | <code>[]</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | acces an array's element |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>.</code> | | style="border-bottom-style: none; border-top-style: none" | <code>.</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | "dot" operator (acces to a class' member) |
|- | |- | ||
! 2 | ! 2 | ||
| style="border-bottom-style: none" | <code>++</code> <code>--</code> | | style="border-bottom-style: none" | <code>++</code> <code>--</code> | ||
− | | style="border-bottom-style: none" | | + | | style="border-bottom-style: none" | postfix increment and decrement |
|- | |- | ||
! rowspan=5| 3 | ! rowspan=5| 3 | ||
| style="border-bottom-style: none" | <code>++</code> <code>--</code> | | style="border-bottom-style: none" | <code>++</code> <code>--</code> | ||
− | | style="border-bottom-style: none" | | + | | style="border-bottom-style: none" | prefix increment and decrement |
− | | style="vertical-align: center" rowspan="5" | | + | | style="vertical-align: center" rowspan="5" | from right to left |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>+</code> <code>-</code> | | style="border-bottom-style: none; border-top-style: none" | <code>+</code> <code>-</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | unary plus and minus |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>!</code> <code>~</code> | | style="border-bottom-style: none; border-top-style: none" | <code>!</code> <code>~</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | logic NOT and bitwise NOT |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>(''type'') val</code> | | style="border-bottom-style: none; border-top-style: none" | <code>(''type'') val</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | type cast |
|- | |- | ||
| style="border-top-style: none" | <code>new</code> | | style="border-top-style: none" | <code>new</code> | ||
− | | style="border-top-style: none" | | + | | style="border-top-style: none" | object or array instantiation |
|- | |- | ||
! 4 | ! 4 | ||
| <code>*</code> <code>/</code> <code>%</code> | | <code>*</code> <code>/</code> <code>%</code> | ||
− | | | + | | Multiplication, division and modulo (remainder) |
− | | style="vertical-align: center" rowspan="13" | | + | | style="vertical-align: center" rowspan="13" | from left to right |
|- | |- | ||
! rowspan=2| 5 | ! rowspan=2| 5 | ||
| style="border-bottom-style: none;" | <code>+</code> <code>-</code> | | style="border-bottom-style: none;" | <code>+</code> <code>-</code> | ||
− | | style="border-bottom-style: none;" | | + | | style="border-bottom-style: none;" | addition and subtraction |
|- | |- | ||
| style="border-top-style: none" | <code>+</code> | | style="border-top-style: none" | <code>+</code> | ||
− | | style="border-top-style: none" | | + | | style="border-top-style: none" | string concatenation |
|- | |- | ||
! 6 | ! 6 | ||
| <code><<</code> <code>>></code> <code>>>></code> | | <code><<</code> <code>>></code> <code>>>></code> | ||
− | | | + | | leftshift, rightshift, arithmetic righshift (preserves sign) |
|- | |- | ||
! rowspan=3| 7 | ! rowspan=3| 7 | ||
| style="border-bottom-style: none;" | <code><</code> <code><=</code> | | style="border-bottom-style: none;" | <code><</code> <code><=</code> | ||
− | | style="border-bottom-style: none;" | | + | | style="border-bottom-style: none;" | "less than" and "less than or equal" logic comparisons |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>></code> <code>>=</code> | | style="border-bottom-style: none; border-top-style: none" | <code>></code> <code>>=</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | "greater than" and "greater than or equal" logic comparisons |
|- | |- | ||
| style="border-top-style: none" | <code>instanceof</code> | | style="border-top-style: none" | <code>instanceof</code> | ||
− | | style="border-top-style: none" | | + | | style="border-top-style: none" | type comparison |
|- | |- | ||
! 8 | ! 8 | ||
| <code>==</code> <code>!=</code> | | <code>==</code> <code>!=</code> | ||
− | | | + | | "equal" and "not equal" logic comparisons |
|- | |- | ||
! 9 | ! 9 | ||
| <code>&</code> | | <code>&</code> | ||
− | | AND | + | | bitwise AND |
|- | |- | ||
! 10 | ! 10 | ||
| <code>^</code> | | <code>^</code> | ||
− | | XOR ( | + | | bitwise XOR (exclusive OR) |
|- | |- | ||
! 11 | ! 11 | ||
| <code><nowiki>|</nowiki></code> | | <code><nowiki>|</nowiki></code> | ||
− | | OR ( | + | | bitwise OR (inclusive OR) |
|- | |- | ||
! 12 | ! 12 | ||
| <code>&&</code> | | <code>&&</code> | ||
− | | AND | + | | logic AND |
|- | |- | ||
! 13 | ! 13 | ||
| <code><nowiki>||</nowiki></code> | | <code><nowiki>||</nowiki></code> | ||
− | | OR | + | | logic OR |
|- | |- | ||
! 14 | ! 14 | ||
| <code>''c'' ? ''t'' : ''f''</code> | | <code>''c'' ? ''t'' : ''f''</code> | ||
− | | | + | | ternary conditional operator (see [[#Conditional operator (the ? operator)]]) |
− | | style="vertical-align: center" rowspan="6" | | + | | style="vertical-align: center" rowspan="6" | from right to left |
|- | |- | ||
! rowspan=5| 15 | ! rowspan=5| 15 | ||
| style="border-bottom-style: none" | <code>=</code> | | style="border-bottom-style: none" | <code>=</code> | ||
− | | style="border-bottom-style: none" | | + | | style="border-bottom-style: none" | assignment |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>+=</code> <code>-=</code> | | style="border-bottom-style: none; border-top-style: none" | <code>+=</code> <code>-=</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | compound assignment with addition or subtraction |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code>*=</code> <code>/=</code> <code>%=</code> | | style="border-bottom-style: none; border-top-style: none" | <code>*=</code> <code>/=</code> <code>%=</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | compound assignment with multiplication, division, modulo |
|- | |- | ||
| style="border-bottom-style: none; border-top-style: none" | <code><<=</code> <code>>>=</code> <code>>>>=</code> | | style="border-bottom-style: none; border-top-style: none" | <code><<=</code> <code>>>=</code> <code>>>>=</code> | ||
− | | style="border-bottom-style: none; border-top-style: none" | | + | | style="border-bottom-style: none; border-top-style: none" | compound assignment with leftshift, rightshift and arithmetic rightshift |
|- | |- | ||
| style="border-top-style: none" | <code>&=</code> <code>^=</code> <code><nowiki>|</nowiki>=</code> | | style="border-top-style: none" | <code>&=</code> <code>^=</code> <code><nowiki>|</nowiki>=</code> | ||
− | | style="border-top-style: none" | | + | | style="border-top-style: none" | compound assignment with bitwise AND, XOR, and OR |
|} | |} | ||
− | == | + | Unlike in C++, the operators cannot be overloaded in Java. |
+ | |||
+ | == Web Resources == | ||
− | # [http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf | + | # [http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf The Java Language Specifications, v.7] |
− | # [http://docs.oracle.com/javase/specs/jvms/se7/jvms7.pdf | + | # [http://docs.oracle.com/javase/specs/jvms/se7/jvms7.pdf The Java Virtual Machine Specifications, v.7] (advanced topic) |
− | # [http://en.wikipedia.org/wiki/Java_syntax | + | # [http://en.wikipedia.org/wiki/Java_syntax Java Syntax - Wikipedia] |
Versiunea curentă din 5 decembrie 2015 01:47
A Java application is composed of two types of elements: classes and interfaces.
Before presenting the lexical structure of a class and interface, we need to list the data types.
Data Types
In Java, there are two types of data: primitives and references. The primitive types refer to those which have immediate values (numerical or logical), and references are "names" which identify objects.
Primitive Types
In Java, the primitive types are:
Name | Category | Bit count | Possible values |
---|---|---|---|
byte | integer | 8 | -128 : 127 |
short | integer | 16 | -32768 : 32767 |
int | integer | 32 | -2147483648 : 2147483647 |
long | integer | 64 | -9223372036854775808 : 9223372036854775807 |
char | character | 16 | Any Unicode character |
boolean | logic | 8 | true, false |
float | floating point | 32 | ±1.18 x 10-38 : ±3.4 x 1038 |
double | floating point | 64 | ±2.23 x 10-308 : ±1.80 x 10308 |
Primitive type variables are declared just like in C. For example:
int someInteger;
int someOtherInteger = 10;
float someFloat = 10.5f;
double someDouble = 5.3 + someFloat;
boolean condition = true;
char oneChar = 'g';
char newLineChar = '\n';
Attention: In Java, there are no unsigned types.
Similar to C, there are cast operators for primitive types in Java as well. Some conversion operations are implicit (from integer to floating point), but some need to be explicitly specified (from floating point to integer, from char to integer), and others are not possible at all (from boolean to any other type and vice-versa).
In Java, primitive type variables are implicitly initialized with the value 0, and the logic ones with the value false.
Reference Types
Reference variables are objects identifiers. Two references can identify the same object but a reference can't identify two objects at the same time.
References are initialized implicitly with the null value.
Object References
Objects of any type (class), are created by using the new operator, just like in the following example:
1Object obj;
2new Object();
3obj = new Object();
You can see line 2, which instantiate a new object, of class Object, but there is no reference to this newly created object. Thus, immediately after instantiation, the allocated memory is freed by the garbage collector, and it can no longer be accessed. Line 3 instantiate a new object and the obj variable will reference the newly created object. More about instantiation of objects and constructors in the following sections.
Character Strings in Java - Class String
In Java, character strings are implemented by class String:
String _name;
_name = "George";
//the following two lines are equivalent
String _firstName = "Vasile";
String _firstName2 = new String("Vasile");
The only overloaded operator in the Java language is the operator +, used for concatenating character strings. If operator + is used for concatenating a String with a primitive value, or reference, then the latter is first automatically converted to a String, by using String.valueOf() method.
String _name;
_name= "George";
String _firstName = "Vasile";
String _fullName= _name + " " + _firstName ;
String _title = "I am number " + 7;
String _firstName = "Vasile";
String _firstName2 = new String("Vasile");
if(_firstName2 == _firstName ){
System.out.println("Equal references");
}else{
System.out.println("Different references");
}
if(_firstName2 .equals(_firstName )){
System.out.println("Equal strings");
}else{
System.out.println("Different strings");
}
Displaying a String in the standard output stream, in a console, is done by using the methods "print" or "println" of the field out of type PrintSteam in the System class:
System.out.println("Hello world!");
String _someString = "Trust " + "no. " + 1;
System.out.println(_someString);
Multi-dimensional Arrays
Arrays are treated as objects in Java, as in there are reference type variables which identify the memory area allocated for the array.
Attention: In the case of reference array instantiation (where each location is a reference, and not a primitive type), the new operator only allocate memory for the array, not each of the array's locations.
Attention: Just like in C, the counting of the elements start from 0. Thus, for an array of 5 elements, the valid positions are 0, 1, 2, 3 and 4.
All arrays have a field called length which holds the number of locations in the array. This field is read-only.
int[] _array1 = new int[5];
System.out.println(_array1.length); //"5" will be displayed
int[][] _array2 = new int[5][9];
System.out.println(_array2.length); //"5" will be displayed
System.out.println(_array2[0].length); //"9" will be displayed
The Java Class
The class is the base type in Java, as in any other object oriented language.
The keyword that define a class is class, being always followed by the class name and its implementation, between curly brackets.
class SomeClass{
// here comes the implementation of the class
}
The implementation of a class is made of field (property) definitions and method definitions and implementations. The fields represent the data contained by the class and the methods represent its functionality, meaning the functions that modify the field values.
Java Packets
Classes of a Java application are structured in a hierarchy similar to the file system: files and directories (folders), with the classes being similar to files and packages to directories. The separator used between package names and classes is ".".
The keyword specifying the package that contains the class/ interface is package. If this directive is missing, the class is placed implicitly in the root of the package hierarchy.
package myPackage;
import java.util.ArrayList;
import java.io.*;
class TestClass{
public static void main(String[] _args){
//ArrayList class is in package java.util so it needs to be imported
ArrayList _arrayList = new ArrayList();
//both FileOutputStream and IOException are in package java.io so they
//are both available.
try{
FileOutputStream _fileOutputStream = new FileOutputStream("test");
_fileOutputStream.close();
}catch(IOException _ioe){
_ioe.printStackTrace();
}
//Class System is in package java.lang so it is automatically imported
System.out.println("Done!");
}
}
Field Definition
Fields, like any other variable, may be of primitive or reference type. They are declared inside the class, but outside any method.
class SomeClass{
//fields here
int somePrimitiveField;
boolean someOtherPrimitiveField;
Object aReferenceField;
int[][] anotherReferenceFieldToAnArray;
}
Attention: Fields have different values for each instance of the class, meaning each object.
Method Definition
Methods can be defined and implemented exclusively inside a class. Methods change the state of the object by changing the values of the fields. Just like in C, methods are declared using the following template:
- zero or more modifiers;
- returned type (or void if the method does not return a value) - attention, constructors does not have a return type, not even void;
- method name
- between parentheses, the list of arguments, defined by type and name, separated by commas (this list can be empty)
- between curly brackets, the method body (implementation).
class SomeClass{
//fields here
int somePrimitiveField;
boolean someOtherPrimitiveField;
Object aReferenceField;
int[][] anotherReferenceFieldToAnArray;
//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
return somePrimitiveField;
}
//---------------------------------------------------------------------
void setSomePrimitiveField(int _somePrimitiveField){
somePrimitiveField = _somePrimitiveField;
}
//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
if(_aReferenceField != null){
aReference = _aReferenceField;
}
return aReference != null;
}
}
Primitive or reference type variables declared inside a method, or as an argument of a method, are called local variables and are not class fields.
Class Constructors
Constructors are special methods of a class that are called automatically when an object is instantiated. Constructors have two specific properties:
Example of constructors for class SomeClass:
class SomeClass{
//fields here
int somePrimitiveField;
boolean someOtherPrimitiveField;
Object aReferenceField;
int[][] anotherReferenceFieldToAnArray;
//constructors here
//---------------------------------------------------------------------
SomeClass(){ //this is a constructor
somePrimitiveField = 0;
someOtherPrimitiveField = false;
aReferenceField = new Object();
anotherReferenceFieldToAnArray = null;
}
//---------------------------------------------------------------------
SomeClass(int _somePrimitiveField){ //this is another constructor
somePrimitiveField = _somePrimitiveField;
someOtherPrimitiveField = false;
aReferenceField = new Object();
anotherReferenceFieldToAnArray = null;
}
//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
return somePrimitiveField;
}
//---------------------------------------------------------------------
void setSomePrimitiveField(int _somePrimitiveField){
somePrimitiveField = _somePrimitiveField;
}
//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
if(_aReferenceField != null){
aReference = _aReferenceField;
}
return aReference != null;
}
}
Example of constructor calling:
class MainClass{
public static void main(String[] _args){
SomeClass _obj1 = new SomeClass(); //this calls the first constructor
SomeClass _obj2 = new SomeClass(1234); //this calls the second constructor
System.out.println(_obj1.getSomePrimitiveField()); //this will print 0
System.out.println(_obj2.getSomePrimitiveField()); //this will print 1234
}
}
this and super Keywords
Keyword this can be used in two ways:
- as a call to a constructor from another constructor of the same class;
- as a reference to the current object as an instance of the current class;
Example if using keyword this:
import java.util.ArrayList;
class SomeClass{
//fields here
int somePrimitiveField;
boolean someOtherPrimitiveField;
Object aReferenceField;
int[][] anotherReferenceFieldToAnArray;
//constructors here
//---------------------------------------------------------------------
SomeClass(){ //this is a constructor
this(10); //this is a call to the other constructor
// (see method overloading)
}
//---------------------------------------------------------------------
SomeClass(int _somePrimitiveField){ //this is another constructor
somePrimitiveField = _somePrimitiveField;
someOtherPrimitiveField = false;
aReferenceField = new Object();
anotherReferenceFieldToAnArray = null;
}
//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
return somePrimitiveField;
}
//---------------------------------------------------------------------
void setSomePrimitiveField(int somePrimitiveField){
this.somePrimitiveField = somePrimitiveField;
/*here, "this" is a reference to the
*current object. It is used to make the difference
*between the field somePrimitiveField and the local
*variable with the same name. Writing "somePrimitiveField"
*with no object specifier ("this") will direct the compiler
*to the closest defined variable with that name: the local
*variable:
*/
somePrimitiveField = 10; //this is the local variable
this.somePrimitiveField = 10; // this is the field
/*"this" can also be used for passing the current object
*as argument to other methods:
*/
ArrayList _list = new ArrayList();
_list.add(this);
}
//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
if(_aReferenceField != null){
aReference = _aReferenceField;
}
return aReference != null;
}
}
Keyword super can be used in two ways (vezi class hierarchies)
- as a call to a super-class constructor from a constructor in the current class;
- as a reference to the current object, as an instance of the super-class.
import java.util.ArrayList;
class SomeClass{
//fields here
int somePrimitiveField;
boolean someOtherPrimitiveField;
Object aReferenceField;
int[][] anotherReferenceFieldToAnArray;
//constructors here
//---------------------------------------------------------------------
SomeClass(){ //this is a constructor
this(10); //this is a call to the other constructor
// (see method overloading)
}
//---------------------------------------------------------------------
SomeClass(int _somePrimitiveField){ //this is another constructor
super();
/* Class SomeClass is extended from Object class so
* the super() call is the call to the Object()
* constructor.
*/
somePrimitiveField = _somePrimitiveField;
someOtherPrimitiveField = false;
aReferenceField = new Object();
anotherReferenceFieldToAnArray = null;
}
//methods here
//---------------------------------------------------------------------
int getSomePrimitiveField(){
return somePrimitiveField;
}
//---------------------------------------------------------------------
void setSomePrimitiveField(int somePrimitiveField){
this.somePrimitiveField = somePrimitiveField;
/*here, "this" is a reference to the
*current object. It is used to make the difference
*between the field somePrimitiveField and the local
*variable with the same name. Writing "somePrimitiveField"
*with no object specifier ("this") will direct the compiler
*to the closest defined variable with that name: the local
*variable:
*/
somePrimitiveField = 10; //this is the local variable
this.somePrimitiveField = 10; // this is the field
/*"this" can also be used for passing the current object
*as argument to other methods:
*/
ArrayList _list = new ArrayList();
_list.add(this);
}
//---------------------------------------------------------------------
boolean aMoreComplexMethod(Object _aReferenceField){
if(_aReferenceField != null){
aReference = _aReferenceField;
}
return aReference != null;
}
//---------------------------------------------------------------------
String toString(){
return "SomeClass " + super.toString();
/* Here, the "super" keyword is used as a reference to the current
* object but it is calling the method "toString" defined in the
* superclass (see method overwriting). If the "super" was missing,
* it would recursively call the same method, crashing the program.
* Instead, it is now calling an entirely different method belonging
* to the superclass.
*/
}
}
Static Members
Static members of a class represent the members which do not change their value or behavior for each distinct object, meaning they are exist in the class context, not the object, or instance context.
class SomeClass{
//fields here
static int someStaticField;
int somePrimitiveField;
boolean someOtherPrimitiveField;
Object aReferenceField;
int[][] anotherReferenceFieldToAnArray;
}
Special Modifiers
Access Modifiers
Modifier | Current Class | Package | Derived Class | Outside Package |
---|---|---|---|---|
public | Yes | Yes | Yes | Yes |
protected | Yes | Yes | Yes | No |
default(no specifier) | Yes | Yes | No | No |
private | Yes | No | No | No |
import java.util.ArrayList;
public class SomeClass{
//fields here
private int somePrimitiveField;
private boolean someOtherPrimitiveField;
private Object aReferenceField;
private int[][] anotherReferenceFieldToAnArray;
//constructors here
//---------------------------------------------------------------------
public SomeClass(){ //this is a constructor
this(10); //this is a call to the other constructor
// (see method overloading)
}
//---------------------------------------------------------------------
public SomeClass(int _somePrimitiveField){//this is another constructor
super();
/* Class SomeClass is extended from Object class so
* the super() call is the call to the Object()
* constructor.
*/
somePrimitiveField = _somePrimitiveField;
someOtherPrimitiveField = false;
aReferenceField = new Object();
anotherReferenceFieldToAnArray = null;
}
//methods here
//---------------------------------------------------------------------
public int getSomePrimitiveField(){
return somePrimitiveField;
}
//---------------------------------------------------------------------
protected void setSomePrimitiveField(int somePrimitiveField){
this.somePrimitiveField = somePrimitiveField;
/*here, "this" is a reference to the
*current object. It is used to make the difference
*between the field somePrimitiveField and the local
*variable with the same name. Writing "somePrimitiveField"
*with no object specifier ("this") will direct the compiler
*to the closest defined variable with that name: the local
*variable:
*/
somePrimitiveField = 10; //this is the local variable
this.somePrimitiveField = 10; // this is the field
/*"this" can also be used for passing the current object
*as argument to other methods:
*/
ArrayList _list = new ArrayList();
_list.add(this);
}
//---------------------------------------------------------------------
private boolean aMoreComplexMethod(Object _aReferenceField){
if(_aReferenceField != null){
aReference = _aReferenceField;
}
return aReference != null;
}
//---------------------------------------------------------------------
public String toString(){
return "SomeClass " + super.toString();
/* Here, the "super" keyword is used as a reference to the current
* object but it is calling the method "toString" defined in the
* superclass (see method overwriting). If the "super" was missing,
* it would recursively call the same method, crashing the program.
* Instead, it is now calling an entirely different method belonging
* to the superclass.
*/
}
}
The public modifier
A public class or member can be accessed from any other class.
The protected modifier
A protected field or method is accessible for the classes defined in the same package and for derived classes.
The default modifier (not explicit)
The lack of an access specifier means that the element is accessible from the current class or classes from the same package, but not other classes.
The private modifier
A private field or method can only be accessed from the defining class.
The final modifier
The final modifier can be applied to:
- a class - the class can't be extended;
- an interface - the interface can't be extended;
- a method - the method can't be overridden;
- a field - the field can only take one value and it will remain constant throughout of the object's lifetime;
A field which is both static and final is called a class constant.
The abstract modifier
Any method without body (without implementation) is an abstract method
Example:
abstract class Sorter{
protected Object[] data;
public Sorter(Object[] _data){
data = _data;
}
//this is an abstract method
protected abstract void sort();
public Object[] getResult(){
sort();
return data;
}
}
class BubbleSorter extends Sorter{
public BubbleSorter(Object[] _data){
super(data);
}
//this is the implementation of the abstract method
protected void sort(){
boolean _done;
do{
_done = true;
for(int i=0; i<data.length - 1; i++){
if(compare(data[i], data[i + 1]) < 0){
Object _tmp = data[i];
data[i] = data[i + 1];
data[i + 1] = _tmp;
_done = false;
}
}
}while(!_done);
}
private int compare(Object _obj1, Object obj2){
//...
}
}
The volatile modifier
A field is declared volatile when that field for some object is accesed by more than one thread, and you want any update to be propagated into the main memory. When a thread writes into a volatile field, any other thread that access that field will see its updated value. Otherwise, the update might stay in the thread's local cache while the other threads continue to use the old value from their local caches.
The volatile fields allow threads to communicate without employing the synchronization mechanism, but this is possible only if there is no any risk to run into race conditions. More details in Concurrent Programming - Threads.
The transient modifier
A class field is declared transient if you do not want it's value to be serialized together with the other object's fields when the object is serialized. It's value will be the default value after the object is deserialized (see Serialization).
The synchronized modifier
A synchronized method or block of statements cannot be executed by more than one thread at a time. If two threads need to call such a method, or execute such a block, one of them must wait for the other to return from the method or to exit the block.
Example:
import java.util.ArrayList;
public class Queue extends ArrayList{
public Queue(){
super();
}
public synchronized void push(Object _obj){
add(_obj);
}
public Object pop(){
if(size() != 0){
synchronized(this){
return remove(0);
}
}else{
throw new RuntimeException("Queue empty!");
}
}
}
More about threads and their synchronization in Concurrent Programming - Threads.
The native modifier
It may be the case that a certain system function or a library function (.dll or .so for example) cannot be called from Java. In that case, the Java application must rely on some functions that are compiled in the native language of the real machine (C or C++ for example), not in the JVM's language. These functions are marked native. The Jana Native Interface JNI allows you to call such functions from a Java program, and also to call Java functions from a native language program.
More about native methods implemntation at Oracle's site.
Class Constants
A field declared at the same time static and final is called a class constant.
Class Extension
The Java language supports simple inheritance (see class hierarchies and polymorphism). The keyword use for extending a class is extends.
Example:
//---------------------------------------------------
//file Vehicle.java
public class Vehicle{ //class Vehicle extends Object
protected int cylinders;
protected float maxSpeed;
protected static float maxAcceptedVehicleMass;
protected float vehicleMass;
public void startEngine(){
//...
}
}
//---------------------------------------------------
//file Truck.java
public class Truck extends Vehicle{ //class Truck extends Vehicle
protected float maxCargoWeight;
protected float currentCargoWeight;
public void loadCargo(float _cargo){
// protected fields maxAcceptedVehicleMass and vehicleMass
// are inherited from Vehicle class
if(currentCargoWeight + _cargo <= maxCargoWeight &&
vehicleMass + currentCargoWeight + _cargo <= maxAcceptedVehicleMass){
currentCargoWeight += _cargo;
}
}
}
Generic classes
There are situations where a particular instance of a class works exclusively with a particular type of data. In this case, if the class is designed to use data of some base type (for example of Object type), then additional and time consuming steps must be taken to down-cast the base data type (the Object type data) to the particular type in order to use them. More than that, these down-cast operations are checked only at runtime, increasing the risk of inserting programming errors that are not detectable at compile time. As an example, we describe below a Stack class that stores references of Object type, and another class, StringStacker, that uses this stack exclusively for String objects::
public class Stack{
private Object[] stackArray;
private int stackTop;
public Stack(int _size){
stackArray = new Object[_size];
stackTop = 0;
}
public Object pop() throws Exception{
if(stackTop > 0){
return stackArray[--stackTop];
}
throw new Exception("Stack empty");
}
public void push(Object _obj) throws Exception{
if(stackTop < stack.length){
stackArray[stackTop++] = _obj;
return;
}
throw new Exception("Stack full");
}
}
public class StringStacker{
public static void main(String[] _args){
Stack _stack = new Stack(10);
try{
// String is automatically up-cast to Object
// we could just as well push any kind of reference
// on this stack, by mistake, and reading and trying
// to down-cast it to String will throw a runtime ClassCastException
_stack.push("Hello world!");
_stack.push("Byebye world");
// Object must be manually down-cast to String
// every time, even if it's obvious that all
// objects on the stack are Strings
String _secondString = (String)_stack.pop();
String _firstString = (String)_stack.pop();
System.out.println(_secondString + ", " + _firstString);
}catch(Exception _e){
System.out.println("Stack error: " + _e.getMessage());
}
}
}
This example may be solved elegantly with a generic Stack class. The StringStacker needs not downcast the data.
public class Stack <GenericType>{
private GenericType[] stackArray;
private int stackTop;
public Stack(int _size){
stackArray = new GenericType[_size];
stackTop = 0;
}
public GenericType pop() throws Exception{
if(stackTop > 0){
return stackArray[--stackTop];
}
throw new Exception("Stack empty");
}
public void push(GenericType _obj) throws Exception{
if(stackTop < stack.length){
stackArray[stackTop++] = _obj;
return;
}
throw new Exception("Stack full");
}
}
public class StringStacker{
public static void main(String[] _args){
// at this point, the _stack object is an instance
// of the class Stack, where GenericType has been
// replaced by String
Stack<String> _stack = new Stack<String>(10);
try{
// now the push method only takes Strings as
// an argument; trying to push an Object will
// fail with a compile time error
_stack.push("Hello world!");
_stack.push("Byebye world");
// pop() will now return a String so casting
// is no longer necessary
String _secondString = _stack.pop();
String _firstString = _stack.pop();
System.out.println(_secondString + ", " + _firstString);
}catch(Exception _e){
System.out.println("Stack error: " + _e.getMessage());
}
}
}
More about generics in this tutorial from Oracle.
Java Interfaces
The Java interface is a structure equivalent to an abstract class without variables and whose methods are all abstract. The only fields that interfaces may have are static constants. Unlike class inheritance, that allows a class to inherit only one base class (simple inheritance), a class may implement any number of interfaces.
//---------------------------------------------------
//file Closeable.java
public interface Closeable{
public void close();
}
//---------------------------------------------------
//file Openable.java
public interface Openable{
public void open();
}
//---------------------------------------------------
//file Stream.java
public class Stream implements Openable, Closeable{
public void close(){
//.. something here
}
public void open(){
//... something here
}
}
//---------------------------------------------------
More about interfaces in Hierarchies and Polymorphism.
Iterative Constructs
The for statement
The for statement has two variants. One of them is identical to the C for statement:
for (initializations; condition; updates) {
//...
}
- initializations - statements that are executed only once, at the beginning of the first iteration;
- condition - an expression that controls the loop. It is evaluated prior to entering an iteration. Enter the iteration if the condition is true, otherwise exit the loop. If the condition is missing, it is assumed to be always true.
- updates - statements that are executed at the end of each iteration;
Example 1: a loop that displays all elements of an array.
int[] someArray = getArray();
for (int i=0; i < someArray.length; i++) {
System.out.println(someArray[i]);
}
Example 2: a loop that iterates through a list:
Node firstNode = getList();
for (Node _eachNode = firstNode; _eachNode != null; _eachNode = _eachNode.getNextNode()) {
System.out.println(_eachNode);
}
Example 3: an infinite for loop (don't do that!):
for ( ; ; ) {
System.out.println("Freedom!");
}
The other variant of the for statement is used to iterate through an array, and uses a reference that directly points to the elements of the array.
Its syntax is:
for (declaration; array) {
//...
}
- declaration - declares a reference whose type is that of the elements of the array;
- array - the name of the array. The loop starts with the reference pointing to the first element of the array. At the end of each iteration the reference is moved to the next element. The loop ends after its iteration for the last element of the array or if a break or return statement is encountered within some iteration.
Example 4: a for loop that behaves exactly as the loop from Example 1:
int[] someArray = getArray();
for (int element : someArray) {
System.out.println(element);
}
The while statement
The while statement has the same syntax as in C:
while (condition){
//... something
}
- condition - an expression evaluated at the beginning of each iteration. If true, the loop continues. If false, exit the loop.
Example 5: At each iteration a is incremented while b is decremented. The loop ends when a becomes greater than b.
int a = 3;
int b = 13;
while (a < b) {
a++;
b--;
System.out.println(a * b);
}
The do-while statement
This statement is also written as in C:
do {
//... something
} while (condition);
- condition - an expression evaluated at the end of each iteration. If true, the loop goes to the another iteration. If false, exit the loop.
Example 6: runs exactly as the previous one.
int a = 3;
int b = 13;
do{
a++;
b--;
System.out.println(a * b);
} while (a < b);
The difference between while and do-while loops is in the way the condition is evaluated. For while loops it is evaluated at the beginning of each iteration, whereas for do-while loops it's evaluated at the end of each iteration. A do-while loop executes at least one iteration, whereas a while loop may not be entered at all if its condition is false upon entering the loop.
The break and continue statements
The break and continue statements behaves exactly as in C/C++, and they are used to exit a loop (break) or to jump to the end of the current iteration (continue).
Example 7: search after the first element of an unsorted array of numbers whose value is greater than 100. If the number is odd, jump to the next number. If the number is even and greater than 100, exit the loop:
int search(int[] someArray){
int result = 0;
for (int element: someArray) {
if (element % 2 != 0) {
continue;
}
if (element > 100) {
result = element;
break;
}
}
return result;
}
The for, while and do-while loops may be nested one within another.
Conditional Constructs
Conditional operator (the ? operator)
The conditional operator is written and works as in C:
(evaluation_expression ? expression_for_true : expression_for_false)
The value of this conditional operation depends on the logic value of the evaluation_expression. If it's true, the conditional operation takes the value of the expression_for_true, otherwise it takes the value of expression_for_false.
Example 8: the static method max returns the greatest value of a pair of numbers. The reurn value, either the value of a, or the value of b, depends on how the evaluation_expression, a > b, is evaluated.
public class Utils{
//private constructor means the class can't be instantiated
private Utils(){
//nothing here
}
public static float max(float a, float b){
// if a is greater than b, the expression is
// evaluated to a and the value of a is returned
// else the expression is evaluated to b and the
// value of b is returned
return a > b ? a : b;
}
}
The if - else statements
The if - else statements are the standard conditional statements, and their syntax is exactly as in C:
if (condition) {
// statements_if_true
} else {
// statements_if_false
}
- condition - a logic expression. If it evaluates to true, the statements from statements_if_true block are executed, otherwise the statements of the else block, statements_if_false, are executed.
Example 9: returns the maximum number from a pair.
public static float max(float a, float b){
float _result = 0;
if (a > b) {
result = a;
} else {
result = b;
}
return result;
}
The if - else statements may be nested as in the example below.
Example 10: limit the range of an input value to [lowLimit, highLimit].
public static float clamp(float value, float lowLimit, float highLimit){
float _result = 0;
if (_value < _lowLimit) {
return lowLimit;
} else if (_value > _highLimit) {
return highLimit;
} else {
return value;
}
}
The else block may be missing. The if block is executed only if condition is true.
Example 11: compute the absolute value of a number.
public static float abs(float a){
if( a < 0) {
a = -a;
}
return a;
}
The switch statement
It is also written as in C. It is useful when there are more than two possible branches from a point in your program:
switch (expression) {
case Value_1:
// branch_1
break;
case Value_2:
// branch_2
break;
case Value_3:
// branch_3
break;
default:
// branch_default
}
- expression - an expression that evaluates to an integer;
- If expression evaluates to Value_i the program jumps to branch_i. Value_i is an integer constant (of type byte, short, int or long).
- If expression evaluates to a value other than any of the Value_i constants, the program jumps to the branch_default block, or if default keyword is missing, to the first instruction after the whole switch block.
- The break statement may be written only at the end of branches, and it forces the program to exit the switch block.
Example 12:
public String intToString(int _value) {
String _result = "";
switch (_value){
case 0: _result = "zero"; break;
case 1: _result = "one"; break;
case 2: _result = "two"; break;
case 3: _result = "three"; break;
case 4: _result = "four"; break;
case 5: _result = "five"; break;
case 6: _result = "six"; break;
case 7: _result = "seven"; break;
case 8: _result = "eight"; break;
case 9: _result = "nine"; break;
default: _result = "more than nine"; break;
}
return _result;
}
Starting from JDK 1.7 strings are also accepted for evaluation. If you use a String object as expression, all Value_i constants must be literal strings;
Keywords Related to Exceptions
- throw - used to generate an exception. The throw keyword is followed by a reference to the exception object to be thrown, or by an explicit instantiation of that exception object.
- throws - appears in the declaration of a method that does not handle some types of exception. The throws keyword is followed by a coma-separated list of that exception types (their order is not important).
- try and catch - used if you want to handle locally the exception. The try keyword is attached to a block of statements that is prone to throw exceptions. The catch keyword precedes a block of statements designed to handle a particular exception. A try block may be followed by multiple catch blocks, each designed to handle a particular type of exception (the order of catch blocks is critical: derived exceptions must precede the basic ones).
Example 13:
public class TestClass{
private int value;
public static void main(String[] _args){
try{
TestClass _obj = new TestClass(10);
_obj.someMethod();
}catch(Exception _e){
System.out.println("Exception caught: " + _e.getMessage());
}
try{
TestClass _obj = new TestClass(-10);
_obj.someMethod();
}catch(Exception _e){
System.out.println("Exception caught: " + _e.getMessage());
}
}
public TestClass(int _value) throws Exception{
if(_value < 0){
throw new Exception("The value must not be negative: " + _value);
}
value = _value;
}
public void someMethod(){
System.out.println("Running method for value " + value);
}
}
More about exceptions and how they are handled in Exception Handling.
Operators
The complete list of Java operators:
Precedence | Operator | Description | Associativity |
---|---|---|---|
1 | ()
|
method call | from left to right |
[]
|
acces an array's element | ||
.
|
"dot" operator (acces to a class' member) | ||
2 | ++ --
|
postfix increment and decrement | |
3 | ++ --
|
prefix increment and decrement | from right to left |
+ -
|
unary plus and minus | ||
! ~
|
logic NOT and bitwise NOT | ||
(type) val
|
type cast | ||
new
|
object or array instantiation | ||
4 | * / %
|
Multiplication, division and modulo (remainder) | from left to right |
5 | + -
|
addition and subtraction | |
+
|
string concatenation | ||
6 | << >> >>>
|
leftshift, rightshift, arithmetic righshift (preserves sign) | |
7 | < <=
|
"less than" and "less than or equal" logic comparisons | |
> >=
|
"greater than" and "greater than or equal" logic comparisons | ||
instanceof
|
type comparison | ||
8 | == !=
|
"equal" and "not equal" logic comparisons | |
9 | &
|
bitwise AND | |
10 | ^
|
bitwise XOR (exclusive OR) | |
11 | |
|
bitwise OR (inclusive OR) | |
12 | &&
|
logic AND | |
13 | ||
|
logic OR | |
14 | c ? t : f
|
ternary conditional operator (see #Conditional operator (the ? operator)) | from right to left |
15 | =
|
assignment | |
+= -=
|
compound assignment with addition or subtraction | ||
*= /= %=
|
compound assignment with multiplication, division, modulo | ||
<<= >>= >>>=
|
compound assignment with leftshift, rightshift and arithmetic rightshift | ||
&= ^= |=
|
compound assignment with bitwise AND, XOR, and OR |
Unlike in C++, the operators cannot be overloaded in Java.