Java Syntax; A Program's Lexical Structure: Diferență între versiuni

De la WikiLabs
Jump to navigationJump to search
 
(Nu s-au afișat 46 de versiuni intermediare efectuate de alți 2 utilizatori)
Linia 422: Linia 422:
</syntaxhighlight>
</syntaxhighlight>


==== Cuvintele cheie ''this'' și ''super'' ====
==== ''this'' and ''super'' Keywords ====


Cuvântul cheie '''this''' poate fi folosit în două situații:
Keyword '''this''' can be used in two ways:
* ca apel de constructor din alt constructor;
* as a call to a constructor from another constructor of the same class;
* ca referință la obiectul curent ca instanță a clasei curente.
* as a reference to the current object as an instance of the current class;


Exemplu de utilizare a cuvântului cheie '''this''':
Example if using keyword '''this''':
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
import java.util.ArrayList;
import java.util.ArrayList;
Linia 496: Linia 496:




Cuvântul cheie '''super''' este folosit în două situații (vezi [[Noțiuni avansate de programare obiect-orientată#Ierarhii de clase|ierarhii de clase]]):
Keyword ''super'' can be used in two ways (vezi [[Advanced Notions About Object Oriented Programming#Class Hierarchies|class hierarchies]])
* ca apel al unui constructor al superclasei dintr-un constructor al clasei curente;
* as a call to a super-class constructor from a constructor in the current class;
* ca referință la obiectul curent ca instanță a superclasei.
* as a reference to the current object, as an instance of the super-class.


<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
Linia 587: Linia 587:




<div class="regula"><font color="#ff0000">Regulă:</font> Orice constructor trebuie să înceapă cu un apel de alt constructor folosind '''super''' sau '''this'''. Dacă acesta nu este specificat explicit, atunci implicit este adăugat apelul '''super();''' de către compilator. În această situație pot apărea erori de compilare în cazul în care superclasa nu are constructor fără argumente. În acest caz, apelul constructorului superclasei trebuie facut explicit.</div>
<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">Regulă:</font> Orice apel de constructor folosind '''super''' sau '''this''' trebuie să fie prima expresie din constructorul curent.</div>
<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>


=== Membrii statici ===
=== Static Members ===


Membrii statici ai unei clase reprezintă membrii care nu-și schimbă valoarea sau comportamentul pentru obiecte distincte, adică țin de clasă, și nu de fiecare instanță în parte.
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 613: Linia 613:
{| class="wikitable"
{| class="wikitable"
|- bgcolor="#ddeeff" align="center"
|- bgcolor="#ddeeff" align="center"
!'''Exemplu de program''' !! '''Schema bloc'''
!'''Program Example''' !! '''Block Diagram'''
|- bgcolor="#ddffdd" align="center"
|- bgcolor="#ddffdd" align="center"
|  
|  
Linia 639: Linia 639:
}
}
</syntaxhighlight>  
</syntaxhighlight>  
|| [[Fișier:static_members.png|600px|Exemplu de câmpuri statice în obiecte]]  
|| [[Fișier:static_members.png|600px|Example of static fields in objects]]  
|}
|}




<div class="sfat"><font color="darkgreen">Sfat:</font> Toate metodele care accesează doar câmpuri statice ale clasei curente, sau nici un câmp, se vor declara la rândul lor statice.</div>
<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="sfat"><font color="darkgreen">Sfat:</font> Accesul la membrii statici ai unei clase se face utilizând numele clasei și nu nume de obiecte.</div>
<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">Regulă:</font> Doar câmpurile, metodele și clasele interne pot fi declarate statice, nu și clasele principale.</div>
<div class="regula"><font color="#ff0000">Rule:</font> Only fields, methods and inner-classes can be declared static, and not regular classes.</div>


=== Modificatori speciali pentru membrii ===
=== Special Modifiers ===


==== Modificatori de access ====
==== Access Modifiers ====


{| class="wikitable"
{| class="wikitable"
|- bgcolor="#ddeeff" align="center"
|- bgcolor="#ddeeff" align="center"
!'''Modificator''' !! '''Clasa Curenta''' !! '''Pachet''' !! '''Clasa Derivată''' !! '''În afara pachetului'''
!'''Modifier''' !! '''Current Class''' !! '''Package''' !! '''Derived Class''' !! '''Outside Package'''
|- bgcolor="#ddffdd" align="center"
|- bgcolor="#ddffdd" align="center"
| public || <font color="green">DA</font> || <font color="green">DA</font> || <font color="green">DA</font> || <font color="green">DA</font>
| 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">DA</font> || <font color="green">DA</font> || <font color="green">DA</font> || <font color="red">NU</font>
| 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"
| implicit (fără specificator) || <font color="green">DA</font> || <font color="green">DA</font> || <font color="red">NU</font> || <font color="red">NU</font>
| 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">DA</font> || <font color="red">NU</font> || <font color="red">NU</font> || <font color="red">NU</font>  
| private || <font color="green">Yes</font> || <font color="red">No</font> || <font color="red">No</font> || <font color="red">No</font>  
|}
|}


Linia 754: Linia 754:
</syntaxhighlight>
</syntaxhighlight>


<div class="sfat"><font color="darkgreen">Sfat:</font> În general, câmpurile se declară private (vezi noțiunea de [[Noțiuni avansate de programare obiect-orientată#Încapsulare|încapsulare]]) iar metodele ''getters'' și ''setters'' publice, constructorii publici. Există, desigur, și excepții. </div>


===== 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>


Un element public este accesibil oricărei alte clase.


===== protected =====
===== The <span style="color:maroon">public</span> modifier =====


Un câmp sau metodă protejată este accesibilă claselor din același pachet și claselor derivate din alte pachete.  
A public class or member can be accessed from any other class.


<div class="regula"><font color="#ff0000">Regulă:</font> O clasă principală nu poate avea specificatorul '''protected'''.</div>
===== The <span style="color:maroon">protected</span> modifier =====


===== implicit (fără specificator) =====
A protected field or method is accessible for the classes defined in the same package and for derived classes.


Lipsa unui modificator de access implică faptul că elementul este accesibil clasei curente sau claselor din același pachet, dar nu și claselor din alte pachete.
<div class="regula"><font color="#ff0000">Rule:</font> A regular class can't have the '''protected''' access modifier.</div>


===== private =====
===== The default modifier (not explicit) =====


Un câmp sau metodă privată este accesibilă doar clasei curente.
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.


<div class="regula"><font color="#ff0000">Regulă:</font> O clasă principală nu poate avea specificatorul '''private'''.</div>
===== The <span style="color:maroon">private</span> modifier =====


==== Modificatorul final ====
A '''private''' field or method can only be accessed from the defining class.


Modificatorul '''final''' poate fi aplicat:
<div class="regula"><font color="#ff0000">Rule:</font> A regular class can't have the '''private''' access modifier.</div>
* unei clase - clasa nu poate fi extinsă;
* unei interfețe - interfața nu poate fi extinsă;
* unei metode - metoda nu poate fi suprascrisă;
* unui câmp - acestuia i se poate da o singură valoare care va rămâne constantă pe toată durata existenței obiectului.


Un câmp care este '''static''' și '''final''' este o constantă a clasei.
==== The <span style="color:maroon">final</span> modifier ====


==== Modificatorul abstract ====
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;


O metodă abstractă este o metodă care nu are implementare (doar prototipul).  
A field which is both '''static''' and '''final''' is called a class constant.


<div class="regula"><font color="#ff0000">Regulă:</font> O clasă care conține cel puțin o metodă abstractă trebuie obligatoriu să fie declarată abstractă.</div>
==== The <span style="color:maroon">abstract</span> modifier ====


Any method without body (without implementation) is an abstract method


<div class="regula"><font color="#ff0000">Regulă:</font> O clasă abstractă nu poate fi instanțiată, ci doar extinsă. O clasă extinsă dintr-o clasă abstractă trebuie ori să implementeze toate metodele abstracte, ori să fie și ea declarată abstractă.</div>
<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>


Exemplu:
 
<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 845: Linia 847:
</syntaxhighlight>
</syntaxhighlight>


==== Modificatorul volatile ====
==== The <span style="color:maroon">volatile</span> modifier ====


Un câmp este declarat volatil atunci când este scris de mai mult de un fir de execuție și în acest caz valoarea respectivă va fi încărcată de fiecare dată din memorie și nu se vor încărca în memoria cache.
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.


Câmpurile volatile reprezintă o alternativă la mecanismul de sincronizare, dar poate fi folosit doar în anumite situații în care nu există ''race conditions''. Vezi [[Programare concurentă - fire de execuție (Threads)]].
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]].


==== Modificatorul transient ====
==== The <span style="color:maroon">transient</span> modifier ====


Un câmp declarat '''transient''' nu va fi salvat împreună cu obiectul la serializarea acestuia (vezi [[serializarea obiectelor]]).
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]]).


==== Modificatorul synchronized ====
==== The <span style="color:maroon">synchronized</span> modifier ====


O metodă sincronizată nu este accesibilă decât unui singur ''thread'' la un moment dat. Acest cuvânt cheie poate fi utilizat atât ca modificator pentru o metodă, cât și ca bloc de instrucțiuni în interiorul unei metode:
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 884: Linia 888:
</syntaxhighlight>
</syntaxhighlight>


Mai multe despre ''thread''-uri în capitolul [[Programare concurentă - fire de execuție (Threads)]].
More about ''threads'' and their synchronization in [[Concurrent Programming - Threads]].


==== Modificatorul native ====
==== The <span style="color:maroon">native</span> modifier ====


Există situații în care anumite funcții de sistem nu pot fi apelate în Java, sau alte cazuri în care din Java trebuie apelate funcții dintr-o bibliotecă (.dll sau .so, etc.). În acest caz, din aplicația Java trebuie apelate funcții compilate în limbajul nativ al mașinii, și nu în limbajul mașinii virtuale. Aceste funcții se numesc native, iar mecanismul prin care se pot apela ele din Java se numește [http://docs.oracle.com/javase/7/docs/technotes/guides/jni/index.html JNI] (Java Native Interface).
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.


Mai multe despre cum se implementează metodele native pe [http://java.sun.com/developer/onlineTraining/Programming/JDCBook/jni.html site-ul Oracle].
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">Sfat:</font> Evitați pe cât posibil utilizarea metodelor native deoarece acestea nu sunt portabile.</div>
<div class="sfat"><font color="darkgreen">Advice:</font> Try to avoid using native methods because they are not portable.</div>


=== Constante de clasă ===
=== Class Constants ===


Un câmp declarat în același timp ''static'' și ''final'' se numește constantă a clasei.
A field declared at the same time ''static'' and ''final'' is called a class constant.


=== Extinderea claselor ===
=== Class Extension ===


Limbajul Java suportă moștenirea simplă (vezi [[Noțiuni avansate de programare obiect-orientată#Ierarhii de clase|ierarhii de clase]] și [[Noțiuni avansate de programare obiect-orientată#polimorfism|polimorfism]]). Cuvântul cheie care permite extinderea unei clase este '''extends'''.
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">Regulă:</font> O clasă Java extinde exact o singură altă clasă (dacă nu este specificată, aceasta este clasa ''Object'').</div>
<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>


Exemplu:
Example:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
//---------------------------------------------------
//---------------------------------------------------
Linia 940: Linia 944:
</syntaxhighlight>
</syntaxhighlight>


=== Șabloane (generics) ===
=== 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::


Există situații în care o anumită instanță a unei clase lucrează exclusiv cu un anumit tip de date. În acest caz, dacă clasa este definită ca folosind, de exemplu, date de tip '''Object''', atunci trebuie făcuți pași suplimentari, consumatori de timp, pentru a face up-cast de la '''Object''' la tipul de date (clasa) cu care se lucrează. În plus, aceste operații de up-cast sunt verificate doar la runtime, crescând șansa să apară erori de programare ne-detectabile la compilare. Ca exemplu, vom descrie o clasă '''Stack''' care stochează referințe de tip '''Object''':
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
public class Stack{
public class Stack{
Linia 973: Linia 977:
}
}
</syntaxhighlight>
</syntaxhighlight>
Și o clasă care folosește o stivă exclusiv pentru obiecte de tip '''String''':
<br>
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
public class StringStacker{
public class StringStacker{
Linia 980: Linia 984:
     Stack _stack = new Stack(10);
     Stack _stack = new Stack(10);
     try{
     try{
         // String is automatically down-cast to Object
         // 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 up-cast it as String will give a runtime ClassCastException
         // 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 up-casted to String
         // 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.002: Linia 1.006:
</syntaxhighlight>
</syntaxhighlight>


Această problemă se poate rezolva folosind șabloane. Vom rescrie clasa '''Stack''':
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.034: Linia 1.038:
</syntaxhighlight>
</syntaxhighlight>


Și clasa '''StringStacker''':
<br>
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
public class StringStacker{
public class StringStacker{
Linia 1.064: Linia 1.068:
</syntaxhighlight>
</syntaxhighlight>


Mai multe despre șabloane în [http://docs.oracle.com/javase/tutorial/java/generics/ tutorial-ul Oracle].
More about generics in this [http://docs.oracle.com/javase/tutorial/java/generics/ tutorial] from Oracle.


== Interfața Java ==
== Java Interfaces==


Interfața Java este o structură echivalentă cu o clasă abstractă în care toate metodele sunt abstracte. Spre deosebire de sistemul de moștenire (extindere), unde o clasă poate moșteni o singură altă clasă (moștenire simplă), o clasă poate implementa oricâte interfețe.
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">Sfat:</font> Evitați declararea câmpurilor în interfețe. Pot apărea conflicte când există mai multe interfețe care conțin fiecare un câmp cu același nume.</div>
<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.102: Linia 1.106:




<div class="regula"><font color="#ff0000">Regulă:</font> Dacă o clasă implementează o interfață, atunci obligatoriu ea trebuie să implementeze toate metodele declarate în interfață, sau clasa să fie abstractă și metodele respective să fie declarate abstracte.</div>
<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>


Mai multe despre interfețe în capitolele [[Noțiuni avansate de programare obiect-orientată#Ierarhii de clase|ierarhii de clase]] și [[Noțiuni avansate de programare obiect-orientată#polimorfism|polimorfism]].
More about interfaces in [[Advanced Notions About Object Oriented Programming#Class Hierarchies|Hierarchies]] and [[Advanced Notions About Object Oriented Programming#Polymorphism|Polymorphism]].


== Construcții repetitive ==
== Iterative Constructs ==


=== Expresia for ===
=== The <span style="color:maroon">for</span> statement ===


Expresia '''for''' are două forme posibile. Prima este identică cu cea din C:
The '''for''' statement has two variants. One of them is identical to the C '''for''' statement:
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
for(expresie_initializare; condiție_continuare; expresie_bucla){
for (initializations; condition; updates) {
     //...
     //...
}
}
</syntaxhighlight>
</syntaxhighlight>


* ''expresie_inițializare'' - reprezintă o expresie care se execută o singură dată la intrarea în buclă;
* ''initializations'' - statements that are executed only once, at the beginning of the first iteration;
* ''condiție_continuare'' - reprezintă o condiție care se evaluează la începutul fiecărei iterații; ciclul se continuă dacă condiția e adevărată sau dacă ea lipsește;
* ''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.
* ''expresie buclă'' - reprezintă o expresie care se execută necondiționat la sfărșitul fiecărei iterații.
* ''updates'' - statements that are executed at the end of each iteration;
 
<br>
Exemplu pentru un array:
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>
Exemplu pentru o listă:
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>
Exemplu pentru o buclă infinită:
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>


Al doilea tip de expresie '''for''' este utilizat pentru vectori în felul următor (identic ca funcționare cu primul exemplu):
* ''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.155: Linia 1.170:
</syntaxhighlight>
</syntaxhighlight>


=== Expresia while ===
=== The <span style="color:maroon">while</span> statement ===


Expresia '''while''' este identică cu cea din C:
The '''while''' statement has the same syntax as in C:


<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
while(conditie_continuare){
while (condition){
     //... something
     //... something
}
}
</syntaxhighlight>  
</syntaxhighlight>  


* ''conditie_continuare'' - este o condiție care se evaluează la începutul fiecarei iterații și bucla se încheie dacă aceasta este falsă.  
* ''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 = 20;
int a = 3;
int b = 3;
int b = 13;
while(a != b){
while (a < b) {
     a++;
     a++;
     b--;
     b--;
Linia 1.177: Linia 1.193:
</syntaxhighlight>
</syntaxhighlight>


=== Expresia do - while ===
=== The <span style="color:maroon">do</span>-<span style="color:maroon">while</span> statement ===


Expresia '''do - while''' este identică cu cea din C:
This statement is also written as in C:


<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
do{
do {
     //... something
     //... something
}while(conditie_continuare);
} while (condition);
</syntaxhighlight>  
</syntaxhighlight>  


* ''conditie_continuare'' - este o condiție care se evaluează la sfârșitul fiecarei iterații și bucla se încheie dacă aceasta este falsă.  
* ''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 = 20;
int a = 3;
int b = 3;
int b = 13;
do{
do{
     a++;
     a++;
     b--;
     b--;
     System.out.println(a * b);
     System.out.println(a * b);
}while(a != b);
} 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.


=== Instrucțiunile break & continue ===
=== The <span style="color:maroon">break</span> and <span style="color:maroon">continue</span> statements ===


Instrucțiunile '''break''' și '''continue''' sunt folosite identic cu cele din C și anume pentru a întrerupe un ciclu repetitiv ('''break''') sau a continua cu următoarea iterație ('''continue''').
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''').


Spre exemplu, pentru a căuta primul număr par mai mare ca 100 într-un vector:
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.220: 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>


<div class="regula"><font color="#ff0000">Regulă:</font> '''Break''' și '''continue''' acționează asupra celui mai apropiat (inner) '''for''', '''while''' sau '''do-while''' din metoda curentă.</div>
== Conditional Constructs ==


== Construcții condiționale ==
=== Conditional operator (the <span style="color:maroon">?</span> operator) ===


=== Operatorul condițional (?) ===
The conditional operator is written and works as in C:
 
Operator condițional este identic cu cel din C:


<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
(expresie_de_evaluat ? expresie_adevarat : expresie_fals)
(evaluation_expression ? expression_for_true : expression_for_false)
</syntaxhighlight>  
</syntaxhighlight>  


* ''expresie_de_evaluat'' - reprezintă o expresie booleană (adevărat sau fals) de care depinde valoarea finală a expresiei condiționale;
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''.
* ''expresie_adevarat'' - dacă ''expresie_de_evaluat'' este adevărată, atunci expresia condițională va lua valoarea ''expresie_adevarat'';
<br>
* ''expresie_fals'' - dacă ''expresie_de_evaluat'' este falsă, atunci expresia condițională va lua valoarea ''expresie_fals'';
<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.259: Linia 1.278:
</syntaxhighlight>
</syntaxhighlight>


=== Expresia if - else ===
=== The <span style="color:maroon">if</span> - <span style="color:maroon">else</span> statements ===


Expresia '''if-else''' este expresia condițională standard și este și ea identică cu cea din C:
The '''if''' - '''else''' statements are the standard conditional statements, and their syntax is exactly as in C:


<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
if(conditie){
if (condition) {
     //instructiuni
     // statements_if_true
}else{
} else {
     //instructiuni
     // statements_if_false
}
}
</syntaxhighlight>
</syntaxhighlight>


* ''conditie'' - este o expresie booleană care se evaluează și în funcție de care se execută primul bloc de instrucțiuni (dacă expresia este adevărată) sau al doilea bloc de instrucțiuni (cel de după '''else''', dacă expresia este falsă).
* ''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>
Exemple de blocuri '''if''':
Example 9: returns the maximum number from a pair.
 
<syntaxhighlight lang="java">
<syntaxhighlight lang="java">
public class Utils{
private Utils(){
    // nothing here
}
public static float clamp(float _value, float _lowestValue, float _highestValue){
    float _result = 0;
    if(_value < _lowestValue){
        _result = _lowestValue;
    }else if(_value > _highestValue){
        _result = _highestValue;
    }else{
        _result = _value;
    }
    return _result;
}
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>


=== Expresia switch ===
=== The <span style="color:maroon">switch</span> statement ===


Expresia '''switch''' este identică cu cea din C. Se folosește atunci când în funcție de valoarea unei expresii trebuie executate diferite instrucțiuni:
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(expresie){
switch (expression) {
     case Valoare_1:
     case Value_1:
         // bloc_instructiuni_1
         // branch_1
    break;
        break;
     case Valoare_2:
     case Value_2:
         // bloc_instructiuni_2
         // branch_2
    break;
        break;
     case Valoare_3:
     case Value_3:
         // bloc_instructiuni_3
         // branch_3
    break;
        break;
     default:
     default:
         // bloc_instructiuni_default
         // branch_default
}
}
</syntaxhighlight>  
</syntaxhighlight>  


* ''expresie'' - reprezintă expresia în funcție de valoarea căreia se sare la blocul de instrucțiuni corespunzător;
* ''expression'' - an expression that evaluates to an integer;
* ''Valoare_i'', ''bloc_instructiuni_i'' - dacă expresia ''expresie'' are valoarea ''Valoare_i'', atunci se sare la ''bloc_instrucțiuni_i''; ''Valoare_i'' trebuie să fie constantă.
* 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''' - este un cuvânt cheie care determină blocul la care se sare (''bloc_instructiuni_default'') în cazul în care valoarea expresiei nu corespunde nici unei valori specificate in blocul '''switch'''.  
* 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">Atenție:</font> Odată saltul făcut la unul din blocurile de instrucțiuni, acestea se vor executa în continuare până la întalnirea cuvântului cheie '''break''' (care face ca execuția programului să se reia de la prima instrucțiune după blocul '''switch''') sau a cuvântului cheie '''return''' care încheie execuția metodei. Dacă se omite instrucțiunea '''break''' atunci programul se va executa în continuare, bloc după bloc, începând cu cel la care s-a sărit. </div>
<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.358: 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;


== Cuvinte cheie pentru tratarea excepțiilor ==
== Keywords Related to Exceptions ==
 
O excepție se aruncă folosind cuvântul cheie '''throw'''. O metodă care nu administrează o excepție trebuie să o declare în prototip folosind cuvântul cheie '''throws'''. Un bloc de administrare a excepțiilor este de tip '''try-catch-finally''' sau, din Java 7, '''try-with-resources''':


* '''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.403: Linia 1.427:


</syntaxhighlight>
</syntaxhighlight>
More about exceptions and how they are handled in [[Exception Handling]].


Mai multe despre excepții în capitolul [[tratarea excepțiilor]].
== Operators ==


== Operatori ==
The complete list of Java operators:
 
Aceasta este lista de operatori permiși în limbajul Java. Spre deosebire de C++, în Java nu este permisă supraîncarcarea operatorilor.


{| class="wikitable"
{| class="wikitable"
|-
|-
! style="text-align: center" | Precedență
! style="text-align: center" | Precedence
! style="text-align: center" | Operator
! style="text-align: center" | Operator
! style="text-align: center" | Descriere
! style="text-align: center" | Description
! style="text-align: center" | Asociativitate
! 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" | Apel de metodă
| style="border-bottom-style: none; border-top-style: none" | method call
| style="vertical-align: center" rowspan="4" | De la stânga la dreapta
| 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" | Acces la elemente din vector
| 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" | Acces la membrul unei clase
| 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" | Incrementare și decrementare ca sufix
| 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" | Incrementare și decrementare ca prefix
| style="border-bottom-style: none" | prefix increment and decrement
| style="vertical-align: center" rowspan="5" | De la dreapta la stânga
| 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" | Plus și minus unar
| 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" | NU logic și NU pe biți
| 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" | Type cast
| 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" | Instanțiere de obiecte sau de vectori
| style="border-top-style: none" | object or array instantiation
|-
|-
! 4
! 4
| <code>*</code> <code>/</code> <code>%</code>
| <code>*</code> <code>/</code> <code>%</code>
| Înmuțire, împărțire și modulo (rest)
| Multiplication, division and modulo (remainder)
| style="vertical-align: center" rowspan="13" | De la stânga la dreapta
| 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;" | Adunare și scădere
| 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" | Concatenare de stringuri
| style="border-top-style: none" | string concatenation
|-
|-
! 6
! 6
| <code>&lt;&lt;</code> <code>&gt;&gt;</code> <code>&gt;&gt;&gt;</code>
| <code>&lt;&lt;</code> <code>&gt;&gt;</code> <code>&gt;&gt;&gt;</code>
| Shift pe biți la stânga, shift pe biți la dreapta cu semn și fără semn
| leftshift, rightshift, arithmetic righshift (preserves sign)
|-
|-
! rowspan=3| 7
! rowspan=3| 7
| style="border-bottom-style: none;" | <code>&lt;</code> <code>&lt;=</code>
| style="border-bottom-style: none;" | <code>&lt;</code> <code>&lt;=</code>
| style="border-bottom-style: none;" | Operator de comparare "mai mic decât" și "mai mic sau egal"
| style="border-bottom-style: none;" | "less than" and "less than or equal" logic comparisons
|-
|-
| style="border-bottom-style: none; border-top-style: none" | <code>&gt;</code> <code>&gt;=</code>
| style="border-bottom-style: none; border-top-style: none" | <code>&gt;</code> <code>&gt;=</code>
| style="border-bottom-style: none; border-top-style: none" | Operator de comparare "mai mare ca" și "mai mare sau egal"
| 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" | Comparare de tip
| style="border-top-style: none" | type comparison
|-
|-
! 8
! 8
| <code>==</code> <code>!=</code>
| <code>==</code> <code>!=</code>
| Operator de comparare "egal cu" sau "diferit de"
| "equal" and "not equal" logic comparisons
|-
|-
! 9
! 9
| <code>&amp;</code>
| <code>&amp;</code>
| AND (și) pe biți
| bitwise AND
|-
|-
! 10
! 10
| <code>^</code>
| <code>^</code>
| XOR (sau exclusiv) pe biți
| bitwise XOR (exclusive OR)
|-
|-
! 11
! 11
| <code><nowiki>|</nowiki></code>
| <code><nowiki>|</nowiki></code>
| OR (sau) pe biți
| bitwise OR (inclusive OR)
|-
|-
! 12
! 12
| <code>&amp;&amp;</code>
| <code>&amp;&amp;</code>
| AND (și) logic
| logic AND
|-
|-
! 13
! 13
| <code><nowiki>||</nowiki></code>
| <code><nowiki>||</nowiki></code>
| OR (sau) logic
| logic OR
|-
|-
! 14
! 14
| <code>''c'' ? ''t'' : ''f''</code>
| <code>''c'' ? ''t'' : ''f''</code>
| Operator ternar condițional (vezi [[#Operatorul condițional (?)]])
| ternary conditional operator (see [[#Conditional operator (the ? operator)]])
| style="vertical-align: center" rowspan="6" | De la dreapta la stânga
| 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" | Asignare simplă
| 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" | Asignare cu sumă sau diferență
| 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" | Asignare cu produs, cât sau rest
| 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>&lt;&lt;=</code> <code>&gt;&gt;=</code> <code>&gt;&gt;&gt;=</code>
| style="border-bottom-style: none; border-top-style: none" | <code>&lt;&lt;=</code> <code>&gt;&gt;=</code> <code>&gt;&gt;&gt;=</code>
| style="border-bottom-style: none; border-top-style: none" | Asignare cu shift la stânga, la dreapta, sau la dreapta fără semn
| style="border-bottom-style: none; border-top-style: none" | compound assignment with leftshift, rightshift and arithmetic rightshift
|-
|-
| style="border-top-style: none" | <code>&amp;=</code> <code>^=</code> <code><nowiki>|</nowiki>=</code>
| style="border-top-style: none" | <code>&amp;=</code> <code>^=</code> <code><nowiki>|</nowiki>=</code>
| style="border-top-style: none" | Asignare cu AND, XOR, sau OR pe biți
| style="border-top-style: none" | compound assignment with bitwise AND, XOR, and OR
|}
|}


== Resurse ==
Unlike in C++, the operators cannot be overloaded in Java.
 
== Web Resources ==


# [http://docs.oracle.com/javase/specs/jls/se7/jls7.pdf Specificația limbajului Java, v.7]
# [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 Specificația mașinii virtuale Java, v.7]
# [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 Sintaxa Java - Wikipedia]
# [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.

Rule: A Java file (.java) contains exactly one interface or regular class and zero or more inner classes.


Advice: Avoid using inner-classes. These can be implemented as regular classes with the appropriate access modifiers.

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.

Rule: Objects, including arrays, are created with the new operator.

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:

Object obj;
new Object();
obj = 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.

Program example Diagram
//...
Object _obj1 = new Object(); //we name this object ID1
Object _obj2 = new Object(); //we name this object ID2
Object _obj3 = _obj1;        //reference to the same object ID1
Object _obj4 = null;         //does not reffer any object
Object _obj5;                //initialized implicitly with null
//...
Reference type variables example

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;


Rule: 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.


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.

Program example Diagram
int[] _array1;
_array1 = new int[5];
_array1[3] = 10;
Object[] _array2 = new Object[10];
_array2[2] = new Object();
int[][] _array3 = new int[5][3];
_array3[1][1] = 5;
char[][][] _array4;
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.

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.

Rule:Nothing can exist outside a class or interface, except for package and import directives.


Rule: Any file can contain only one regular class.

The keyword that define a class is class, being always followed by the class name and its implementation, between curly brackets.


Convention: Any class or interface name starts with an uppercase letter.


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.

Rule: The operator used to access a class member (field or method) is ".".

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 ".".

Rule: A Java package can contain classes, interfaces and other packages.

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.

Rule: 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.


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.

Convention: Field names start with a lowercase letter.


Convention: In order to distinguish easily between fields and local variables, the latter ones will have names starting with the underscore character ("_").


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.

Program example Diagram
class MainClass{

public static void main(String[] _args){
    SomeClass _obj1 = new SomeClass(); //we name this object ID1
    SomeClass _obj2 = new SomeClass(); //we name this object ID2
    _obj1.somePrimitiveField = 5;
    _obj2.somePrimitiveField = 10;
    System.out.println("Field somePrimitiveField from _obj1 is = " + 
        _obj1.somePrimitiveField + " and from _obj2 is = " +
        _obj2.somePrimitiveField);
    if(_obj1.somePrimitiveField == _obj2.somePrimitiveField){
        System.out.println("They are equal!");
    }else{
        System.out.println("They are NOT equal!");
    }
}

}
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 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).
Convention: With the exception of constructors, the method names begin with a lowercase letter.


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.

Convention: In order to distinguish easily between fields and local variables, the latter ones will have names starting with the underscore character ("_").

Class Constructors

Constructors are special methods of a class that are called automatically when an object is instantiated. Constructors have two specific properties:

Rule: Constructors have the exact same name with the class they belong to.


Rule: Constructors don't have a return type (not even void).

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;
}

}


Rule: 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.


Rule: When instantiating an object (but not arrays), after the new operator, the next element is always a constructor call.

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.
     */
}

}


Rule: 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.


Rule: Any constructor call done by using super or this must be the first statement in a constructor.

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;
 
}


Program Example Block Diagram
class MainClass{

public static void main(String[] _args){
    SomeClass _obj1 = new SomeClass(); //notam acest obiect cu ID1
    SomeClass _obj2 = new SomeClass(); //notam acest obiect cu ID2
    _obj1.someStaticField = 5;
    _obj2.someStaticField = 10;
    System.out.println("Field someStaticField from _obj1 is = " + 
        _obj1.someStaticField + " and from _obj2 is = " +
        _obj2.someStaticField);
    if(_obj1.someStaticField == _obj2.someStaticField){
        System.out.println("They are equal!");
    }else{
        System.out.println("They are NOT equal!");
    }

    System.out.println("Proper way of accessing static members: " +
        SomeClass.someStaticField);
}

}
Example of static fields in objects


Advice: All methods that only access static fields of the class or no fields at all, should be also declared static.


Convention: Access to static members of a class is done by using the class name, not object references.


Rule: Only fields, methods and inner-classes can be declared static, and not regular classes.

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.
     */
}

}


Advice: Usually, fields are declared private (see encapsulation), and getters and setters methods and constructors are declared public. There are, of course, exceptions.


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.

Rule: A regular class can't have the protected access modifier.
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.

Rule: A regular class can't have the private access modifier.

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

Rule:If a class contains at least one abstarct method, that class must be declared abstract, too.


Rule: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.

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.

Advice: Try to avoid using native methods because they are not portable.

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.

Rule: A Java class extends exactly one other class (if this is not specified, then the base class is Object).

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.

Hint: Avoid fields in interfaces. Conflicts may appear when a class implements two interfaces with the same name for some constants.


//---------------------------------------------------
//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
}

}
//---------------------------------------------------


Rule: 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.

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.

Rule: break and continue statements affect only the most inner for, while or do-while loop in which they reside.

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.


Be careful: 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.


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.

Web Resources

  1. The Java Language Specifications, v.7
  2. The Java Virtual Machine Specifications, v.7 (advanced topic)
  3. Java Syntax - Wikipedia