Sunteți pe pagina 1din 158

Intro

Workbook - Java from scratch


Introducere
Caiet de lucru - Java de la zero

Welcome to the fascinating world of Java. This Handbook focuses on several basic and essential

aspects so that after having familiarized with it you can successfully write simple programs and

express simple logics in the Java code. This does not mean that the material is only addressed

superficially. On the contrary, each issue is explained in detail and exemplified. In addition, each

chapter is concluded with exercises, and the final part of the Handbook includes some assignments

for you to be done. However, due to the volume of the Handbook, it does not exhaust the subject.

Bine ați venit în lumea fascinantă a Java. Acest manual se concentrează pe


câteva aspecte de bază și esențiale, astfel încât, după ce v-ați familiarizat cu el,
puteți scrie cu succes programe simple și puteți exprima logici simple în codul
Java. Acest lucru nu înseamnă că materialul este abordat doar superficial.
Dimpotrivă, fiecare problemă este explicată în detaliu și exemplificată. În plus,
fiecare capitol este încheiat cu exerciții, iar partea finală a Manualului include
câteva teme pe care trebuie să le faci. Cu toate acestea, din cauza volumului
Manualului, acesta nu epuizează subiectul.
I encourage you to read “from beginning to end”. While reading, it is advisable to run code snippets
on your own. Each chapter is concluded with a Summary, that is, a revision and reminder of
information in a nutshell as well as additional conclusions. Exercises are meant for independent
work, experimenting, verification and testing the codes. Assignments in many cases involve the
knowledge from several chapters and they should be executed at the end, after reading the entire
Handbook.

Vă încurajez să citiți „de la început


In many places additional markings have been applied.

până la sfârșit”. În timpul citirii, este recomandabil să rulați singur fragmente de


cod. Fiecare capitol este încheiat cu un Rezumat, adică o revizuire și o
reamintire a informațiilor pe scurt, precum și concluzii suplimentare. Exercițiile
sunt menite pentru munca independentă, experimentarea, verificarea și testarea
codurilor. Sarcinile presupun în multe cazuri cunoștințele din mai multe capitole
și trebuie executate la final, după citirea întregului Manual.
În multe locuri au fost aplicate marcaje suplimentare.

1
Note Notă
This icon indicates additional information (usually to increase the knowledge) or a reference to a

subject beyond the scope of this Handbook. Această pictogramă indică informații
suplimentare (de obicei pentru a spori cunoștințele) sau o referire la un subiect
care nu intră în domeniul de aplicare al acestui manual.
Tip Bacsis

This icon indicates advice, explanation or a good practice. Această pictogramă indică un

sfat, o explicație sau o bună practică.

Important
This icon is meant to highlight and emphasize very important information that should be memorized.
The individual chapters of the Handbook provide a brief introduction to the most important issues of
Java language.

Această pictogramă este menită să evidențieze și să sublinieze informații foarte


importante care ar trebui memorate.
Capitolele individuale ale Manualului oferă o scurtă introducere la cele mai
importante probleme ale limbajului Java.
 Introduction

In this chapter you will learn a short history of the language as well as its basic design

goals and concepts. You will get to know how to set up your work environment and then you

Introducere
will write your first program in Java.

 În acest capitol veți învăța o scurtă istorie a limbii, precum și obiectivele


și conceptele sale de bază de proiectare. Veți învăța cum să vă configurați
mediul de lucru și apoi veți scrie primul program în Java.
 Types of data

This chapter fairly thoroughly discusses the available data types. You will learn about both

primitive and object-oriented types and the conversion mechanisms between them. Tipuri
de date
 Acest capitol discută destul de amănunțit tipurile de date disponibile. Veți
învăța atât despre tipurile primitive, cât și despre cele orientate pe obiect
și despre mecanismele de conversie dintre acestea.
 Operators

After mastering the data types, it is time to perform operations on them. In this chapter you

will learn about mathematical and logic operations and comparisons. Operatori

2
 După stăpânirea tipurilor de date, este timpul să efectuați operațiuni
asupra acestora. În acest capitol veți afla despre operații și comparații
matematice și logice.

 Conditional statements

Computer programs are a series of statements, but very often performing a given operation

Declarații condiționale
depends on a certain condition.

 Programele de calculator sunt o serie de instrucțiuni, dar de foarte multe


ori efectuarea unei anumite operații depinde de o anumită condiție.
 Loops

Just like in your everyday life, also in programming certain operations must be performed

many times. You will learn how to use various types of loops and how to write an infinite

loop.Bucle
 La fel ca în viața de zi cu zi, și în programare anumite operații trebuie
efectuate de mai multe ori. Veți învăța cum să utilizați diferite tipuri de
bucle și cum să scrieți o buclă infinită.
 Arrays

When you have many things of the same or similar kind, you often want to keep them

together, close one to another. In programming, you can use arrays for this purpose, which

Matrice
allow you to store multiple data of the same type in one place.

 Când aveți multe lucruri de același fel sau asemănător, de multe ori doriți
să le țineți împreună, aproape una de alta. În programare, puteți utiliza
matrice în acest scop, care vă permit să stocați mai multe date de același
tip într-un singur loc.
 Object-oriented programming

Java is an object-oriented language. This chapter describes classes and objects. You will

learn to define classes, create objects of these classes and perform operations on them.

Programare orientată pe obiecte


 Java este un limbaj orientat pe obiecte. Acest capitol descrie clase și
obiecte. Veți învăța să definiți clase, să creați obiecte ale acestor clase și
să efectuați operații asupra lor.
Enjoy your reading!

Lectură plăcută!

3
A brief history of Java
O scurtă istorie a Java
The history of Java begins in 1991, when a group of engineers from the Sun company under the
leadership of James Gosling and Patrick Naughton started to work on the project that got a code
name Green. The team aimed at developing a possibly " light" programming language that would be
independent of the hardware platform. Initially, the language was to be applied in cable TV tuners.

The engineers derived from Unix circles, therefore they based their new language on C+
+ and Smalltalk. Thanks to this, they created an object-oriented, and not a procedural language.

At the initial stage of the project, the language was called Oak- Object Application Kernel.
Reportedly, the name was chosen by James Gosling because of the view of the oak tree outside the
window of his office. It turned out that a language with this name already existed, and a decision
was made to change the name to Java (which is a coffee bush variety), which turned out to be a hit.

The first version of Java was launched in early 1996. In the next version (1.1) many features were
added and improved, but the language still had many restrictions.

Then from the version to the version new functionalities were introduced to Java, yet retaining its
backward compatibility.

Since 2010, Java has been developed by Oracle. O scurtă istorie a Java

Istoria Java începe în 1991, când un grup de ingineri de la compania Sun sub
conducerea lui James Gosling și Patrick Naughton a început să lucreze la
proiectul care a primit un nume de cod Green. Echipa și-a propus să dezvolte un
limbaj de programare posibil „ușor”, care să fie independent de platforma
hardware. Inițial, limbajul urma să fie aplicat în tunerele TV prin cablu.
Inginerii au derivat din cercurile Unix, prin urmare și-au bazat noul limbaj pe
C++ și Smalltalk. Datorită acestui fapt, au creat un limbaj orientat pe obiecte, nu
procedural.
La etapa inițială a proiectului, limbajul a fost numit Oak-Object Application
Kernel. Se pare că numele a fost ales de James Gosling din cauza vederii
stejarului din afara ferestrei biroului său. S-a dovedit că o limbă cu acest nume
exista deja și s-a luat decizia de a schimba numele în Java (care este un soi de
tufiș de cafea), care s-a dovedit a fi un succes.
Prima versiune de Java a fost lansată la începutul anului 1996. În următoarea
versiune (1.1) au fost adăugate și îmbunătățite multe caracteristici, dar limbajul
avea încă multe restricții.

4
Apoi, de la versiune la versiune, au fost introduse noi funcționalități în Java,
păstrându-și totuși compatibilitatea cu versiunea anterioară.
Din 2010, Java a fost dezvoltat de Oracle.

Language assumptions
In May 1996, James Gosling and Henry McGilton published "A White Paper" where they described,

among other things, the assumptions and goals of the language. The basic assumptions were as

Ipoteze de limbaj
follows:

În mai 1996, James Gosling și Henry McGilton au publicat „A White Paper” în


care au descris, printre altele, ipotezele și scopurile limbii. Ipotezele de bază au
fost următoarele:

 Simplicity

Unlike other programming languages (e.g. C++), Java has been deprived of many rarely used or

difficult and erroneous structures and functions. Also, it is relatively easy to learn this language.

Simplitate
Spre deosebire de alte limbaje de programare (de exemplu, C++), Java a fost
lipsit de multe structuri și funcții rar utilizate sau dificile și eronate. De
asemenea, este relativ ușor să înveți această limbă
 Object-orientation

Java is an object-oriented language where data, or objects, play the most important role. They

have identity, status and behavior. Orientare obiect


Java este un limbaj orientat pe obiecte în care datele, sau obiectele, joacă cel
mai important rol. Au identitate, statut și comportament
 Reliability

A Java compiler can detect many errors that in other languages would not occur until the

Fiabilitate
application was launched.

Un compilator Java poate detecta multe erori care în alte limbi nu ar apărea până
la lansarea aplicației.

 Networking

5
Java provides a broad library of functionalities that enable communication through many popular

Rețele
network protocols.

Java oferă o bibliotecă largă de funcționalități care permit comunicarea prin


multe protocoale de rețea populare.

 Architecture Neutral and Portable

A compiled Java code can be run on many processors, regardless of their architecture. Thanks to

(in simple terms) the Java Virtual Machine, it is translated into a machine code on the fly. In

addition, it is platform-independent, which means you can focus on programming without worrying

about the specific mechanisms of a particular operating system. Arhitectură neutră și


portabilă
Un cod Java compilat poate fi rulat pe mai multe procesoare, indiferent de
arhitectura acestora. Datorită (în termeni simpli) mașinii virtuale Java, aceasta
este tradusă într-un cod de mașină din mers. În plus, este independent de
platformă, ceea ce înseamnă că vă puteți concentra pe programare fără să vă
faceți griji cu privire la mecanismele specifice ale unui anumit sistem de
operare.

 High Performance

Despite the need to compile and then interpret a byte code, programs written in Java can be very

efficient. Compilers feature optimizing mechanisms, e.g. they can optimize the most frequently

executed code snippets in terms of speed or eliminate the number of function calls ( inlining).

Performanta ridicata
În ciuda necesității de a compila și apoi de a interpreta un cod octet, programele
scrise în Java pot fi foarte eficiente. Compilatoarele dispun de mecanisme de
optimizare, de ex. pot optimiza fragmentele de cod executate cel mai frecvent
din punct de vedere al vitezei sau pot elimina numărul de apeluri de funcții
(inlining).

 Multithreading Capability

Concurrent and parallel programming is relatively difficult. Java provides an accessible abstraction

that covers complex constructions, yet allows you to write a code to be run on various processors

(cores). Capacitate multithreading

6
Programarea simultană și paralelă este relativ dificilă. Java oferă o abstractizare
accesibilă care acoperă construcții complexe, dar vă permite să scrieți un cod
care să fie rulat pe diferite procesoare (nuclee).

Basic concepts Noțiuni de bază


While learning Java, you will encounter many names and abbreviations. Below you fill find the ones

În timp ce
that you should know from the very beginning of your adventure with the language.

înveți Java, vei întâlni multe nume și abrevieri. Mai jos le găsești pe cele pe care
ar trebui să le cunoști de la începutul aventurii tale cu limba.
 Java SE - Java Standard Edition, a platform to be used on standard computers and in simple
server applications.
 Java EE - Java Enterprise Edition, a platform designed for complex and expanded server
applications.
 Java ME - Java Micro Edition, a platform for applications on mobile phones, mobile devices
and small devices.
 IDE - Integraed Development Environment, integrated development environment; it is used to
develop, test, build and run programs.
 JVM - Java Virtual Machine, executes a Java byte code by interpreting/compiling into
machine code.
 Source code - A record of a computer program using a specific programming language that
describes the operations to be performed by the computer on collected or received data. The
source code is the result of a programmer's work and makes it possible to express the
structure and operation of a computer program in a human-readable form. In Java, the source
code is included in text files with a .java extension.
 Compiler - A program that converts a source code into a code written in other language. In
addition, a compiler is to find lexical and semantic errors and optimize the code. In Java, a
compiler processes the code stored in files with a .java extension and places the result of the
operation in files with a .class extension.

Bytecode - The outcome of compiling a program written in Java. This code is understandable for

the Java runtime environment (JVM).

• Java SE - Java Standard Edition, o platformă care poate fi utilizată pe


computere standard și în aplicații server simple.
• Java EE - Java Enterprise Edition, o platformă concepută pentru aplicații de
server complexe și extinse.
• Java ME - Java Micro Edition, o platformă pentru aplicații pe telefoane
mobile, dispozitive mobile și dispozitive mici.

7
• IDE - Integraed Development Environment, mediu de dezvoltare integrat; este
folosit pentru a dezvolta, testa, construi și rula programe.
• JVM - Java Virtual Machine, execută un cod de octet Java prin
interpretarea/compilarea în codul mașinii.
• Cod sursă - O înregistrare a unui program de calculator folosind un limbaj de
programare specific care descrie operațiunile care trebuie efectuate de computer
cu privire la datele colectate sau primite. Codul sursă este rezultatul muncii unui
programator și face posibilă exprimarea structurii și funcționării unui program
de calculator într-o formă care poate fi citită de om. În Java, codul sursă este
inclus în fișierele text cu extensia .java.
• Compilator - Un program care convertește un cod sursă într-un cod scris în
altă limbă. În plus, un compilator trebuie să găsească erori lexicale și semantice
și să optimizeze codul. În Java, un compilator procesează codul stocat în fișiere
cu extensia .java și plasează rezultatul operației în fișiere cu extensia .class.
• Bytecode - Rezultatul compilării unui program scris în Java. Acest cod este de
înțeles pentru mediul de rulare Java (JVM).

Working Environment Mediu de lucru

To execute exercises and assignments, you will need the following: Pentru a executa exerciții
și sarcini, veți avea nevoie de următoarele:

 JDK (Java Development Kit) - tools necessary for programming in Java

 IDE (Integrated Development Environment) - the environment in which writing a code in the

Java language is possible

 JDK (Java Development Kit) - instrumente necesare pentru programarea


în Java
• IDE (Integrated Development Environment) - mediul în care este posibilă
scrierea unui cod în limbajul Java

Note: If for any reasons you do not want to or cannot install the above applications or during the
installation unexpected problems occurred, you can use one of the tools available online, such

8
as OnlineGDB. It is sufficient for the performance of exercises and assignments from this
Handbook.

In order to install Java and IntelliJ IDEA IDE please go to this section and choose appropriate

guide depending on your operating system (Windows, Linux or MacOS). Please note that installation

guide contains information how to install all necessary software that will be used during the


course. For now, you don't need anything else than Java and Intellij IDEA.

Notă: Dacă din orice motiv nu doriți sau nu puteți instala aplicațiile de mai sus
sau în timpul instalării au apărut probleme neașteptate, puteți utiliza unul dintre
instrumentele disponibile online, cum ar fi OnlineGDB. Este suficient pentru
efectuarea exercițiilor și a sarcinilor din acest Manual.
Pentru a instala Java și IntelliJ IDEA IDE, vă rugăm să accesați această secțiune
și să alegeți ghidul potrivit în funcție de sistemul dvs. de operare (Windows,
Linux sau MacOS). Vă rugăm să rețineți că ghidul de instalare conține
informații despre cum să instalați tot software-ul necesar care va fi folosit în
timpul cursului. Deocamdată, nu aveți nevoie de nimic altceva decât Java și
Intellij IDEA.
Creating a project Crearea unui proiect
When you have installed Java and IntelliJ IDEA, it is time to create a project in which you will locate

Java programs. After you run IntelliJ IDEA, the Welcome to IntelliJ IDEA window will appear with

După ce ați instalat Java și IntelliJ IDEA, este timpul


several options to choose from.

să creați un proiect în care veți localiza programe Java. După ce rulați IntelliJ
IDEA, va apărea fereastra Bun venit la IntelliJ IDEA cu mai multe opțiuni din
care să alegeți.

 select New Project

 on the next screen choose Java project of left side of the window. In the project SDK choose
installed Java version and click Next.

 in case no Java (i.e. no SDK) is available, click the arrow on the SDK select list and
choose Download SDK...

Choose Java version to install (11 or 17 in case it is available) and choose any vendor from the list
(e.g. AdoptOpenJDK) and click Download.

 on the next screen click Next

 give a name to the project (e.g. sda-java-prework) and choose directory where project will be
stored. Click Finish. An empty project should be created.

9
You should be ready to create your first program!

• selectați Proiect nou


• pe ecranul următor alege proiectul Java din partea stângă a ferestrei. În SDK-ul
proiectului, alegeți versiunea Java instalată și faceți clic pe Următorul.
• în cazul în care nu este disponibil Java (adică nici un SDK), faceți clic pe
săgeata din lista de selecție SDK și alegeți Descărcare SDK...
Alegeți versiunea Java de instalat (11 sau 17 în cazul în care este disponibilă) și
alegeți orice furnizor din listă (de exemplu, AdoptOpenJDK) și faceți clic pe
Descărcare.
• pe ecranul următor, faceți clic pe Următorul
• dați un nume proiectului (de exemplu, sda-java-prework) și alegeți directorul
în care va fi stocat proiectul. Faceți clic pe Terminare. Ar trebui creat un proiect
gol.
• Ar trebui să fiți gata să vă creați primul program!

Your first program Primul tău program


Traditionally, the exemplary text "Hello, world!" is presented as the first program. Its task is to
display the following text on the screen:
Hello, World!

Below, the (source) code of this program saved in Java is presented.


// MyFirstJavaProgram.java

public class MyFirstJavaProgram { // (1)

public static void main(String[] args) { // (2)


System.out.println("Hello, World!"); // (3)
}
}

Does it look complicated? Below we will discuss step by step what is happening in the individual
lines.

În mod tradițional, textul exemplar „Bună, lume!” este prezentat ca primul


program. Sarcina sa este de a afișa următorul text pe ecran:
Salut Lume!
Mai jos, este prezentat codul (sursă) al acestui program salvat în Java.
// MyFirstJavaProgram.java

clasă publică MyFirstJavaProgram { // (1)

10
public static void main(String[] args) {// (2)
System.out.println("Bună ziua, lume!"); // (3)
}
}
Pare complicat? Mai jos vom discuta pas cu pas ce se întâmplă în rândurile
individuale.

(1) MyFirstJavaProgram is the name of our program. Besides, it is also the name of the file where the

program, i.e. MyFirstJavaProgram.java (a file with .java extension), is located. At the moment we will

skip the explanation of the words public and class; I will only mention that MyFirstJavaProgram is also

the name of a class. Classes are basic entities in Java, and each program consists of one or more

• (1) MyFirstJavaProgram este


classes (later on, you will learn more on what the class is).

numele programului nostru. În plus, este și numele fișierului în care se află


programul, adică MyFirstJavaProgram.java (un fișier cu extensia .java).
Momentan vom sări peste explicația cuvintelor public și clasă; Voi menționa
doar că MyFirstJavaProgram este și numele unei clase. Clasele sunt entități de
bază în Java și fiecare program constă dintr-una sau mai multe clase (mai târziu,
veți afla mai multe despre ce este clasa).

(2) public static void main(String[] args) - this fragment has a special "power". It indicates the

declaration of the main method that is responsible for running the entire program; everything starts

here. For now, treat this line as a mantra. In our future programs, in this very method we will be

(2) public static void main(String[] args) -


placing the Java code that we are going to run.

acest fragment are o „putere” specială. Indică declararea metodei principale care
este responsabilă pentru rularea întregului program; totul începe aici.
Deocamdată, tratați această linie ca pe o mantră. În programele noastre viitoare,
chiar în această metodă vom plasa codul Java pe care îl vom rula.
(3) System.out.println() is responsible for writing the text on the screen, which in this case is: Hello,

World!.3) System.out.println() este responsabil pentru scrierea textului pe ecran,


care în acest caz este: Hello, World!.
Note: CamelCase notation — if a name consists of several words, we type it without space, and

each word begins with a capital letter, for instance MyFirstJavaProgram, AccountService or

BankAccount. It has also been adopted that all elements such as classes, methods or variables are

named in English. Notă: Notația CamelCase — dacă un nume este format din mai

11
multe cuvinte, îl introducem fără spațiu, iar fiecare cuvânt începe cu o literă
majusculă, de exemplu MyFirstJavaProgram, AccountService sau
BankAccount. De asemenea, s-a adoptat ca toate elementele precum clasele,
metodele sau variabilele să fie denumite în limba engleză.

Let us go back to our example again.


// MyFirstJavaProgram.java

public class MyFirstJavaProgram { // (1)

public static void main(String[] args) { // (2)


System.out.println("Hello, World!"); // (3)
} // (4)
} // (5)

Să ne întoarcem din nou la exemplul nostru.


// MyFirstJavaProgram.java

clasă publică MyFirstJavaProgram { // (1)

public static void main(String[] args) {// (2)


System.out.println("Bună ziua, lume!"); // (3)
} // (4)
} // (5)
o We already know that MyFirstJavaProgram is the name of the file and class that we have

created. Please notice the opening brace ({) that defines the beginning of the class

(1) Știm deja că


body. The end of the class body is defined by the final brace ( }).

MyFirstJavaProgram este numele fișierului și clasei pe care le-am


creat. Vă rugăm să observați acolada de deschidere ({) care
definește începutul corpului clasei. Sfârșitul corpului clasei este
definit de acolada finală (}).

o Notice the opening brace at the end of the line—it defines the beginning of

(2) Observați acolada de deschidere de la sfârșitul


the method body.

liniei — definește începutul corpului metodei.


o System.out.println() is an instruction. Is means invoking the println() method on the

out object (more information on this topic can be found in further part of this

Handbook). The println() method displays the content included between the quotes.

Please also note the semicolon at the end of the instruction. • (3) System.out.
12
println() este o instrucțiune. Este înseamnă invocarea metodei
println() pe obiectul out (mai multe informații despre acest subiect
pot fi găsite în partea ulterioară a acestui manual). Metoda println()
afișează conținutul inclus între ghilimele. Vă rugăm să rețineți și
punctul și virgulă de la sfârșitul instrucțiunii.

 (4) The brace ending the main method body (4) Acolada care se termină cu corpul
principal al metodei
 (5) The brace ending the MyFirstJavaProgram class body (5) Acolade care termină corpul
clasei MyFirstJavaProgram
Note: Please notice the way of formatting the code and indentation that are used for fast
identification of blocks and analysis of control flow. They have no meaning for the computer, but
they make the program more legible for the programmer.

Notă: Vă rugăm să observați modul de formatare a codului și a indentării care


sunt utilizate pentru identificarea rapidă a blocurilor și analiza fluxului de
control. Nu au nicio semnificație pentru computer, dar fac programul mai lizibil
pentru programator.

 Working with IntelliJ IDEA Lucrul cu IntelliJ IDEA


 Now let us see how to save and run this program in a Java environment. We will use the

Acum să vedem cum să salvăm și să rulăm acest


IntelliJ IDEA program.

program într-un mediu Java. Vom folosi programul IntelliJ IDEA.


 faceți
click the src directory and then right-click to select New › Java Class from the menu
clic pe directorul src și apoi faceți clic dreapta pentru a selecta New › Java
Class din meniu
 in the Name field, enter MyFirstJavaProgram (without .java) and click OK în câmpul Name,
introduceți MyFirstJavaProgram (fără .java) și faceți clic pe OK
 rewrite the above code snippet rescrieți fragmentul de cod de mai sus

13
Then run the program using one of the following methods: Apoi rulați programul folosind
una dintre următoarele metode:
 Select Run › Run... from the top menu and select the MyFirstJavaProgram. You can also use a
Selectați Run › Run... din meniul de sus și
keyboard shortcut: Alt + Shift + F10
selectați MyFirstJavaProgram. De asemenea, puteți utiliza o comandă rapidă
de la tastatură: Alt + Shift + F10
Click the green triangle located on the left at the height of public class MyFirstJavaProgram or public static

void main(String[] args) • Faceți clic pe triunghiul


and select Run MyFirstJavaProgram.main()

verde situat în stânga la înălțimea clasei publice MyFirstJavaProgram sau public


static void main(String[] args) și selectați Run MyFirstJavaProgram.main()
In the window below the code, you should see the text Hello, World!

În fereastra de sub cod, ar trebui să vedeți textul Hello, World!

14
Note: In order to improve the efficiency of your work, it is worth mastering
at least basic keyboard shortcuts. I encourage you to download the full list
of keyboard shortcuts from IntelliJ IDEA site. You can also use Key Promoter
X plugin to learn and master keyboard shortcuts. More information can be
found here. Notă: Pentru a îmbunătăți eficiența muncii dvs., merită să stăpâniți
cel puțin comenzile rapide de la tastatură de bază. Vă încurajez să descărcați
lista completă a comenzilor rapide de la tastatură de pe site-ul IntelliJ IDEA. De
asemenea, puteți utiliza pluginul Key Promoter X pentru a învăța și a stăpâni
comenzile rapide de la tastatură. Mai multe informații pot fi găsite aici.

Shortcut Action

15
Double Shift Search Everywhere
Căutare cu Quickly find any file, action, symbol, tool window, or setting in IntelliJ IDEA, in your project, and in the current Git repository.
două ture Găsiți rapid orice fișier, acțiune, simbol, fereastră de instrumente sau setare în
peste tot IntelliJ IDEA, în proiectul dvs. și în depozitul Git curent.

Ctrl+Shift+A Find Action

Găsiți o comandă și executați-


Find a command and execute it, open a tool window, or search for a setting.

o, deschideți o fereastră de instrumente sau căutați o setare.

Alt+Enter Show Context Actions

Quick-fixes for highlighted errors and warnings, intention actions for improving and optimizing your code. Afișați
acțiuni de context
Remedieri rapide pentru erorile și avertismentele evidențiate, acțiuni de
intenție pentru îmbunătățirea și optimizarea codului.

F2 Navigate between code issues


Shift+F2 Navigați între problemele de cod
Jump to the next or previous highlighted error.

Treceți la eroarea evidențiată următoare sau anterioară.


Ctrl+E View recent files

Vedeți fișierele recente


Select a recently opened file from the list.

Selectați un fișier deschis recent din listă.


Ctrl+Shift+Enter Complete Current Statement

Insert any necessary trailing symbols and put the caret where you can start typing the next statement. Declarație
curentă completă
Introduceți toate simbolurile de sfârșit necesare și puneți marcajul unde puteți
începe să tastați următoarea afirmație.
Ctrl+Alt+L Reformat Code

Codul de reformat
Reformat the whole file or the selected fragment according to the current code style settings.

Reformatați întregul fișier sau fragmentul selectat în funcție de setările


curente ale stilului de cod.

16
Ctrl+Alt+Shift+T Invoke refactoring

Invocați
Refactor the element under the caret, for example, safe delete, copy, move, rename, and so on.

refactorizarea Refactorizați elementul sub semnul indicator, de exemplu,


ștergeți în siguranță, copiați, mutați, redenumiți și așa mai departe.
Ctrl+W Extend or shrink selection
Ctrl+Shift+W
Extindeți sau micșorați
Increase or decrease the scope of selection according to specific code constructs.

selecția Măriți sau micșorați domeniul de selecție în funcție de constructe


specifice de cod.
Ctrl+/ Add/remove line or block comment
Ctrl+Shift+/
Adăugați/eliminați linia sau blocați comentariul
Comment out a line or block of code.

Comentați o linie sau un bloc de cod.


Ctrl+B Go To Declaration

Accesați Declarație
Navigate to the initial declaration of the instantiated class, called method, or field.

Navigați la declarația inițială a clasei instanțiate, numită metodă sau câmp.


Alt+F7 Find Usages

Găsiți utilizări
Show all places where a code element is used across your project.

Afișați toate locurile în care un element de cod este utilizat în proiectul dvs.
Alt+1 Focus the Project tool window

Focalizează fereastra instrumentului Proiect


Escape
Focus the editor Concentrează editorul

Choose the right keymap


To view the keymap configuration, open the Settings/Preferences dialog Ctrl+Alt+S and select Keymap.
Enable function keys and check for possible conflicts with global OS shortcuts.
Use a predefined keymap

IntelliJ IDEA automatically suggests a predefined keymap based on your environment. Make sure that it matches the OS you are
using or select the one that matches shortcuts from another IDE or editor you are used to (for example, Eclipse or NetBeans).

When consulting this page and other pages in IntelliJ IDEA documentation, you can see keyboard shortcuts for the keymap that you
use in the IDE — choose it using the selector at the top of a page.
Install a keymap from a plugin
Besides the default set of keymaps, you can install keymaps from plugins (such as, keymaps for GNOME and KDE): open
the Settings/Preferences dialog Ctrl+Alt+S, select Plugins, switch to the Marketplace tab and search for keymap.

17
Tune your keymap
You can modify a copy of any predefined keymap to assign your own shortcuts for commands that you use frequently.
Import custom keymap
If you have a customized keymap that you are used to, you can transfer it to your installation.
If your keymap stopped working after an update, it is likely that the keymap is not available by default in the new version of

Alegeți harta de taste potrivită


Pentru a vizualiza configurația keymap, deschideți dialogul Setări/Preferințe
Ctrl+Alt+S și selectați Keymap.
Activați tastele funcționale și verificați posibilele conflicte cu comenzile rapide
globale ale sistemului de operare.
Utilizați o hartă de taste predefinită
IntelliJ IDEA sugerează automat o hartă de taste predefinită bazată pe mediul
dumneavoastră. Asigurați-vă că se potrivește cu sistemul de operare pe care îl
utilizați sau selectați-l pe cel care se potrivește cu comenzile rapide din alt IDE
sau editor cu care sunteți obișnuit (de exemplu, Eclipse sau NetBeans).
Când consultați această pagină și alte pagini din documentația IntelliJ IDEA,
puteți vedea comenzile rapide de la tastatură pentru harta tastaturii pe care o
utilizați în IDE - alegeți-o folosind selectorul din partea de sus a paginii.
Instalați o hartă de taste dintr-un plugin
Pe lângă setul implicit de hărți de taste, puteți instala hărți de taste din plugin-uri
(cum ar fi hărți de taste pentru GNOME și KDE): deschideți dialogul
Setări/Preferințe Ctrl+Alt+S, selectați Pluginuri, comutați la fila Piață și căutați
harta de taste.
Reglați harta tastelor
Puteți modifica o copie a oricărei hărți de taste predefinite pentru a vă atribui
propriile comenzi rapide pentru comenzile pe care le utilizați frecvent.
Importați hartă personalizată
Dacă aveți o hartă de taste personalizată cu care sunteți obișnuit, o puteți
transfera în instalație.
Dacă harta tastaturii nu mai funcționează după o actualizare, este probabil ca
harta tastaturii să nu fie disponibilă implicit în noua versiune a IntelliJ IDEA.
Găsiți această hartă de taste ca plugin și instalați-o pe pagina Pluginuri, așa cum
este descris în Instalare pluginuri.
IntelliJ IDEA. Find this keymap as a plugin and install it on the Plugins page as described inInstall plugins.

18
Learn shortcuts as you work Învață comenzi rapide în timp ce
lucrezi
IntelliJ IDEA provides several possibilities to learn shortcuts:
 Find Action lets you search for commands and settings across all menus and tools.

Press Ctrl+Shift+A and start typing to get a list of suggested actions. Then select the necessary action and press Enter to execute
it.

IntelliJ IDEA oferă mai multe posibilități de a învăța comenzi rapide:


• Găsiți acțiune vă permite să căutați comenzi și setări în toate meniurile și
instrumentele.
Apăsați Ctrl+Shift+A și începeți să tastați pentru a obține o listă de acțiuni
sugerate. Apoi selectați acțiunea necesară și apăsați Enter pentru a o executa.

To add or change the shortcut for any action, press Alt+Enter when it is selected in the list.
 Key Promoter X is a plugin that shows a popup notification with the corresponding keyboard shortcut whenever a command is
executed using the mouse. It also suggests creating a shortcut for commands that are executed frequently.
 If you are using one of the predefined keymaps, you can print the default keymap reference card and keep it on your desk to consult
it if necessary. This cheat sheet is also available uner Help | Keyboard Shortcuts PDF.

Pentru a adăuga sau modifica


To print a non-default or customized keymap, use the Keymap exporter plugin.

comanda rapidă pentru orice acțiune, apăsați Alt+Enter când este selectată în
listă.
• Key Promoter X este un plugin care afișează o notificare pop-up cu comanda
rapidă de la tastatură corespunzătoare ori de câte ori o comandă este executată
folosind mouse-ul. De asemenea, sugerează crearea unei comenzi rapide pentru
comenzile care sunt executate frecvent.

19
• Dacă utilizați una dintre hărțile de taste predefinite, puteți tipări cardul de
referință implicit al hărții de taste și îl puteți păstra pe birou pentru ao consulta
dacă este necesar. Această foaie de cheat este disponibilă și în Ajutor | Comenzi
rapide de la tastatură PDF.
• Pentru a imprima o hartă de taste care nu este implicită sau personalizată,
utilizați pluginul de export Keymap

Use advanced features Utilizați funcții avansate


You can further improve your productivity with the following useful features:
Quick Lists
If there is a group of actions that you often use, create a quick list to access them using a custom shortcut. For example,
you can try using the following predefined quick lists:
 Refactor thisCtrl+Alt+Shift+T
 VCS OperationsAlt+`
Smart Keys
IntelliJ IDEA provides a lot of typing assistance features, such as automatically adding paired tags and quotes, and
detecting CamelHump words.
Speed search
When the focus is on a tool window with a tree, list, or table, start typing to see matching items.
Press twice
Some actions in IntelliJ IDEA provide more results when you execute them multiple times. For example, when you
invoke basic code completion with Ctrl+Space on a part of a field, parameter, or variable declaration, it suggests names
depending on the item type within the current scope. If you invoke it again, it will include classes available through
module dependencies. When invoked for the third time in a row, the list of suggestions will include the whole project.
Resize tool windows
You can adjust the size of tool windows without a mouse:
 To resize a vertical tool window, press Ctrl+Alt+Shift+Left and Ctrl+Alt+Shift+Right
 To resize a horizontal tool window, press Ctrl+Alt+Shift+Up and Ctrl+Alt+Shift+Down
 Vă puteți îmbunătăți și mai mult productivitatea cu următoarele
caracteristici utile:
 Liste rapide
 Dacă există un grup de acțiuni pe care le utilizați des, creați o listă rapidă
pentru a le accesa folosind o comandă rapidă personalizată. De exemplu,
puteți încerca să utilizați următoarele liste rapide predefinite:
 • Refactorizează thisCtrl+Alt+Shift+T
 • VCS OperationsAlt+`
 Chei inteligente

20
 IntelliJ IDEA oferă o mulțime de funcții de asistență la tastare, cum ar fi
adăugarea automată de etichete și ghilimele asociate și detectarea
cuvintelor CamelHump.
 Căutare rapidă
 Când se pune accentul pe o fereastră de instrumente cu un arbore, o listă
sau un tabel, începeți să tastați pentru a vedea elementele care se
potrivesc.
 Apăsați de două ori
 Unele acțiuni din IntelliJ IDEA oferă mai multe rezultate atunci când le
executați de mai multe ori. De exemplu, când invocați completarea
codului de bază cu Ctrl+Spațiu pe o parte a unui câmp, a unui parametru
sau a unei declarații de variabilă, acesta sugerează nume în funcție de
tipul de articol din domeniul curent. Dacă îl invocați din nou, va include
clase disponibile prin dependențele modulelor. Când este invocată pentru
a treia oară consecutiv, lista de sugestii va include întregul proiect.
 Redimensionați ferestrele instrumentului
 Puteți ajusta dimensiunea ferestrelor instrumentului fără mouse:
 • Pentru a redimensiona o fereastră verticală a instrumentului, apăsați
Ctrl+Alt+Shift+Stânga și Ctrl+Alt+Shift+Dreapta
 • Pentru a redimensiona o fereastră de instrument orizontală, apăsați
Ctrl+Alt+Shift+Sus și Ctrl+Alt+Shift+Jos

Working on the console


This Handbook focuses on writing and running programs in the IDE — IntelliJ IDEA. However,
many books, studies and websites provide examples of Java programs operating from the
terminal level. Therefore, I decided to discuss this way here as well.

Note: All examples presented in this Handbook can successfully run on the console.

If you want to run programs from the console level, you can write them using one of the
following editors:

 Sublime Text
 Visual Studio Code
jEdit Se lucrează la consolă
Acest manual se concentrează pe scrierea și rularea programelor în IDE —
IntelliJ IDEA. Cu toate acestea, multe cărți, studii și site-uri web oferă exemple
21
de programe Java care funcționează de la nivelul terminalului. Prin urmare, am
decis să discut în acest fel și aici.
Notă: Toate exemplele prezentate în acest manual pot rula cu succes pe consolă.
Dacă doriți să rulați programe de la nivel de consolă, le puteți scrie folosind
unul dintre următoarele editoare:
• Text sublim
• Cod Visual Studio
• jEdit
Crearea unei clase
Creating a class

Create a directory on the hard drive to store your Java programs. Using the selected editor create
the MyFirstJavaProgram.java file in this directory, with the following content:
// MyFirstJavaProgram.java

public class MyFirstJavaProgram {

public static void main(String[] args) {


System.out.println("Hello, World!");
}

} Crearea unei clase


Creați un director pe hard disk pentru a vă stoca programele Java. Folosind
editorul selectat, creați fișierul MyFirstJavaProgram.java în acest director, cu
următorul conținut:
// MyFirstJavaProgram.java

Compilation

Activate the terminal and navigate to the directory where MyFirstJavaProgram.java file is
located. Using the javac command, compile the class.
javac MyFirstJavaProgram.java

As a result of this operation, the MyFirstJavaProgram.class file is created. There should be two
files in the directory now:
 MyFirstJavaProgram.java - the source code
MyFirstJavaProgram.class - the compiled class with the byte code (bytecode)
Compilare
Activați terminalul și navigați la directorul în care se află fișierul
MyFirstJavaProgram.java. Folosind comanda javac, compilați clasa.
javac MyFirstJavaProgram.java

22
Ca rezultat al acestei operațiuni, este creat fișierul MyFirstJavaProgram.class.
Ar trebui să existe două fișiere în director acum:
• MyFirstJavaProgram.java - codul sursă
• MyFirstJavaProgram.class - clasa compilată cu codul octet (bytecode)

Activation

Now it is time to run the compiled code using the java command.
java MyFirstJavaProgram

The following text should appear in the terminal window:


Hello, World!

The javac command is used to compile. To do this, enter a filename, e.g. javac
App.java. The java command is used to run a program, e.g. java App. Activare
Acum este timpul să rulați codul compilat folosind comanda java.
java MyFirstJavaProgram
Următorul text ar trebui să apară în fereastra terminalului:
Salut Lume!
Comanda javac este folosită pentru a compila. Pentru a face acest lucru,
introduceți un nume de fișier, de ex. javac App.java. Comanda java este folosită
pentru a rula un program, de ex. aplicația java.

Developing your first program


Now we will try to display something else on the screen so that you can see how Java's
instructions are invoked. Let us add text Hello, Java! to the program.
// MyFirstJavaProgram.java

public class MyFirstJavaProgram {

public static void main(String[] args) {


System.out.println("Hello, World!");
System.out.println("Hello, Java!");
}
}

The result of program execution should be as below:


Hello, World!

Dezvoltarea primului tău program


Hello, Java!

Acum vom încerca să afișăm altceva pe ecran, astfel încât să puteți vedea cum
sunt invocate instrucțiunile Java. Să adăugăm text Bună ziua, Java! la program.
// MyFirstJavaProgram.java

23
clasă publică MyFirstJavaProgram {

public static void main(String[] args) {


System.out.println("Bună ziua, lume!");
System.out.println("Bună ziua, Java!");
}
}
Rezultatul execuției programului ar trebui să fie după cum urmează:
Salut Lume!
Bună, Java!

You have learned two things now. The first one is that Java executes instructions from top to
bottom: the first message displayed was Hello, World!, followed by Hello, Java!. Besides,
now you know more about the println() method operation. This method displays the text
passed to it and "goes to a new line", i.e., adds a new line sign to the displayed text. Is there a
method that can only* display the text without going to a new line? Of course there is. Let us
try to remove ln from the *println()** name to invoke the print() method.
// MyFirstJavaProgram.java

public class MyFirstJavaProgram {

public static void main(String[] args) {


System.out.print("Hello, World!");
System.out.print("Hello, Java!");
}
}

When the program is run, the displayed result should be as below:


Ați învățat două lucruri acum. Prima este că Java execută
Hello, World!Hello, Java!

instrucțiuni de sus în jos: primul mesaj afișat a fost Hello, World!, urmat de
Hello, Java!. În plus, acum știți mai multe despre operația metodei println().
Această metodă afișează textul transmis și „trece la o linie nouă”, adică adaugă
un nou semn de linie textului afișat. Există o metodă care poate afișa numai*
textul fără a trece la o nouă linie? Desigur că există. Să încercăm să eliminăm ln
din numele *println()** pentru a invoca metoda print() .
// MyFirstJavaProgram.java

clasă publică MyFirstJavaProgram {

24
public static void main(String[] args) {
System.out.print ("Bună ziua, lume!");
System.out.print ("Bună ziua, Java!");
}
}
Când programul este rulat, rezultatul afișat ar trebui să fie ca mai jos:
Bună, lume! Bună ziua, Java!

Note: The println() and print() methods are very useful and offer more possibilities. Later
you will learn that more than a text can be passed to them.

What if you would like to separate these two strings with an empty line? For example, you can
invoke the println() method without passing any text to it. Then the method will have no text to
display, but it will go to a new line anyway.
// MyFirstJavaProgram.java

public class MyFirstJavaProgram {

public static void main(String[] args) {


System.out.print("Hello, World!");
System.out.println(); // (1)
System.out.print("Hello, Java!");
}

} Notă: Metodele println() și print() sunt foarte utile și oferă mai multe
posibilități. Mai târziu vei afla că li se poate transmite mai mult decât un text.
Ce se întâmplă dacă ați dori să separați aceste două șiruri cu o linie goală? De
exemplu, puteți invoca metoda println() fără a-i transmite niciun text. Apoi
metoda nu va avea text de afișat, dar va merge oricum la o nouă linie.
// MyFirstJavaProgram.java

clasă publică MyFirstJavaProgram {


public static void main(String[] args) {
System.out.print ("Bună ziua, lume!");
System.out.println(); // (1)
System.out.print ("Bună ziua, Java!");
}
}

 (1) invoking the println() method without passing a text to display; the method does not display
anything but only goes to a new line.

25
The result of this program will be as below:
Hello, World!

(1) invocarea metodei println() fără a trece un text pentru afișare;


Hello, Java!

metoda nu afișează nimic ci merge doar la o nouă linie.


Rezultatul acestui program va fi următorul:
Salut Lume!

Bună, Java!

Summary
What have you learned in this chapter?
What is the history of Java?
The history of Java began in 1991. Engineers from the Unix circle created a "light" programming
language independent of the hardware platform. Initially, the language was named Oak, but then
it was changed to Java. Since 2010, Java has been developed by Oracle.

What are the basic assumptions of the language?


The basic assumptions are: simplicity, object-orientation, reliability,
networking, independence of architecture, portability, high efficiency and
multithreading. rezumat
Ce ai învățat în acest capitol?
Care este istoria Java?
Istoria Java a început în 1991. Inginerii din cercul Unix au creat un limbaj de
programare „ușor” independent de platforma hardware. Inițial, limba a fost
numită Oak, dar apoi a fost schimbată în Java. Din 2010, Java a fost dezvoltat
de Oracle.
Care sunt ipotezele de bază ale limbii?
Ipotezele de bază sunt: simplitate, orientare obiect, fiabilitate, rețea,
independență de arhitectură, portabilitate, eficiență ridicată și multithreading
What is a source code?
A source code is the result of the programmer's work. These are the operations
to be executed by the computer. In Java, you place a source code in text files
with .java extension. Ce este un cod sursă?

26
Un cod sursă este rezultatul muncii programatorului. Acestea sunt operațiunile
care trebuie executate de computer. În Java, plasați un cod sursă în fișiere text
cu extensia .java.
What is a compiler?
A compiler is a program that converts (and at the same time, optimizes and
detects errors) the source code into a code written in other language. In
Java, a compiler processes files with .java extension and places the result
in .class files. Ce este un compilator?
Un compilator este un program care convertește (și în același timp, optimizează
și detectează erori) codul sursă într-un cod scris în altă limbă. În Java, un
compilator procesează fișiere cu extensia .java și plasează rezultatul în
fișiere .class.
What is a bytecode?
It is the result of compiling a program written in Java. Ce este un bytecode?
Este rezultatul compilării unui program scris în Java

What is an IDE and which ones are now popular?


IDE means an Integrated Development Environment. It is used to create, test,
build and run programs. It offers many capabilities that can be expanded with
a plugin mechanism. Three environments are now popular: IntelliJ IDEA, Eclipse
and NetBeans. Ce este un IDE și care sunt acum populare?
IDE înseamnă un mediu de dezvoltare integrat. Este folosit pentru a crea, testa,
construi și rula programe. Oferă multe capabilități care pot fi extinse cu un
mecanism de plugin. Trei medii sunt acum populare: IntelliJ IDEA, Eclipse și
NetBeans.
Do I need an IDE to write a program in Java?

No, you can use your favorite text editor. You can build an application using the javac command
and run it using java.

How can I check which Java version has been installed on my computer?

You can do this, for example, by using the console and entering the java -version command.

What is the name of the method that runs the program in Java?

27
This method is public static void main(String[] args) .

What is the operation of println() and print() methods?

Both methods display the text passed to them on the screen. However, the println() method
goes to a new line after the text is displayed.

How can I display an empty line?

There are several ways to do this. You have learned one of them: you can invoke
the println() method without passing a text to it.

What are the basic rules for naming in Java?


It is assumed to use English to name classes, fields and variables in Java. A
class name starts with a capital letter, while other elements start with a
lowercase letter. If the name consists of several words, we use the so-
called CamelCase notation: each subsequent word of the name starts with a
capital letter. Am nevoie de un IDE pentru a scrie un program în Java?
Nu, puteți folosi editorul de text preferat. Puteți construi o aplicație folosind
comanda javac și o puteți rula folosind java.
Cum pot verifica ce versiune Java a fost instalată pe computerul meu?
Puteți face acest lucru, de exemplu, utilizând consola și introducând comanda
java -version.
Care este numele metodei care rulează programul în Java?
Această metodă este public static void main(String[] args).
Care este funcționarea metodelor println() și print()?
Ambele metode afișează textul transmis pe ecran. Cu toate acestea, metoda
println() trece la o nouă linie după ce textul este afișat.
Cum pot afișa o linie goală?
Există mai multe moduri de a face acest lucru. Ați învățat una dintre ele: puteți
invoca metoda println() fără a-i transmite un text.
Care sunt regulile de bază pentru denumirea în Java?
Se presupune că se folosește limba engleză pentru a denumi clase, câmpuri și
variabile în Java. Un nume de clasă începe cu o literă majusculă, în timp ce alte
elemente încep cu o literă mică. Dacă numele este format din mai multe cuvinte,
folosim așa-numita notație CamelCase: fiecare cuvânt ulterior al numelui începe
cu o literă mare.

28
Exercises

 Write a program (create a new class using the main method) to display Hello, <Your
Name>! instead of Hello, World! on the screen.
 Write a program that displays your business card like the one below:
########################
# #
# John Smith #
# Sesame Street 345/7b #
# New York 10019 #
# #
########################

 use different characters, for instance:


 - for horizontal lines
 | for vertical lines
 / and \ (or +) for corners
 Test the compiling and running the class from the console
 create a new directory
 create a PrintHello class (in the file named PrintHello.java) in the new directory:
public class PrintHello {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

 compile the class using javac command:


 javac PrintHello.java

 run the PrintHello class by using the java command:


 java PrintHello

 Check whether the text like below is displayed:


 Hello, WOrld!

 Remove one of the quotes around the Hello, World! text:


public class PrintHello {
public static void main(String[] args) {
System.out.println("Hello, World!);
}
}

 try to compile the program...


 check whether the following error appeared:
PrintHello.java:4: error: unclosed string literal
System.out.println("Hello, World!);

1 error

 correct the quote and try to "damage" the program in some other way (each time try to compile
and pay attention to the errors returned):
 remove or add brace { or }
 remove ;
 remove or add a letter to one of the methods
change the class name (without changing the file name) Exerciții
29
• Scrieți un program (creați o clasă nouă folosind metoda principală) pentru a
afișa Bună ziua, <Numele tău>! în loc de Hello, World! pe ecran.
• Scrieți un program care să vă afișeze cartea de vizită ca cel de mai jos:
#######################
##
# John Smith #
# Sesame Street 345/7b #
# New York 10019 #
##
#######################
• utilizați caractere diferite, de exemplu:
• - pentru linii orizontale
• | pentru linii verticale
• / și \ (sau +) pentru colțuri
• Testați compilarea și rularea clasei din consolă
• creați un director nou
• creați o clasă PrintHello (în fișierul numit PrintHello.java) în noul director:
clasă publică PrintHello {
public static void main(String[] args) {
System.out.println("Bună ziua, lume!");
}
}
• compilați clasa folosind comanda javac:
• javac PrintHello.java
• rulați clasa PrintHello utilizând comanda java:
• java PrintHello
• Verificați dacă este afișat textul de mai jos:
• Salut Lume!
• Eliminați unul dintre ghilimele din jurul Hello, World! text:
clasă publică PrintHello {
public static void main(String[] args) {
System.out.println ("Bună ziua, lume!);
}
}

30
• încercați să compilați programul...
• verificați dacă a apărut următoarea eroare:
PrintHello.java:4: eroare: literal șir neînchis
System.out.println ("Bună ziua, lume!);

1 eroare
• corectați citatul și încercați să „deteriorați” programul într-un alt mod (de
fiecare dată încercați să compilați și să acordați atenție erorilor returnate):
• eliminați sau adăugați acolade { sau }
• elimina ;
• eliminați sau adăugați o literă la una dintre metode
• schimbați numele clasei (fără a schimba numele fișierului)
Types of data
In Java, as in other languages, we distinguish many (built-in) data types that can store numbers,
characters, strings (texts), logical type, and many sophisticated, complex types that can perform
operations in addition to storing values.

Data types can be divided into two types:

 simple (primitive)
 complex (object-oriented/reference)

Tip

The names of primitive types are written in lowercase, while object-oriented types are capitalized.

Tipuri de date
În Java, ca și în alte limbi, distingem multe tipuri de date (încorporate) care pot
stoca numere, caractere, șiruri (texte), tip logic și multe tipuri sofisticate și
complexe care pot efectua operații pe lângă stocarea valorilor.
Tipurile de date pot fi împărțite în două tipuri:
• simplu (primitiv)
• complex (orientat pe obiect/referință)
Bacsis
Numele tipurilor primitive sunt scrise cu litere mici, în timp ce tipurile orientate
pe obiecte sunt scrise cu majuscule.

Variables

31
Variables can be compared to “containers” or “boxes” for data. The data that can be stored in a
specific variable are defined by their type. Each variable has:

 a type
 a name

 a value

Variabile
Variabilele pot fi comparate cu „containere” sau „cutii” pentru date. Datele care
pot fi stocate într-o anumită variabilă sunt definite de tipul lor. Fiecare variabilă
are:
• un fel
• un nume
• o valoare
Pattern of a variable declarationModelul unei declarații variabile
type variable-name; tip nume-variabilă;

While declaring the variable, you must specify its name. The value can be assigned later.

Când declarați variabila, trebuie să specificați numele acesteia. Valoarea poate fi


atribuită ulterior.

Pattern of declaration and initialization of a variable Model de declarare și inițializare a


unei variabile
type variable-name = value; tip nume-variabilă = valoare;

Before a variable can be used, a value must be assigned to it. The code below will result in an error!

Înainte ca o variabilă să poată fi utilizată, trebuie să i se atribuie o valoare.


Codul de mai jos va avea ca rezultat o eroare!

Example of using a variable without initialization Exemplu de utilizare a unei variabile


fără inițializare
int size; dimensiune int;

System.out.println("Size = " + size);

System.out.println("Dimensiune = " + dimensiune);


Note Notă

32
The entry "Size = " + size means concatenation of two values. Concatenation is performed by

the + operator which in this case combines the Size = string with the value of the size variable.

More information can be found in chapter Arithmetic and concatenation operators.

Intrarea „Size = ” + size înseamnă concatenarea a două valori. Concatenarea se


realizează de către operatorul + care în acest caz combină dimensiunea = șir cu
valoarea variabilei dimensiune. Mai multe informații pot fi găsite în capitolul
Operatori aritmetici și de concatenare.
Tip Bacsis
Names of variables should be descriptive and self-documenting. Numele variabilelor trebuie
să fie descriptive și auto-documentate.
The division of data types determines the types of variables: Împărțirea tipurilor de date
determină tipurile de variabile:
- variables of simple types

- variabile de tipuri simple


they store values only

ele stochează numai valori


- variables of complex types

they store only references (an address of a memory cell) to the data that they “point to” -
variabile de tipuri complexe
stochează doar referințe (o adresă a unei celule de memorie) la datele către care
„indică”

To better understand the difference between the variables of simple and complex (object-oriented)

Pentru a înțelege mai bine diferența dintre variabilele


types, I will use some examples.

tipurilor simple și complexe (orientate pe obiect), voi folosi câteva exemple.


Coins and banknotes can be compared to simple type variables, because the value indicated by the

denomination is stored in them. However, a bank card or a credit card is in this case responsible for

a variable of the complex type (references); the card only indicates the account where the money

Monedele și bancnotele pot fi comparate cu variabile de


(value) is physically located.

tip simplu, deoarece în ele este stocată valoarea indicată de denumire. Totuși, un
card bancar sau un card de credit este în acest caz responsabil pentru o variabilă
de tip complex (referințe); cardul indică doar contul în care se află fizic banii
(valoarea).
A remote control that remotely executes operations on a receiver, e.g. a TV, an amplifier, etc., is

another example of analogy to the reference (object-oriented) types. Unlike variables of simple

types (that store the value), variables of complex types only store the reference to the object,

33
therefore it is possible to have more than one variable that has the same reference to the object; it

O telecomandă care
is like having more than one remote control for a TV or a stereo set.

execută de la distanță operațiuni pe un receptor, de ex. un televizor, un


amplificator etc., este un alt exemplu de analogie cu tipurile de referință
(orientate pe obiecte). Spre deosebire de variabilele de tipuri simple (care
stochează valoarea), variabilele de tipuri complexe stochează doar referința la
obiect, prin urmare este posibil să existe mai mult de o variabilă care are aceeași
referință la obiect; este ca și cum ai avea mai mult de o telecomandă pentru un
televizor sau un set stereo.
Important Important

Java features strict type control. Each variable must be of a specific type that has been once

declared—it cannot be changed anymore!

Java are un control strict al tipului. Fiecare variabilă trebuie să fie de un anumit
tip care a fost odată declarată - nu mai poate fi schimbată!
Primitive types Tipuri primitive
There are eight basic types in Java. These are types that have a certain size in memory; they can

store numeric values (integers and floating point values), characters and logical values. All

Există opt tipuri de bază în Java.


numerical types are signed , i.e., they have a sign.

Acestea sunt tipuri care au o anumită dimensiune în memorie; pot stoca valori
numerice (numere întregi și valori în virgulă mobilă), caractere și valori logice.
Toate tipurile numerice sunt semnate, adică au un semn.
Tip Bacsis

Variables (values) of basic types are compared using sign ==. Variabilele (valorile) tipurilor

de bază sunt comparate folosind semnul ==.


Important Important
In a simple type variable, only the value is stored!

Într-o variabilă de tip simplu, doar valoarea este stocată!


Integer types Tipuri întregi
Integer types are numbers with no fractional part. They can represent both positive and negative
values. Tipurile întregi sunt numere fără parte fracțională. Ele pot reprezenta atât
valori pozitive, cât și negative.
- byte: from `- 128` to `127` (`2^8^` numbers) - octet: de la `- 128` la `127` (numere

`2^8^`)

34
- short: from `- 32 768` to `32 767` (`2^16^` numbers) - scurt: de la `- 32 768` la `32 767`
(`2^16^` numere)
- int: from `- 2 147 483 648` to `2 147 483 647` (`2^32^` numbers) - int: de la `- 2 147 483
648` la `2 147 483 647` (`2^32^` numere)
- long: from `- 9 223 372 036 854 775 808` to `9 223 372 036 854 775 807` (`2^64^` numbers); suffix

`l` or `L` is applied (`L` is recommended) - lung: de la `- 9 223 372 036 854 775 808` la
`9 223 372 036 854 775 807` (`2^64^` numere); se aplică sufixul `l` sau `L` (se
recomandă `L`)
The most frequently used types are byte, int and long. Cele mai frecvent utilizate tipuri

sunt byte, int și long


- `byte`

in programming, we often use bits, and *1 byte* is 8 bits; `byte` is often used when working with

- `octet`
files, networks and large arrays

în programare, folosim adesea biți, iar *1 octet* este de 8 biți; `byte` este adesea
folosit când lucrați cu fișiere, rețele și matrice mari
- `int`
is the default integer data type in Java. When you enter a value, for instance `5`, Java treats
this value as `int` by default. Operations on numbers (integers) are also performed on `int` types
by default. This range is sufficient for most operations

- `int`
este tipul de date întreg implicit în Java. Când introduceți o valoare, de exemplu
`5`, Java tratează această valoare ca `int` în mod implicit. Operațiile pe numere
(întregi) sunt efectuate și pe tipurile `int` în mod implicit. Acest interval este
suficient pentru majoritatea operațiunilor
- `long`

sometimes during operations on the `int` type we can exceed the range for this type and we need a

larger one, e.g. when adding very large numbers of the `int` type we get a number out of range—then

it is worth switching to the `long` type. The long values are marked with letter `l` or `L`, e.g.

`5L`, `120000000L`, `-556677889900L`

- `lung`
uneori în timpul operațiunilor pe tipul `int` putem depăși intervalul pentru acest
tip și avem nevoie de unul mai mare, de ex. când adăugăm numere foarte mari
de tip `int` obținem un număr în afara intervalului — atunci merită să trecem la
tipul `long`. Valorile lungi sunt marcate cu litera `l` sau `L`, de ex. `5L`,
`120000000L`, `-556677889900L`
Examples of variables of integer types Exemple de variabile de tipuri întregi

35
byte b = (byte) 56;
short s = (short) 89;
int i = 256;

long l = 5500L;

octet b = (octet) 56;


scurt s = (scurt) 89;
int i = 256;
lung l = 5500L;

 (byte) indicates casting on the byte type


 (short) indicates casting on the short type

 • (octet) indică turnarea pe tipul de octet


 • (scurt) indică turnarea pe tipul scurt
In this case, casting is not necessary (Java can perform it automatically), but this mechanism is

În
worth knowing (more information about it can be found in chapter CONVERSION OF TYPES)

acest caz, castingul nu este necesar (Java o poate efectua automat), dar acest
mecanism merită cunoscut (mai multe informații despre el găsiți în capitolul
CONVERSIUNEA TIPURILOR)

By default, integer operations in Java are performed using the int type. Please look at the code
below: ); În mod implicit, operațiile cu numere întregi în Java sunt efectuate
folosind tipul int. Vă rugăm să priviți codul de mai jos:
long a = 24 * 60 * 60 * 1000 * 1000;
long b = 24 * 60 * 60 * 1000;

System.out.println("a / b = " + a / b

lung a = 24 * 60 * 60 * 1000 * 1000;


b lung = 24 * 60 * 60 * 1000;
System.out.println("a / b = " + a / b);
According to what we remember from our math lessons, we can reduce the a / b quotient by pulling
value 24 * 60 * 60 * 1000 in front of the bracket and expect a result equal to **1000**. Unfortunately, in
Conform a ceea ce ne
the current form, the value displayed on the screen will be as below:5
amintim din lecțiile noastre de matematică, putem reduce coeficientul a/b
trăgând valoarea 24 * 60 * 60 * 1000 în fața parantezei și ne așteptăm la un
rezultat egal cu **1000**. Din păcate, în forma actuală, valoarea afișată pe
ecran va fi următoarea:
5
What is more, if both the a and b values are multiplied by 1000 first, the result will be even more
surprising:

36
long a = 24 * 60 * 60 * 1000 * 1000 * 1000;
long b = 24 * 60 * 60 * 1000 * 1000;
System.out.println("a / b = " + a / b);
Result:

-3 În plus, dacă ambele valori a și b sunt înmulțite mai întâi cu 1000, rezultatul
va fi și mai surprinzător:
lung a = 24 * 60 * 60 * 1000 * 1000 * 1000;
lung b = 24 * 60 * 60 * 1000 * 1000;
System.out.println("a / b = " + a / b);
Rezultat:
-3
Why is this happening? Why when we multiply and divide positive numbers, we get a negative

De ce se întâmplă asta? De ce atunci când înmulțim și împărțim


number as a result?

numere pozitive, obținem ca rezultat un număr negativ


As I have mentioned earlier, Java performs calculations on the int type by default. When

multiplying int type values, the range is exceeded and the result becomes incorrect (it is still

După cum am menționat mai devreme,


the int type). Then it is assigned to the long type.

Java efectuează calcule pe tipul int în mod implicit. La înmulțirea valorilor de


tip int, intervalul este depășit și rezultatul devine incorect (este tot tipul int).
Apoi este atribuit tipului lung.

To avoid such a situation, it is enough to add letter L to one of the values, which will allow Java to

Pentru a evita o astfel de situație, este suficient


perform the operation on the long type.

să adăugați litera L la una dintre valori, ceea ce va permite Java să efectueze


operația pe tipul lung.
long a = 24 * 60 * 60L * 1000 * 1000;
long b = 24 * 60 * 60 * 1000;
System.out.println("a / b = " + a / b);

lung a = 24 * 60 * 60L * 1000 * 1000;


b lung = 24 * 60 * 60 * 1000;
System.out.println("a / b = " + a / b);
Floating point types
Floating point types are types with a fractional part, which can be both positive and negative
values.
- `float`
a single precision format on 32 bits; suffix `f` or `F` is applied (`F` is recommended)

- `double`

37
a double precision format on 64 bits; **the default type for floating point values**; to increase

Tipuri în virgulă mobilă


readability, you can use suffix `d` or `D` (`D` is recommended)

Tipurile cu virgulă mobilă sunt tipuri cu o parte fracțională, care pot fi atât
valori pozitive, cât și negative.
- `plutire`
un singur format de precizie pe 32 de biți; se aplică sufixul `f` sau `F` (se
recomandă `F`)
- `dublu`
un format de dublă precizie pe 64 de biți; **tipul implicit pentru valorile în
virgulă mobilă**; pentru a crește lizibilitatea, puteți folosi sufixul `d` sau `D`
(se recomandă `D`)
Examples of variable of floating point types
float f = 3.141592F;
double d = 2.718281828D;

Types float and double should not be used to store financial values, because in some cases the

string of these numbers leads to loss of information (precision). This is due to the representation of

floating point numbers in a binary system in which there is no accurate representation of

fraction 1/10, just like in the decimal system there is no exact representation of fraction 1/3.

Exemple de tipuri de variabile cu virgulă mobilă


float f = 3,141592F;
dublu d = 2,718281828D;
Tipurile float și double nu ar trebui folosite pentru a stoca valori financiare,
deoarece în unele cazuri șirul acestor numere duce la pierderea de informații
(precizie). Acest lucru se datorează reprezentării numerelor cu virgulă mobilă
într-un sistem binar în care nu există o reprezentare exactă a fracției 1/10, la fel
ca în sistemul zecimal nu există o reprezentare exactă a fracției 1/3.
Example of a problem with precision
System.out.println(2.00 - 1.10);
System.out.println(2.00 - 1.50);
System.out.println(2.00 - 1.80);

The result of the operation will be as below: Rezultatul operațiunii va fi următorul:


0.8999999999999999
0.5
0.19999999999999996

Tip

Bacsis
For storing financial values, use the BigDecimal class.

Pentru stocarea valorilor financiare, utilizați clasa BigDecimal.

38
Character types
- `char`
is used to store one character. These characters are entered between apostrophes, e.g. `'a'`,
`'T'`, `'+'`. They are

character codes (non-negative integers from 0 to 65 556). Each code indicates a character

in Unicode standard. We can express them in hexadecimal notation (in the position system based

on number 16). Their values range from '\u0000' to '\uFFFF'. \u is a substitute symbol for a character

in the Unicode. char is the type without a sign (unsigned) - it stores non-negative values. Tipuri
de caractere
- `char`
este folosit pentru a stoca un caracter. Aceste caractere sunt introduse între
apostrofe, de ex. `'a'`, `'T'`, `'+'`. Sunt
coduri de caractere (numere întregi nenegative de la 0 la 65 556). Fiecare cod
indică un caracter în standardul Unicode. Le putem exprima în notație
hexazecimală (în sistemul de poziții bazat pe numărul 16). Valorile lor variază
de la „\u0000” la „\uFFFF”. \u este un simbol înlocuitor pentru un caracter în
Unicode. char este tipul fără semn (nesemnat) - stochează valori
nenegative.Examples of character type variables
char a = 'a';
char bigA = 'A';
char newLine = '\n';
char plus = '+';

 'A' to '\u0041'
 'B' to '\u0042'
 'C' to '\u0043'
 'a' to '\u0061'
 'b' to '\u0062'
 'c' to '\u0063'
 '0' to '\u0030'
 '1' to '\u0031'
 '9' to '\u0039'

Pe
In addition to the \u symbol, there are several other important and useful substitute symbols.

lângă simbolul \u, există câteva alte simboluri de înlocuire importante și utile.

39
Substitute symbols substitute
for special
symbol name
characters
înlocuiți
Înlocuiți
numele
simbolurile cu simbolului
caracterele
speciale

\b Backspace

\t
Horizontal
tab Filă
orizontală

\n
New line
Linie nouă
Citat dublu

\r
Retur
transport
Carriage
return

\" Double quote


Citat dublu

\'
Single quote
ghilimele
unice

\\ Backslash

40
Example of substitution symbols applied
System.out.print("Hello, World!\n");
System.out.print("\tHello, World!\n");
System.out.print("\t\t\"Hello, World!\"\n");

The result will be as below:


Hello, World!
Hello, World!
"Hello, World!"

Logical type

 booleana logical type that can store one of two values: false or true. It is used to verify logic
conditions

Examples of variables of a logical type


boolean isAdult = true;

Tip logic
boolean active = false;

• boolean un tip logic care poate stoca una dintre două valori: false sau
adevărată. Este folosit pentru verificarea condițiilor logice
Exemple de variabile de tip logic
boolean esteAdult = adevărat;
boolean activ = fals;
Note

The table below is for reference only, you do not have to remember all ranges or values exactly.

Notă
Tabelul de mai jos este doar pentru referință, nu trebuie să vă amintiți exact
toate intervalele sau valorile.

type siz description default


e value

byte 1 -128 … 127 (byte)


byt 0
e

shor 2 –32 768 … 32 767 (short


t byt )0
es

41
type siz description default
e value

int 4 –2 147 483 648 … 2 147 483 647 0


byt
es

long 8 –9 223 372 036 854 775 808 … 9 0L


byt 223 372 036 854 775 807
es

floa 4 -3,40282347E+38 0.0F


t byt … \</subscript> 3,40282347E+38
es

doub 8 -1,79769313486231570E+308 … \ 0.0


le byt </subscript> 1,7976931348623157
es 0E+308

char 2 0 … 65 556 ('\u0000' … '\uFFFF') '\


byt u0000'
es

bool 1 false, true


ean bit
*

Primitive types—summary
*
) boolean type stores 1 bit of information, but according to the documentation its size is not

precisely specified

Tipuri primitive — rezumat


*) tipul boolean stochează 1 bit de informație, dar conform documentației
dimensiunea acestuia nu este specificată precis

Object-oriented types Tipuri orientate pe obiecte

42
In addition to the above-mentioned simple types (which only store the value), Java provides
thousands of object-oriented types that can consist of both primitive and object-oriented types. In
Pe lângă tipurile simple
addition to storing values, they also provide operations (methods).
menționate mai sus (care stochează doar valoarea), Java oferă mii de tipuri
orientate pe obiecte care pot consta atât din tipuri primitive, cât și din cele
orientate pe obiecte. Pe lângă stocarea valorilor, acestea oferă și operațiuni
(metode).
In addition to the types found in the Java distribution, there are hundreds of thousands types

created and shared (in the form of libraries) by Java programmers around the world.

Pe lângă tipurile găsite în distribuția Java, există sute de mii de tipuri create și
partajate (sub formă de biblioteci) de programatorii Java din întreaga lume.
What is more, each of us—by programming and defining new classes—creates new types of data
every day.

Tip

Variables of object-oriented types are compared using the equals() method.

Note

Instances of classes (objects) of object-oriented types are created using a key word: new.

Important

În plus, fiecare dintre noi, prin


The default value for object-oriented variables is null.

programarea și definirea de noi clase, creează noi tipuri de date în fiecare zi.
Bacsis
Variabilele tipurilor orientate pe obiecte sunt comparate folosind metoda
equals().
Notă
Instanțe de clase (obiecte) de tipuri orientate pe obiecte sunt create folosind un
cuvânt cheie: nou.
Important
Valoarea implicită pentru variabilele orientate pe obiect este nulă.

String
Perhaps the most popular object-oriented type in Java is String - we were using it in the program

displaying text Hello, World!. A String is called a chain type since it consists of a chain (string) of

43
characters, that is, individual characters (chars) surrounded by quotes " ". For instance, “Alice has a

cat.", "Hello, World!", "New York 10019" or "" (indicating an empty string of characters). Character

Şir
strings are often called inscriptions or literals.

Poate cel mai popular tip orientat pe obiecte din Java este String - îl folosim în
programul care afișa textul Hello, World!. Un șir se numește un tip de lanț
deoarece constă dintr-un lanț (șir) de caractere, adică caractere individuale
(caractere) înconjurate de ghilimele " ". De exemplu, „Alice are a cat.”, „Hello,
World!”, „New York 10019” sau „” (indicând un șir gol de caractere). Șirurile
de caractere sunt adesea numite inscripții sau literale.

Examples of variables of the String type


String helloWorld = "Hello, World!";
String title = "Thinking in Java";

The String class is unique in many respects. Primitive types have only values that we assign to

variables using the = sign. To create an object-oriented type (create an object of a given class;

more information on this topic can be found in chapter “Object-oriented programming”), you should

Clasa String este unică în multe


use the keyword new before invoking the constructor.

privințe. Tipurile primitive au numai valori pe care le atribuim variabilelor


folosind semnul =. Pentru a crea un tip orientat pe obiecte (creați un obiect
dintr-o clasă dată; mai multe informații despre acest subiect puteți găsi în
capitolul „Programare orientată pe obiecte”), ar trebui să utilizați cuvântul cheie
new înainte de a invoca constructorul.

Examples of creating String type objects


String helloWorld = new String("Hello, World!");
String title = new String("Thinking in Java");

 entry new String("text") indicates invoking the constructor of the String class and transferring
the "text" argument to it; it creates a new object of the String class

The String type is so popular that we do not need to use the keyword new and the constructor in

order to create a new instance; you simply need to assign a string of characters to the variable. •
entry new String(„text”) indică invocarea constructorului clasei String și
transferul argumentului „text” către acesta; creează un nou obiect al clasei
String

44
Tipul String este atât de popular încât nu trebuie să folosim cuvântul cheie new
și constructorul pentru a crea o instanță nouă; trebuie pur și simplu să atribuiți
un șir de caractere variabilei.

Examples of creating objects of the String type - short version


String helloWorld = "Hello, World!";
String title = "Thinking in Java";

Important Important
There is a subtle difference between these two entries! Există o diferență subtilă între
aceste două intrări!
In addition to storing entries, you can perform operations on the String type, that is, you can invoke

methods. Pe lângă stocarea intrărilor, puteți efectua operații pe tipul String, adică
puteți invoca metode.
An example of invoking the length() method that returns the length of a string Un exemplu de

invocare a metodei length() care returnează lungimea unui șir


System.out.println("Alice has a cat, and a cat has Alice!".length());
- to invoke the method, we use a dot character (`.`) followed by the method name, in this case
`length()`; in round

brackets we pass arguments to the method - in this case we invoked the argumentless (non-
parametric) method.

The following text will be displayed on the screen:

26

System.out.println("Alice are o pisică, iar o pisică o are pe Alice!".length());


- pentru a invoca metoda, folosim un caracter punct (`.`) urmat de numele
metodei, în acest caz `length()`; în rotund
între paranteze trecem argumente metodei - în acest caz am invocat metoda fără
argumente (neparametrică).
Următorul text va fi afișat pe ecran:
26
An example of invoking substring() method that returns the string length
String text = "Alice has a cat, and a cat has Alice!";
System.out.println(text.substring(13, 25));

- the substring(int beginIndex, int endIndex) method returns the substring (fragment of the

text) according to the passed argument values. beginIndex indicates the beginning of the

fragment (including this character), while endIndex indicates the end of the fragment (without this

45
character); the values are provided starting from zero Un exemplu de invocare a metodei
substring() care returnează lungimea șirului
String text = „Alice are o pisică, iar o pisică are Alice!”;
System.out.println(text.substring(13, 25));
- metoda subșir(int beginIndex, int endIndex) returnează subșirul (fragment de
text) conform valorilor argumentului transmise. beginIndex indică începutul
fragmentului (inclusiv acest caracter), în timp ce endIndex indică sfârșitul
fragmentului (fără acest caracter); valorile sunt furnizate începând de la zero
Alice has a cat, and a cat has Alice!
01234567891111111111222222
0123456789012345
^ ^
| |
(inclusive) (exclusive)

The screen will display:


and a cat has Alice

If we try to invoke an operation, i.e., refer after the dot (.) on an uninitialized variable, a runtime

Dacă încercăm să invocăm


error will occur (an exception NullPointerException will be returned).

o operație, adică să facem referire după punctul (.) pe o variabilă neinițializată,


va apărea o eroare de rulare (va fi returnată o excepție NullPointerException).

name of the method operation

charAt(int index)
returns the character
located at
the index position returnează
caracterul situat la poziția
indexului

endsWith(String
checks whether the text ends
suffix)
with a suffix string verifică
dacă textul se termină cu un
șir de sufix

equalsIgnoreCase(Strin
compares the text and

46
name of the method operation

g otherString)
ignores the case of the
letters compară textul și
ignoră cazul literelor

indexOf(String str)
returns the position of the
beginning of the str string
in the text returnează
poziția începutului șirului str
în text

isEmpty()
checks whether the text is
empty ("")verifică dacă textul
este gol ("")

lastIndexOf(String
returns the last position of
str)
the beginning of
the str string in the text
returnează ultima poziție a
începutului șirului str din
text

replace(char oldChar,
returns the text,
char newChar)
replacing oldChar with newCha
rreturnează textul, înlocuind
oldChar cu newChar

startsWith(String
checks whether the text
prefix)
begins with
the prefix string verifică
dacă textul începe cu șirul de

47
name of the method operation

prefix

toLowerCase()
returns the text, changing
uppercase letters to
lowercase onesreturnează
textul, schimbând literele
mari în minuscule

toUpperCase()
returns the text, replacing
lowercase letters with
uppercase ones returnează
textul, înlocuind literele mici
cu majuscule

trim()
returns text, removing white
characters from the
beginning and end returnează
text, eliminând caracterele
albe de la început și Sfârșit

Some useful methods of the String class

The String class is immutable (unmodifiable)! Please note that the methods of this class do not
modify the original value of the string and only return the modified copy.
String hello = "Hello, World!"
hello.toUpperCase();

Câteva metode utile ale clasei String


System.out.println(hello);

Clasa String este imuabilă (nemodificabilă)! Vă rugăm să rețineți că metodele


acestei clase nu modifică valoarea originală a șirului și returnează doar copia
modificată.
String salut = "Bună ziua, lume!"

48
hello.toUpperCase();
System.out.println(bună ziua);
 The toUpperCase was invoked, which does not modify the original text but only returns the
modified string; in this case, we did not assign the result to the new variable, so we have lost
the effect of its operation.
Hello, World!
I would like to point to the difference in the invoking of the methods that we have used so far.
Please look at the code below:
String.valueOf(23);
String text = new String("Alice has a cat");
text.endsWith("cat");

- It is the invoking of the `valueOf() method` on the `**String class**`. We did not invoke this

• A fost invocat toUpperCase, care nu modifică textul original, ci


method on an

returnează doar șirul modificat; în acest caz, nu am atribuit rezultatul noii


variabile, așa că am pierdut efectul funcționării acesteia.
Salut Lume!
Aș dori să subliniez diferența în invocarea metodelor pe care le-am folosit până
acum. Vă rugăm să priviți codul de mai jos:
String.valueOf(23);
String text = new String("Alice are o pisică");
text.endsWith("pisica");
- Este invocarea metodei `valueOf()` pe `**clasa String**`. Nu am invocat
această metodă pe un

(object-oriented) variable, i.e. we did not invoke this method on a particular value of this variable,
but only (in a context-free manner) on the String class. The valueOf() method is a static method,
that is, it can be run without having (creating) a variable of the String type.
> **Note**
> Classes, methods, blocks and static variables are not within the scope of this Handbook.

 this is invoking the endsWith() method on a specific variable. Depending on the value stored in
the text variable, the action (result of the invocation) of this method will vary.
The endsWith() method is an instance method, that is, we invoke it on a String class object.
You will learn more about it in chapter Object-oriented programming.

 orientată pe obiect), adică nu am invocat această metodă pe o anumită


valoare a acestei variabile, ci doar (într-o manieră fără context) pe clasa
String. Metoda valueOf() este o metodă statică, adică poate fi rulată fără a
avea (crearea) o variabilă de tip String.
 > **Notă**
 > Clasele, metodele, blocurile și variabilele statice nu fac parte din
domeniul de aplicare al acestui manual.

49
 • aceasta este invocarea metodei endsWith() pe o anumită variabilă. În
funcție de valoarea stocată în variabila text, acțiunea (rezultatul invocării)
acestei metode va varia. Metoda endsWith() este o metodă de instanță,
adică o invocăm pe un obiect din clasă String. Veți afla mai multe despre
el în capitolul Programare orientată pe obiecte.

Classes responsible for date and time


Now I will show you several classes that store the date and time and offer the opportunity to work
on this data.

 LocalDate
 LocalTime

Clasele responsabile pentru data și ora


LocalDateTime

Acum vă voi arăta mai multe clase care stochează data și ora și oferă
posibilitatea de a lucra la aceste date.
• LocalDate
• Ora locala
• LocalDateTime
Example of receiving current date and time
System.out.println(LocalDate.now());
System.out.println(LocalTime.now());
System.out.println(LocalDateTime.now());

Tip

To use these classes, we need to import them (indicate to Java in which package (directory) they
are located). At the beginning of the file, before the declaration of the class, add the following text:

` java import java.time.*;

The result will vary depending on the start time, but it will have the format as below.
2019-04-08
20:21:16.726
2019-04-08T20:21:16.726
Based on the output, we see that:

 LocalDate represents date


 LocalTime represents time
 LocalDateTime represents date and time

 Bacsis

50
 Pentru a folosi aceste clase, trebuie să le importam (indicați în Java în ce
pachet (director) se află). La începutul dosarului, înainte de declararea
clasei, se adaugă următorul text:
 ` import java java.time.*;
 Rezultatul va varia în funcție de ora de începere, dar va avea formatul de
mai jos.
 08-04-2019
 20:21:16.726
 2019-04-08T20:21:16.726
 Pe baza rezultatelor, vedem că:
 • LocalDate reprezintă data
 • LocalTime reprezintă ora
 • LocalDateTime reprezintă data și ora

Note

You will often encounter also Date and Calendar classes where date and/or time are processed.

Notă
As an exercise, test the methods of these classes.

Veți întâlni adesea și clase de date și calendar în care sunt procesate data și/sau
ora.
Ca exercițiu, testați metodele acestor clase

Class for simple mathematical operations


For simple mathematical operations, we can use the Math class. Clasa pentru operatii
matematice simple
Pentru operații matematice simple, putem folosi clasa Math
Example of some basic mathematical operations
System.out.println(Math.max(5, 10));
System.out.println(Math.min(55, 100));
System.out.println(Math.abs(-77));
System.out.println(Math.ceil(3.55D));
System.out.println(Math.floor(3.55D));
System.out.println(Math.pow(2, 10));
System.out.println(Math.random());
System.out.println(Math.round(9.99D));
System.out.println(Math.sqrt(81));
System.out.println(Math.PI);
System.out.println(Math.E);

Note Notă

51
Math.PI indicates a reference to a constant. A constant is similar to a variable, but it has a value

assigned that cannot be changed. In addition, the names of constants are written in capital letters.

Math.PI indică o referință la o constantă. O constantă este similară cu o


variabilă, dar are o valoare atribuită care nu poate fi modificată. În plus, numele
constantelor sunt scrise cu majuscule.
The result of running the above code:

Rezultatul rulării codului de mai sus:

10
55
77
4.0
3.0
1024.0
0.20464094804059307
10
9.0
3.141592653589793
2.718281828459045

 this value differ for each run; the random() function returns a pseudo-random value within the
range of <0, 1).

• această
Your exercise now it to test the above for other values and using other methods.

valoare diferă pentru fiecare cursă; funcția random() returnează o valoare


pseudo-aleatorie în intervalul <0, 1).
Exercițiu-l acum pentru a testa cele de mai sus pentru alte valori și folosind alte
metode.

Wrappers of simple types


Apart from the simple types mentioned before, everything in Java is an object. For each simple type,

Ambalaje de tipuri simple


its equivalent, that is, a wrapper class, was created in Java.

În afară de tipurile simple menționate anterior, totul în Java este un obiect.


Pentru fiecare tip simplu, echivalentul său, adică o clasă wrapper, a fost creat în
Java.

52
sim compl
ple ex
type type

byt Byte
e

sho Short
rt

int Integ
er

lon Long
g

flo Float
at

dou Doubl
ble e

cha Chara
r cter

boo Boole
lea an
n

Wrappers of simple types Ambalaje de tipuri simple

Example of creation and application


byte byteValue = 56;
Byte byteObject = new Byte(byteValue);
short shortValue = 89;
Short shortObject = new Short(shortValue);
int intValue = 256;
Integer integerObject = new Integer(intValue);
long longValue = 5500L;
Long longObject = new Long(longValue);
float floatValue = 3.141592F;
Float floatObject = new Float(floatValue);

53
double doubleValue = 2.718281828D;
Double doubleObject = new Double(doubleValue);
char charValue = 'a';
Character characterObject = new Character(charValue);
boolean booleanValue = true;
Boolean booleanObject = new Boolean(booleanValue);

System.out.println("byteValue = " + byteValue);


System.out.println("byteObject = " + byteObject);
System.out.println("doubleValue = " + doubleValue);
System.out.println("doubleObject = " + doubleObject);
System.out.println("charValue = " + charValue);
System.out.println("characterObject = " + characterObject);
System.out.println("booleanValue = " + booleanValue);
System.out.println("booleanObject = " + booleanObject);

The result is:


byteValue = 56
byteObject = 56
doubleValue = 2.718281828
doubleObject = 2.718281828
charValue = a
characterObject = a
booleanValue = true
booleanObject = true

Variables xxxObject are object-oriented, we can execute methods on them, while we cannot do it
on xxxValue variables because they are variables of primitive types, that is, they only have a value.
Variabilele xxxObject sunt orientate pe obiecte, putem executa metode pe ele, în
timp ce nu o putem face pe variabilele xxxValue deoarece sunt variabile de
tipuri primitive, adică au doar o valoare.
Example of invocation of a few methods Exemplu de invocare a câtorva metode

double doubleValueFromByte = byteObject.doubleValue();


float floatValueFromInteger = integerObject.floatValue();
char charValueFromCharacter = characterObject.charValue();

boolean booleanValueFromBoolean = booleanObject.booleanValue();

double doubleValueFromByte = byteObject.doubleValue();


float floatValueFromInteger = integerObject.floatValue();
char charValueFromCharacter = characterObject.charValue();
boolean booleanValueFromBoolean = booleanObject.booleanValue();

Autoboxing and unboxing


Thanks to the built-in autoboxing and unboxing mechanisms, we can shorten the record and

conversion between primitive types and the corresponding object-oriented types (wrappers).

Datorită mecanismelor de autoboxing și unboxing încorporate, putem scurta

54
înregistrarea și conversia între tipurile primitive și tipurile corespunzătoare
orientate pe obiect (wrappers).
autoboxing automatic conversion of simple types into complex ones. Where, for example,

an Integer type is expected, we can provide e.g. value 5 or a variable of the int type, and it will be

automatically converted into the Integer type. The same applies to other types.

• autoboxing conversia automată a tipurilor simple în cele complexe. Acolo


unde, de exemplu, este de așteptat un tip întreg, putem furniza de ex. valoarea 5
sau o variabilă de tip int și va fi convertită automat în tipul Integer. Același
lucru este valabil și pentru alte tipuri.

Example of autoboxing.
Byte byteObject = 56;
Short shortObject = 89;
Integer integerObject = 256;
Long longObject = 5500L;
Float floatObject = 3.141592F;
Double doubleObject = 2.718281828D;
Character characterObject = 'a';
Boolean booleanObject = true;

- unboxing automatic conversion of object-oriented types to primitive ones. Where, for example,

a double type is expected, we can provide a variable of the Double type. It will be automatically

- unboxing conversia
converted into the double type. The same applies to other types.

automată a tipurilor orientate pe obiecte în cele primitive. Acolo unde, de


exemplu, este de așteptat un tip dublu, putem furniza o variabilă de tip Double.
Acesta va fi convertit automat în tipul dublu. Același lucru este valabil și pentru
alte tipuri.
Example of unboxing.
byte byteValue = new Byte((byte) 56);
short shortValue = new Short((short) 89);
int intValue = new Integer(256);
long longValue = new Long(5500L);
float floatValue = new Float(3.141592F);
double doubleValue = new Double(2.718281828D);
char charValue = new Character('a');
oolean booleanValue = new Boolean(true);

 constructor Byte(byte value) requires passing a byte type value - it is required to cast
the int type values constructorul Byte(valoarea octetului)
to byte: (byte)
necesită trecerea unei valori de tip octet - este necesar să turnați valorile
tipului int în octet: (octet)
constructor Short(short value) requires passing the short type value - it is also required to cast

the int type value to short: (short) • constructorul Short(valoare scurtă) necesită

55
trecerea valorii de tip scurt - este, de asemenea, necesar să turnați valoarea
tipului int la scurt: (short)

The ranges of values for basic types and their wrappers are the same. The difference lies in the

default values: for object-oriented types it is null, which has no equivalent (there is no such value)

Intervalele de valori pentru tipurile de bază și ambalajele acestora


in primitive types

sunt aceleași. Diferența constă în valorile implicite: pentru tipurile orientate pe


obiect este nul, care nu are echivalent (nu există o astfel de valoare) în tipurile
primitive.
When converting object-oriented types to primitive ones ( unboxing), pay attention to whether the


variable value is null. If this is the case, an error will appear.

Când convertiți tipurile orientate pe obiect în cele primitive (unboxing), acordați


atenție dacă valoarea variabilei este nulă. Dacă acesta este cazul, va apărea o
eroare.

An example of incorrect unboxing


Integer integerObject = null;
int intValue = integerObject;

Result:
Exception in thread "main" java.lang.NullPointerException

Important
Integer a = 0;
Integer b = null;

Variables a and b are not the same, 0 and null are completely different values.
Variable a indicates the object of the Integer class that stores value 0. Variable b does not
indicate any object!

Tip You can compare a variable b to a remote control without a receiver so it has nothing to

Variabilele a și b nu sunt aceleași, 0 și null sunt valori complet diferite.


control.

Variabila a indică obiectul clasei Integer care stochează valoarea 0. Variabila b


nu indică niciun obiect!
Sfat Puteți compara o variabilă b cu o telecomandă fără receptor, astfel încât să
nu aibă nimic de controlat.

Conversion of types Conversia tipurilor

56
Java copes quite well with adjusting the types. Only in some cases we must use additional

mechanisms to help it.Java se descurcă destul de bine cu ajustarea tipurilor. Doar în


unele cazuri trebuie să folosim mecanisme suplimentare pentru a o ajuta.
Diagram of conversion of types Diagrama de conversie a tipurilor

Let us look at types: byte, short, int and long. Their ranges increase: byte is included in short, short

in int, and int in long. Any value from the byte range will fit in the short range, etc. However, the

result for the other direction is not so obvious. For example, if you store a small value in an int type

variable (that fits in short or byte), you can cast an int type variable to a variable with a smaller

range.Să ne uităm la tipuri: byte, short, int și long. Intervalele lor cresc: byte este
inclus în short, short în int și int în long. Orice valoare din intervalul de octeți se
va potrivi în intervalul scurt, etc. Cu toate acestea, rezultatul pentru cealaltă
direcție nu este atât de evident. De exemplu, dacă stocați o valoare mică într-o
variabilă de tip int (care se potrivește în scurt sau octet), puteți transforma o
variabilă de tip int într-o variabilă cu un interval mai mic.
Conversions from a smaller range to a larger one happen automatically (this is indicated by the

direction of the arrows). Conversions from a larger range to a smaller one must be done consciously

using the projection operator: (<typ>).

Conversiile dintr-un interval mai mic la unul mai mare au loc automat (acest
lucru este indicat de direcția săgeților). Conversiile dintr-un interval mai mare la
unul mai mic trebuie făcute în mod conștient folosind operatorul de proiecție:
(<tip>).
Example of automatic conversions to extend the type
byte b = (byte) 56;
short s = (short) 89;
int i = b;
long l = s;
float f = i;

 byte type is extended automatically to the int type


 short type is extended automatically to the long type
 int type is extended automatically to the float type

 tipul octet este extins automat la tipul int


 • tipul scurt este extins automat la tipul lung
 • tipul int este extins automat la tipul float

Example of an explicit narrowing conversion


byte a = 127;
byte b = (byte) 130;
float c = 3.14F;

57
int d = 5;
byte e = (byte) d;
long f = (long) c;

System.out.println("a = " + a);


System.out.println("b = " + b);
System.out.println("f = " + f);

 there is no need to cast, because value (literal) 127 is in the range of the byte type
 casting is necessary because value 130 is out of range; pay attention to the result!
 casting is necessary, because Java can only “see” the int type of variable c (it “cannot see”
the value) and requires explicit casting
 casting is necessary, because the range is exceeded; besides, the fractional part is lost

nu este nevoie de cast, deoarece valoarea (literal) 127 este în


The result is as below:

intervalul tipului de octet


• turnarea este necesară deoarece valoarea 130 este în afara intervalului; atentie
la rezultat!
• castingul este necesar, deoarece Java poate „vedea” doar tipul int al variabilei
c („nu poate vedea” valoarea) și necesită casting explicit
• turnarea este necesară, deoarece intervalul este depășit; în plus, partea
fracționată se pierde
Rezultatul este ca mai jos:
a = 127
b = -126
f = 3

Conversion from complex types to simple types Conversia de la tipuri complexe la tipuri
simple
Objects of simple-type wrapper classes provide a number of methods for converting from complex

types to simple types.

Obiectele claselor wrapper de tip simplu oferă o serie de metode de conversie de


la tipuri complexe la tipuri simple.

 Byte, Short, Integer, Long, Float, Double


 byteValue()
 shortValue()
 intValue()
 floatValue()
 doubleValue()
 Character
 charValue()

 Boolean
 booleanValue()

Wrapper classes offer methods that enable creating objects based on values or simple-type
variables.

58
 Byte.valueOf(byte b) creates a Byte class object based on the b value
 Short.valueOf(short s) creates a Short class object based on the s value
 Integer.valueOf(int i) creates an Integer class object based on the i value
 Long.valueOf(long l) creates a Long class object based on the l value
 Float.valueOf(float f) creates a Float class object based on the f value
 Double.valueOf(double d) creates a Double class object based on the d value
 Boolean.valueOf(boolean b) creates a Boolean class object based on the b value

 Clasele Wrapper oferă metode care permit crearea de obiecte bazate pe


valori sau variabile de tip simplu.
 • Byte.valueOf(byte b) creează un obiect de clasă Byte pe baza valorii b
 • Short.valueOf(short s) creează un obiect de clasă Short pe baza valorii s
 • Integer.valueOf(int i) creează un obiect de clasă Integer pe baza valorii i
 • Long.valueOf(long l) creează un obiect de clasă Long pe baza valorii l
 • Float.valueOf(float f) creează un obiect de clasă Float pe baza valorii f
 • Double.valueOf(double d) creează un obiect de clasă Double pe baza
valorii d
 • Boolean.valueOf(boolean b) creează un obiect de clasă boolean pe baza
valorii b
Wrapper classes (except Character) provide additional methods for converting values stored in

Clasele
a String type to a primitive type. These are methods in the parseXXX(String s) form.

Wrapper (cu excepția Character) oferă metode suplimentare pentru conversia


valorilor stocate într-un tip String într-un tip primitiv. Acestea sunt metode în
forma parseXXX(String s).
Example of converting values stored in String
System.out.println(Boolean.parseBoolean("true"));
System.out.println(Boolean.parseBoolean("TRUE"));
System.out.println(Boolean.parseBoolean("1"));
System.out.println(Boolean.parseBoolean("0"));
System.out.println(Integer.parseInt("123"));
System.out.println(Double.parseDouble("3.1415"));

Result:

Wynik
true
true
false
false
123
3.1415

Summary
What have you learned in this chapter?

59
How do we divide data types in Java? We divide them into simple (primitive) and complex (object-
oriented, reference) types.

What are the differences between simple and complex types? Simple types have only a value.
Complex types, in addition to storing value, provide methods for operations on them.

What is a variable? A variable is like a “place”, or a “container”, for data. A variable always has its
own type and only data of this type can be stored in it.

How do we compare variables (values) of primitive types? We use the == sign,


e.g., a == 5 or a == c.

How do we compare variables of object-oriented types? We use the equals() method.

How can I check whether the object variable is null? By comparing the variable to the null value,
e.g. a == null.

What types of integers are offered by Java? There are four integer types in
Java: byte, short, int and long. All of them are signed (they have a sign). The long type is marked
by adding letter L to the value.

Is any of the integer types default? Yes, it is the int type.

What floating point types are offered by Java? There are two floating point types: float and double;
float is of single precision, while double is of double precision. The float type is marked by adding
letter F to the value, while the double type is marked by adding letter D.

rezumat
Ce ai învățat în acest capitol?
Cum împărțim tipurile de date în Java? Le împărțim în tipuri simple (primitive)
și complexe (orientate pe obiecte, de referință).
Care sunt diferențele dintre tipurile simple și complexe? Tipurile simple au doar
o valoare. Tipurile complexe, pe lângă stocarea valorii, oferă metode pentru
operații asupra lor.
Ce este o variabilă? O variabilă este ca un „loc” sau un „container” pentru date.
O variabilă are întotdeauna propriul tip și numai datele de acest tip pot fi stocate
în ea.
Cum comparăm variabilele (valorile) tipurilor primitive? Folosim semnul ==, de
exemplu, a == 5 sau a == c.
Cum comparăm variabilele tipurilor orientate pe obiecte? Folosim metoda
equals().
Cum pot verifica dacă variabila obiect este nulă? Prin compararea variabilei cu
valoarea nulă, de ex. a == nul.

60
Ce tipuri de numere întregi sunt oferite de Java? Există patru tipuri de numere
întregi în Java: byte, short, int și long. Toate sunt semnate (au semn). Tipul lung
este marcat prin adăugarea literei L la valoare.
Este vreunul dintre tipurile de întregi implicite? Da, este de tip int.
Ce tipuri de virgulă mobilă sunt oferite de Java? Există două tipuri de virgulă
mobilă: float și double; float este de precizie simplă, în timp ce dublu este de
precizie dublă. Tipul float este marcat prin adăugarea literei F la valoare, în timp
ce tipul dublu este marcat prin adăugarea literei D.
What is the character type? The character (char) type enables storing exactly one character in the
variable. These are characters in the Unicode standard, e.g. 'a', 'Z' or ' '. The char type is a type
without a sign (unsigned), which means that the cores are non-negative numbers in the range
from 0 to 65556.

What is the logical type? The logical type (boolean) can have only two values: false or true. It is used
to check logic conditions.

What are object-oriented types? These are types that in addition to storing values also provide
operations (methods). Java provides several thousand (over 4,000) types. Developers around the
world provide more than ten hundred thousand types. When creating a class, you also create a new
type.

What is the String class for? The String class is used for storing strings and provides methods for
operations on them. It features a short form of declaration and initialization:
String text = "I love Java!";

What does it mean that the String is immutable?** This means that the class does not change its
status, but only creates a new instance with the changed value. If you perform an operation on
the String class that modifies data (changes the string), then the original value is not actually
changed; the method returns only the changed string.

What classes can be used to support the date and time? These can
be LocalDate, LocalTime or LocalDateTime classes. Also older classes can be often
encountered: Date and Calendar.

What class can you use for simple mathematical operations? It is the Math class.

What happens when I try to invoke a method on a variable that is null? When attempting to invoke
a method on a null reference (variable), a program runtime error will occur. In detail,
the NullPointerException will appear.

What are simple type wrappers? These are curtain classes for all simple types available in Java.
They expand their capabilities by providing methods; they are a bridge between simple and object
types.

What is autoboxing and unboxing? Autoboxing is a mechanism for automatic conversion of


simple types into complex ones. Unboxing is a mechanism that works in the opposite direction.
**Note!**

The mechanism may return an error if you try to convert a variable that stores the null value to a

simple type variable. In simple types there is no equivalent of the null value! Care este tipul

61
de caracter? Tipul de caracter (char) permite stocarea exact unui caracter în
variabilă. Acestea sunt caractere în standardul Unicode, de ex. „a”, „Z” sau „”.
Tipul char este un tip fără semn (fără semn), ceea ce înseamnă că nucleele sunt
numere nenegative în intervalul de la 0 la 65556.
Care este tipul logic? Tipul logic (boolean) poate avea doar două valori: fals sau
adevărat. Este folosit pentru a verifica condițiile logice.
Ce sunt tipurile orientate pe obiecte? Acestea sunt tipuri care, pe lângă stocarea
valorilor, oferă și operații (metode). Java oferă câteva mii (peste 4.000) de
tipuri. Dezvoltatorii din întreaga lume oferă mai mult de zece sute de mii de
tipuri. Când creați o clasă, creați și un nou tip.
Pentru ce este clasa String? Clasa String este folosită pentru stocarea șirurilor de
caractere și oferă metode pentru operații asupra acestora. Are o formă scurtă de
declarare și inițializare:
String text = „Îmi place Java!”;
Ce înseamnă că șirul este imuabil?** Aceasta înseamnă că clasa nu își schimbă
starea, ci doar creează o instanță nouă cu valoarea modificată. Dacă efectuați o
operațiune asupra clasei String care modifică datele (schimbă șirul), atunci
valoarea inițială nu este de fapt modificată; metoda returnează doar șirul
modificat.
Ce clase pot fi folosite pentru a susține data și ora? Acestea pot fi clase
LocalDate, LocalTime sau LocalDateTime. De asemenea, pot fi întâlnite des
clase mai vechi: Data și Calendarul.
Ce clasă poți folosi pentru operații matematice simple? Este clasa de
matematică.
Ce se întâmplă când încerc să invoc o metodă pe o variabilă care este nulă?
Când încercați să invocați o metodă pe o referință nulă (variabilă), va apărea o
eroare de rulare a programului. În detaliu, va apărea NullPointerException.
Ce sunt ambalajele de tip simplu? Acestea sunt clase cortina pentru toate tipurile
simple disponibile în Java. Ei își extind capacitățile furnizând metode; sunt o
punte între tipurile simple și obiecte.
Ce este autoboxing și unboxing? Autoboxing este un mecanism de conversie
automată a tipurilor simple în cele complexe. Unboxing-ul este un mecanism
care funcționează în direcția opusă.
**Notă!**

62
Mecanismul poate returna o eroare dacă încercați să convertiți o variabilă care
stochează valoarea nulă într-o variabilă de tip simplu. În tipurile simple nu
există un echivalent al valorii nule!
What is conversion of types? Conversion of types is the assignment of one type to another. If you

convert a narrower type into a wider one (e.g. short to int), then such conversion is safe. It is

called casting up. If, on the other hand, you convert a wider type into a narrower one, then such

conversion can be dangerous. In such cases you should use the casting operator: (<type on which you

cast>).Ce este conversia tipurilor? Conversia tipurilor este atribuirea unui tip la
altul. Dacă convertiți un tip mai restrâns într-unul mai larg (de exemplu, scurt în
int), atunci o astfel de conversie este sigură. Se numește turnare. Dacă, pe de
altă parte, convertiți un tip mai larg într-unul mai îngust, atunci o astfel de
conversie poate fi periculoasă. În astfel de cazuri, ar trebui să utilizați operatorul
de casting: (<tipul pe care ați proiectat>).

Exercises
 Create (declare and initialize) several variables of primitive types based on things that
surround you or can be found in your industry. Think over which type to use. Display the values.
 Try to assign a value out of range for the variable. See the result displayed. Try using casing
operator ( ).
 Use wrapper classes and try to create object-oriented equivalents for all variables (of primitive
types) from the previous exercise.
 Test the chosen methods (xxValue(), valueOf() and parseXXX()) from wrappers of simple types.
 Write a program (create a new class with the main method) that displays Hello, <Your name>! on
the screen. Make your name stored in a variable of the String type.
 Write a program that displays your business card like the one below:
 ############################
 # #
 # John Smith #
 # Sesame Street 345/7b #
 # New York 10019 #
 # #
 ############################

 use different signs, for instance:


 - for horizontal lines
 | for vertical lines
 / i \ (lub +) for corners
 make the horizontal line be stored in a variable; you will be able to declare its value only
once , but use it twice

make the characters for vertical lines and corners also be stored in variables Exerciții

63
• Creați (declarați și inițializați) mai multe variabile de tipuri primitive pe baza
lucrurilor care vă înconjoară sau care pot fi găsite în industria dvs. Gândiți-vă ce
tip să utilizați. Afișați valorile.
• Încercați să atribuiți o valoare în afara intervalului pentru variabilă. Vedeți
rezultatul afișat. Încercați să utilizați operatorul de carcasă ( ).
• Folosiți clase wrapper și încercați să creați echivalente orientate pe obiecte
pentru toate variabilele (de tipuri primitive) din exercițiul anterior.
• Testați metodele alese (xxValue(), valueOf() și parseXXX()) din wrapper-uri
de tipuri simple.
• Scrieți un program (creați o nouă clasă cu metoda principală) care să afișeze
Bună ziua, <Numele tău>! pe ecran. Faceți numele dvs. stocat într-o variabilă de
tip String.
• Scrieți un program care să vă afișeze cartea de vizită ca cel de mai jos:
• ############################
•##
• # John Smith #
• # Sesame Street 345/7b #
• # New York 10019 #
•##
• ############################
• utilizați semne diferite, de exemplu:
• - pentru linii orizontale
• | pentru linii verticale
• / i \ (lub +) pentru colțuri
• face ca linia orizontală să fie stocată într-o variabilă; veți putea să-i declarați
valoarea o singură dată, dar să o utilizați de două ori
• face ca caracterele pentru liniile verticale și colțurile să fie și ele stocate în
variabile
 create further variables for the name, surname, street, building number, flat number, zip
code
 add a variable (and its display) that stores the phone number
 suggest further variables, e.g. area code, address (concatenation of street , building
number and flat number)
 add boolean type variable specifying whether to display the frame; if it has a false value,
then do not display it
 create any variable and try to use it without initialization; observe the error
 Create a few String variables and test the presented methods that operate on strings.

64
 Create a few variables of the LocalDate, LocalTime and LocalDateTime types and test invoking a few
methods on them. Display the results.
 Test the methods of the Math class.

 creați alte variabile pentru numele, prenumele, strada, numărul clădirii,


numărul apartamentului, codul poștal
 • adăugați o variabilă (și afișarea acesteia) care stochează numărul de
telefon
 • sugerează alte variabile, de ex. prefix, adresa (concatenarea străzii,
numărul clădirii și numărul apartamentului)
 • adăugarea variabilei de tip boolean specificând dacă se va afișa cadrul;
dacă are o valoare falsă, atunci nu o afișați
 • creați orice variabilă și încercați să o utilizați fără inițializare; observați
eroarea
 • Creați câteva variabile String și testați metodele prezentate care
operează pe șiruri.
 • Creați câteva variabile ale tipurilor LocalDate, LocalTime și
LocalDateTime și testați invocând câteva metode pe ele. Afișați
rezultatele.
 • Testați metodele clasei de matematică.
Operators
You can perform various actions and operations on variables and literals.

Arithmetic and concatenation operators


Arithmetic operations are used to perform mathematical operations. In the case of operations for
different types, the result is the wider of types.

 + addition, e.g. 5 + 4, x + y
 - subtraction, e.g. 9 - 7, x - y
 * multiplication, e.g. 3 * 6, x * y
 / division, e.g. 15 / 3, x / y
 % remainder (modulo), e.g. 13 % 5, x % y
 ++ increase by 1 (increment), e.g. x``+`` (*post-increment*), ``+``x (pre-increment)
 -- decrease by 1 (decrement), e.g. x``--`` (post-decrement), ``--``x (pre-decrement)

 =
x = 10; (assigning value 10 to variable x; unlike in mathematics where it means equality)
 +=
x += 10; it is a shortened record of x = x + 10;
 -=
x -= it is a shortened record of x = x * 10;

65
 *=
x \*= it is a shortened record of x = x * 10;
 /=
x /= 10; it is a shortened record of x = x / 10;

%=

Operatori
x %= 10; it is a shortened record of x = x % 10;

Puteți efectua diverse acțiuni și operații asupra variabilelor și literalelor.


Operatori aritmetici și de concatenare
Operațiile aritmetice sunt folosite pentru a efectua operații matematice. În cazul
operațiunilor pentru diferite tipuri, rezultatul este mai larg dintre tipuri.
• + adaos, de ex. 5 + 4, x + y
• - scăderea, de ex. 9 - 7, x - y
• * înmulțire, de ex. 3 * 6, x * y
• / împărțire, de ex. 15 / 3, x / y
• % rest (modulo), de ex. 13 % 5, x % y
• ++ crește cu 1 (increment), de ex. x``+`` (*post-increment*), ``+``x (pre-
increment)
• -- scădere cu 1 (scădere), de ex. x``--`` (post-decrementare), ``--``x (pre-
decrementare)
•=
x = 10; (atribuirea valorii 10 variabilei x; spre deosebire de matematică, unde
înseamnă egalitate)
• +=
x += 10; este o înregistrare scurtată de x = x + 10;
• -=
x -= este o înregistrare scurtată de x = x * 10;
• *=
x \*= este o înregistrare scurtată de x = x * 10;
• /=
x /= 10; este o înregistrare scurtată de x = x / 10;
• %=
x %= 10; este o înregistrare scurtată de x = x % 10;

Example of pre- and post-increment and decrement


int x = 5;
System.out.print(x++);
System.out.print(++x);

66
System.out.print(--x);
System.out.print(x--);

 first, value x will be assigned to the print() function, then displayed, and then increased by 1
 value x will be increased by 1, then transferred to the function and then displayed

Result:

5766mai întâi, valoarea x va fi atribuită funcției print(), apoi afișată și apoi mărită
cu 1
• valoarea x va fi mărită cu 1, apoi transferată în funcție și apoi afișată
Rezultat:
5766

Operator of String concatenation


Operator + for the String types has a different action. It connects (concatenates) strings together.

Examples of String concatenation


String text = "Alice" + " " + "has" + " " + "a" + "cat";
String anotherText = text + "and a cat has Alice!"
int count = 5;
System.out.println("Alice has" + count + "cats");

 combining "Alice" with " ", and then with "has" etc.
 combining a String text type variable with the text "and a cat has Alice!"

combining two texts with the int variable, it has been automatically converted into String

Operator de concatenare șiruri


Operatorul + pentru tipurile String are o acțiune diferită. Conectează
(concatenează) șiruri împreună.
Exemple de concatenare șiruri
String text = "Alice" + " " + "are" + " " + "a" + "pisica";
String anotherText = text + "și o pisică are Alice!"
număr int = 5;
System.out.println("Alice are" + count + "pisici");
• combinarea „Alice” cu „ „, apoi cu „are” etc.
• combinarea unei variabile de tip text String cu textul „și o pisică are Alice!”
• combinând două texte cu variabila int, aceasta a fost convertită automat în
String

Comparison operators
67
Operators of comparison (relation) are used for comparing values. The result of such operation is a

Operatori de comparare
logical value true or false.

Operatorii de comparație (relație) sunt utilizați pentru compararea valorilor.


Rezultatul unei astfel de operațiuni este o valoare logică adevărată sau falsă.
 ==
equal, e.g. 5 == 6, x == y, 5 == y
 !=
not equal, e.g. 5 != 6, x != y, 5 != x
 <
less than, e.g. 5 < 6, x < y, 5 < x
 \<=
less than or equal to, e.g. 5 \<= 6, x \<= y, 6 \<= y
 >
greater than, e.g. 5 > 6, x > y, 5 > x
 >=
greater than or equal, e.g. 5 >= 6, x >= y, 6 >= y

Examples of the use of comparison operators


int i = 8, j = 8;
System.out.println(i == j);
System.out.println(i != j);
System.out.println(i < 24);
System.out.println(j != 5);
System.out.println(i >= 8);

Result:
true
false
true
true
true

Example of comparing simple types with object-oriented types


int fiveValue = 5;
Integer fiveObject = 5;
Integer fiveObjectByNew = new Integer(5);
Integer anotherFiveObjectByNew = new Integer(5);

System.out.println(fiveValue == fiveObject);
System.out.println(fiveValue == fiveObjectByNew);
System.out.println(fiveObject == fiveObjectByNew);
System.out.println(fiveObjectByNew == anotherFiveObjectByNew);

System.out.println(fiveObject.equals(fiveObjectByNew));
System.out.println(fiveObject.equals(anotherFiveObjectByNew));
System.out.println(fiveObjectByNew.equals(anotherFiveObjectByNew));

int twoHundredValue = 200;


Integer twoHundredObject = 200;
System.out.println(twoHundredValue == twoHundredObject);

Result:
true
true
false
false
true

68
true
true
false

The results may be a bit surprising. Particularly it may come as a surprise that for value 5 it is true,
while for value 200 it is false. Explanation of this issue goes beyond the scope of this Handbook.

 Primitive types are compared using the == sign


 Object-oriented types are compared using the equals() method

When comparing a primitive type with an object-oriented type, we also use the equals() method to

Rezultatele
invoke it on an object variable, and pass a primitive type variable as an argument

pot fi puțin surprinzătoare. În special, poate fi surprinzător faptul că pentru


valoarea 5 este adevărat, în timp ce pentru valoarea 200 este fals. Explicația
acestei probleme depășește scopul acestui manual.
• Tipurile primitive sunt comparate folosind semnul ==
• Tipurile orientate pe obiecte sunt comparate folosind metoda equals().
• Când comparăm un tip primitiv cu un tip orientat pe obiect, folosim, de
asemenea, metoda equals() pentru a-l invoca pe o variabilă obiect și trecem o
variabilă de tip primitiv ca argument

Important

Important
Operator = means assignment Operator == means comparison

Operator = înseamnă atribuire Operator == înseamnă comparație

int i = 8, j = 8;
Integer k = new Integer(8);
Integer l = new Integer(8);
System.out.println(i == j);
System.out.println(k.equals(l));
System.out.println(l.equals(j));
Result:
true
true
true
true

Logical operators
Logical operators are used to combine logical conditions. The result is also a logical

Operatori logici
value true or false.

Operatorii logici sunt utilizați pentru a combina condiții logice. Rezultatul este,
de asemenea, o valoare logică adevărată sau falsă.

69
 &&
logical conjunction, AND, e.g. x && y

x y x &&
y

true tru true


e

true fal fals


se e

fals tru fals


e e e

fals fal fals


e se e

 The truth table for the && operation


 ||
logical alternative, OR, e.g. x || y

x y x \|\
|y

tru tru true


e e

tru fal true


e se

fal tru true


se e

fal fal fals


se se e

 Truth table for the || operation


 !
logical negation, NOT, e.g. ``!``x

70
x ``!``x

tru fal
e se

fal tru
se e

 Truth table for the ! operation

Summary
What have you learned in this chapter?

What types of operators are there in Java?

Operators are divided into:

 arithmetic
 comparisons
 logical

What arithmetic operators do we use? rezumat


Ce ai învățat în acest capitol?
Ce tipuri de operatori există în Java?
Operatorii sunt împărțiți în:
• aritmetic
• comparaţii
• logic
Ce operatori aritmetici folosim?
Arithmetic operators are as follows:


 — addition

 — subtraction

 — multiplication
 / — division
 % — remainder (modulo)
 ++ — increase by 1
 -- — decrease by 1

What is the modulo (%) operator?

71
The modulo operator (%) returns the remainder of the division. For instance:

 7 % 5 = 2 (digit 5 can be included in digit 7 once, and the “left over” is 2)


 7 % 9 = 7 (digit 9 can be included in digit 9 zero times and the “left over” is 7)

What are the ++ and -- operators and how do they operate?

These are operators that (respectively) increase by 1 and decrease by 1.

 ++ - increase by 1 (increment); it can be x++ (post-increment) or ++x (pre-increment)


 -- - decrease by 1 (decrement); it can be x-- (post-decrement) or --x (pre-decrement)

 Operatorii aritmetici sunt după cum urmează:


 •
 • — adaos
 •
 • — scădere
 •
 • — înmulțire
 • / - Divizia
 • % — rest (modulo)
 • ++ — crește cu 1
 • -- — scade cu 1
 Ce este operatorul modulo (%)?
 Operatorul modulo (%) returnează restul diviziunii. De exemplu:
 • 7 % 5 = 2 (cifra 5 poate fi inclusă în cifra 7 o dată, iar „rămăsul” este 2)
 • 7 % 9 = 7 (cifra 9 poate fi inclusă în cifra 9 de zero ori, iar „rămăsul”
este 7)
 Care sunt operatorii ++ și -- și cum funcționează aceștia?
 Aceștia sunt operatori care (respectiv) cresc cu 1 și scad cu 1.
 • ++ - crește cu 1 (increment); poate fi x++ (post-increment) sau ++x (pre-
increment)
 • -- - scade cu 1 (scade); poate fi x-- (post-decrementare) sau --x (pre-
decrementare)
What are abbreviated assignment operators?

These are operators that enable performing an action and changing the value of the variable at the
same time.

 += - addition with assignment


72
 = - subtraction with assignment
 *= - multiplication with assignment
 /= - division with assignment
 %= - modulo with assignment

How does the “Strings” concatenation operator work?

The operator of Strings concatenation (+) combines two texts together to form one new text.

What are the comparison operators?

The comparison (relation) operators are as follows:

 == - equal to
 != - not equal to
 < - less than
 <= - less than or equal to

 greater than

Ce sunt operatorii de atribuire abreviați?


= - greater than or equal to

Aceștia sunt operatori care permit efectuarea unei acțiuni și modificarea valorii
variabilei în același timp.
• += - adunare cu atribuire

• = - scădere cu atribuire
• *= - înmulțire cu atribuire
• /= - împărțire cu atribuire
• %= - modulo cu atribuire
Cum funcționează operatorul de concatenare „Șiruri”?
Operatorul de concatenare șiruri de caractere (+) combină două texte împreună
pentru a forma un text nou.
Care sunt operatorii de comparare?
Operatorii de comparație (relație) sunt următorii:
• == - egal cu
• != - nu este egal cu
• < - mai puțin decât
• <= - mai mic sau egal cu

• mai mare ca
• = - mai mare sau egal cu
What are the logical operators?

73
The logical operators are as follows:

 && - logical AND (conjunction)


 || - logical OR (alternative)

Care sunt operatorii logici?


! - NOT, logical false (negation)

Operatorii logici sunt următorii:


• && - AND logic (conjuncție)
• || - SAU logic (alternativă)
• ! - NU, fals logic (negație)

Exercises

 Declare a few variables of various types and test invoking the following operations on
them: +, -, *, /, %.
 Declare an int type variable and test the ++ and -- operations both in their pre- and post-
variations.
 Declare two variables corresponding to the sides of a rectangle and count its field and
circumference.
 Declare two variables corresponding to the sides of a right-angled triangle and calculate its
field.
 Declare the variable corresponding to the diameter of a circle and count its field and
circumference.
 Declare three variables corresponding to the sides of a triangle and check whether it is right-
angled.
 Declare a variable corresponding to age; use a ternary operator to display: adult or underage.

 Exerciții
 • Declarați câteva variabile de diferite tipuri și testați invocând
următoarele operații asupra lor: +, -, *, /, %.
 • Declarați o variabilă de tip int și testați operațiile ++ și -- atât în pre- și
post-variații.
 • Declarați două variabile corespunzătoare laturilor unui dreptunghi și
numărați câmpul și circumferința acestuia.
 • Declarați două variabile corespunzătoare laturilor unui triunghi
dreptunghic și calculați câmpul acestuia.
 • Declarați variabila corespunzătoare diametrului unui cerc și numărați
câmpul și circumferința acestuia.
 • Declarați trei variabile corespunzătoare laturilor unui triunghi și
verificați dacă acesta este dreptunghic.

74
 • Declararea unei variabile corespunzătoare vârstei; utilizați un operator
ternar pentru a afișa: adult sau minor.

Conditional statements
Until now, the code we wrote was executed sequentially from top to bottom; unconditionally.

However, in programming the logics of our application very often depends on some conditions. For

example, if the amount to be paid exceeds 1000, we would like to charge a discount. Otherwise, the

amount will remain unchanged. To accomplish this, we can use conditional statements.

Declarații condiționale
Până acum, codul scris de noi era executat secvenţial de sus în jos;
necondiţionat. Cu toate acestea, în programare, logica aplicației noastre depinde
foarte des de anumite condiții. De exemplu, dacă suma care trebuie plătită
depășește 1000, am dori să percepem o reducere. În caz contrar, suma va
rămâne neschimbată. Pentru a realiza acest lucru, putem folosi instrucțiuni
condiționale.

The if statement
The if conditional statement checks the logical condition contained between brackets ( and ). If
the condition is met (is true), the statement executes the code contained between
brackets { and }.

Structure of the if statement


if (<logical-condition>) {
// operations
}

Example
if (totalPrice > 1000) {
totalPrice = totalPrice - discount;
}
Note

Please note the indentation of the code in the line in the if body. Similarly as in the code in
the main function, also in conditional statements indentation is applied.

A logical condition is a statement which after calculation returns value true or false. It is placed in

round brackets. Examples of correct logical conditions are as follows: Declarația if

75
Instrucțiunea condiționată if verifică condiția logică cuprinsă între paranteze ( și
). Dacă condiția este îndeplinită (este adevărată), instrucțiunea execută codul
conținut între paranteze { și }.
Structura declarației if
if (<condiție-logică>) {
// operațiuni
}
Exemplu
dacă (totalPrice > 1000) {
totalPrice = totalPrice - discount;
}
Notă
Vă rugăm să rețineți indentarea codului în rândul din corpul if. La fel ca și în
codul din funcția principală, și în instrucțiunile condiționate se aplică
indentarea.
O condiție logică este o declarație care, după calcul, returnează valoarea
adevărată sau falsă. Este plasat în paranteze rotunde. Exemple de condiții logice
corecte sunt următoarele:

 age > 5

 price == 7.45

 dayNr != 7

 !active (where active is of the boolean type)

 true

 false

Examples of incorrect logical conditions:

 age + 1

 price = 7.45

 dayNr % 2

 1

 "Alice has a cat"

A logical condition can be complex and consist of several expressions, but the result must still be a

O condiție logică poate fi complexă și constă din mai multe expresii,


logical value.

dar rezultatul trebuie să fie totuși o valoare logică.

76
Example of a complex logic condition
if ((age > 18 && dayNr == 6) || amount > 1000) {

The if - else statement


The code after the else statement (included in brackets { and }) is invoked when the logical
condition of the if statement is not met (is false).

Structure of the if - else statement


if (<logical-condition>) {
// operations
} else {
// operations
}

Example of the if - else statement


if (age >= 18) {
System.out.println("You are adult");
} else {
System.out.println("You are underage");
}

Declarația if - else
Codul de după instrucțiunea else (inclusă între paranteze { și }) este invocat
atunci când condiția logică a instrucțiunii if nu este îndeplinită (este falsă).
Structura declarației if - else
if (<condiție-logică>) {
// operațiuni
} altfel {
// operațiuni
}
Exemplu de declarație if - else
dacă (vârsta >= 18) {
System.out.println(„Sunteți adult”);
} altfel {
System.out.println(„Sunteți minor”);
}

The if - else if - else statement


The else if structure is used to combine conditional statements and works just like the connection
of if and else.

77
Structure of the if - else if - else statement
if (<logical-condition- 1>) {
// operations
} else if (<logical-condition- 2>) {
// operations

...

} else {
// operations
}

Declarația if - else if - else


Structura else if este folosită pentru a combina instrucțiunile condiționate și
funcționează la fel ca conexiunea dintre if și else.
Structura instrucțiunii if - else if - else
if (<condiție-logică-1>) {
// operațiuni
} else if (<condiție-logică- 2>) {
// operațiuni

...

} altfel {
// operațiuni
}

Example of the if - else if - else statement


if (dayOfTheWeekNr == 7) {
System.out.println("Today is Sunday - holiday!");
} else if (dayOfTheWeekNr == 6) {
System.out.println("Today is Saturday - free!");
} else {
System.out.println("Today is a business day - work!");
}

Braces { and } are not required, but it is ADVISABLE to ALWAYS use them, even when the if is
followed by one statement only. A code with one statement after if will be working properly.
if (totalPrice > 1000)
totalPrice = totalPrice - discount;

But if we would like to add, for example, a discount from the seller in the next line, unfortunately
the code will not work as we would expect—the discount from the seller will always be counted
unconditionally. In addition, the indentation in the second line of the if statement can be
confusing.
if (totalPrice > 1000)
totalPrice = totalPrice - discount;
totalPrice = totalPrice - dealersDiscount;
To make the code work as intended, we must enclose it in brackets.
if (totalPrice > 1000) {
totalPrice = totalPrice - discount;

78
totalPrice = totalPrice - dealersDiscount;
}

Exemplu de instrucțiune if - else if - else


dacă (dayOfTheWeekNr == 7) {
System.out.println("Astăzi este duminică - sărbătoare!");
} else if (dayOfTheWeekNr == 6) {
System.out.println("Astăzi este sâmbătă - gratuit!");
} altfel {
System.out.println("Astăzi este o zi lucrătoare - lucru!");
}
Acoladele { și } nu sunt necesare, dar este RECOMANDAT să le folosiți
ÎNTOTDEAUNA, chiar și atunci când if este urmat de o singură instrucțiune.
Un cod cu o declarație după if va funcționa corect.
dacă (Preț total > 1000)
totalPrice = totalPrice - discount;
Dar dacă dorim să adăugăm, de exemplu, o reducere de la vânzător în rândul
următor, din păcate, codul nu va funcționa așa cum ne-am aștepta - discountul
de la vânzător va fi întotdeauna numărat necondiționat. În plus, indentarea din a
doua linie a instrucțiunii if poate fi confuză.
dacă (Preț total > 1000)
totalPrice = totalPrice - discount;
totalPrice = totalPrice - dealersDiscount;
Pentru ca codul să funcționeze așa cum este prevăzut, trebuie să-l închidem între
paranteze.
dacă (totalPrice > 1000) {
totalPrice = totalPrice - discount;
totalPrice = totalPrice - dealersDiscount;
}
Ternary operator
A ternary operator is also called a conditional operator. It is similar to the if-else statement, but it
returns the value. In addition, it can be seen as an abbreviated record of this statement.

Structure of a ternary operator


<logical-expression> ? <value-1> : <value-2>

If the value of the logical expression is true, the value-1 expression is calculated and the operator
returns its result. If the logical expression is false, then the value-2 expression is calculated and
the operator returns its result.

79
Example of a ternary operator
String text = age >= 18 ? "adult" : "“underage";
System.out.println("You are" + text);

The above logic can also be expressed with the use of the if-else statement.

Example of the if - else statement corresponding to the ternary operator

Operator ternar
Un operator ternar se mai numește și operator condiționat. Este similar cu
instrucțiunea if-else, dar returnează valoarea. În plus, poate fi văzută ca o
înregistrare prescurtată a acestei declarații.
Structura unui operator ternar
<expresie-logică> ? <valoare-1> : <valoare-2>
Dacă valoarea expresiei logice este adevărată, expresia valoare-1 este calculată
și operatorul returnează rezultatul acesteia. Dacă expresia logică este falsă,
atunci expresia valoare-2 este calculată și operatorul returnează rezultatul
acesteia.
Exemplu de operator ternar
String text = vârsta >= 18 ? „adult” : „„minor”;
System.out.println(„Sunteți” + text);
Logica de mai sus poate fi exprimată și prin utilizarea declarației if-else.
Exemplu de instrucțiune if - else corespunzătoare operatorului ternar

String text;
if (age >= 18) {
text = "adult";
} else {
text = "“underage";
}
System.out.println("You are " + text);
<logical-expression> ? <value-1> : <value-2>

Usually value-1 and value-2 are of the same type, e.g. int or String as in the previous example.
However, in the example below:
System.out.println(true ? 1 : 3.1415);
although the logical expression is true (is unconditionally true), the screen will display
value 1.0 and not 1 as initially expected. The ternary operator works in such a way that the
returned type is the common (narrowest) type, in this case it is double. If we would like to assign
the result of this operation, we could write, for example:
double result = true ? 1 : 3.1415;

De obicei, valoarea-1 și valoarea-2 sunt de același tip, de ex. int sau String ca în
exemplul anterior. Cu toate acestea, în exemplul de mai jos:
System.out.println(true ? 1 : 3,1415);

80
deși expresia logică este adevărată (este adevărată necondiționat), ecranul va
afișa valoarea 1.0 și nu 1 așa cum se aștepta inițial. Operatorul ternar
funcționează în așa fel încât tipul returnat să fie tipul comun (cel mai îngust), în
acest caz este dublu. Dacă dorim să atribuim rezultatul acestei operații, am putea
scrie, de exemplu:
rezultat dublu = adevărat? 1: 3,1415;

The switch statement


Another type of conditional statement is the switch statement. It is useful in situations where there
are many options to choose from; then the if - else statement may be ineffective.

Declarația switch
Structure of the switch statement

Un alt tip de instrucțiune condiționată este instrucțiunea switch. Este util în


situațiile în care există multe opțiuni din care să alegeți; atunci declarația if -
else poate fi ineficientă.
Structura instrucțiunii switch

switch (<variable>) {
case <value-1>:
// operations
break;
case <value-2>:
// operations
break;

...

default:
// operations
}

Example of rolling the dice


int valueOnTheDice = 5;
switch (valueOnTheDice) {
case 1:
System.out.println("Outcome is 1");
break;
case 2:
System.out.println("Outcome is 2");
break;
case 3:
System.out.println("Outcome is 3");
break;
case 4:
System.out.println("Outcome is 4");
break;
case 5:
System.out.println("Outcome is 5");
break;

81
case 6:
System.out.println("Outcome is 6");
break;
default:
System.out.println("Error or the dice has landed on the edge!");
}
For the given value of the valueOnTheDice = 5 variable, the following result will be displayed on
the screen:
Outcome is 5

Exemplu de aruncare a zarurilor


int valueOnTheDice = 5;
comutați (valueOnTheDice) {
cazul 1:
System.out.println("Rezultatul este 1");
pauză;
cazul 2:
System.out.println("Rezultatul este 2");
pauză;
cazul 3:
System.out.println("Rezultatul este 3");
pauză;
cazul 4:
System.out.println("Rezultatul este 4");
pauză;
cazul 5:
System.out.println("Rezultatul este 5");
pauză;
cazul 6:
System.out.println("Rezultatul este 6");
pauză;
Mod implicit:
System.out.println("Eroare sau zarul a aterizat pe margine!");
}
Pentru valoarea dată a variabilei valueOnTheDice = 5, următorul rezultat va fi
afișat pe ecran:
Rezultatul este 5

If we change the value of the valueOnTheDice variable for instance to 100, the following text will be
displayed:

82
Error or the dice has landed on the edge!

The case variable and values can be as follows:

 constant expressions of byte, short, char and int types

 relevant wrapper classes: Byte, Short, Character and Integer

 enumeration constants (Enum)

 character Strings

The default section is optional. It is executed when none of the values in the case can be adjusted.

The break statements are also optional, but they are very significant in this structure. I will present

Dacă
it using an example with dice. Let us remove the break statement from the case statement:

schimbăm valoarea variabilei valueOnTheDice, de exemplu, la 100, va fi afișat


următorul text:
Eroare sau zarul a aterizat pe margine!
Variabila caz și valorile pot fi după cum urmează:
• expresii constante ale tipurilor byte, short, char și int
• clase de wrapper relevante: Byte, Short, Character și Integer
• constante de enumerare (Enum)
• șiruri de caractere
Secțiunea implicită este opțională. Se execută atunci când niciuna dintre valorile
din carcasă nu poate fi ajustată.
Declarațiile break sunt și ele opționale, dar sunt foarte semnificative în această
structură. O voi prezenta folosind un exemplu cu zaruri. Să eliminăm
instrucțiunea break din instrucțiunea case:
int valueOnTheDice = 5;
switch (valueOnTheDice) {
case 1:
System.out.println("Outcome is 1");
case 2:
System.out.println("Outcome is 2");
case 3:
System.out.println("Outcome is 3");
case 4:
System.out.println("Outcome is 4");
case 5:
System.out.println("Outcome is 5");
case 6:
System.out.println("Outcome is 6");
default:
System.out.println("Error or the dice has landed on the edge!");
}

For the provided value of the valueOnTheDice = 5 variable, the following text will be displayed on the
screen now:
Outcome is 5
Outcome is 6
Error or the dice has landed on the edge!

83
Why has this happened? The switch statement works so that as soon as it matches the case value,
it executes all statements from all the case sections (including default), until it encounters a
possible break statement. It may look a bit unintuitive, but remember about this and use
the break statement properly.

When can such an operation be useful? For example, when for the value of pips on the dice we want

to display the information whether the result was even. Then we can apply two break statements

Pentru valoarea furnizată a variabilei


and group the case values together.

valueOnTheDice = 5, următorul text va fi afișat acum pe ecran:


Rezultatul este 5
Rezultatul este 6
Eroare sau zarul a aterizat pe margine!
De ce sa întâmplat asta? Instrucțiunea switch funcționează astfel încât, de îndată
ce se potrivește cu valoarea casei, execută toate instrucțiunile din toate
secțiunile case (inclusiv implicit), până când întâlnește o posibilă instrucțiune
break. Poate părea puțin intuitiv, dar rețineți acest lucru și utilizați instrucțiunea
break în mod corespunzător.
Când poate fi utilă o astfel de operație? De exemplu, când pentru valoarea pips-
ului de pe zar vrem să afișăm informațiile dacă rezultatul a fost par. Apoi putem
aplica două instrucțiuni break și grupăm valorile case împreună.

int valueOnTheDice = 5;
switch (valueOnTheDice) {
case 1:
case 3:
case 5:
System.out.println("Odd number of pips");
break;
case 2:
case 4:
case 6:
System.out.println("Even number of pips");
break;
default:
System.out.println("Error or the dice has landed on the edge!");
}

For values 1, 3 and 5, the following text will be displayed:


Odd number of pips

For values 2, 4 and 6, the displayed text will be as follows:

Pentru valorile 1, 3 și 5, va fi afișat următorul text:


Even number of pips

Număr impar de sâmburi


Pentru valorile 2, 4 și 6, textul afișat va fi după cum urmează:
Număr par de sâmburi

84
Summary
What have you learned in this chapter?

What are the conditional statements in Java?

These are the if and switch statements. The if statement has a few
forms: if, if - else and if, else if - else.

What is a logical condition?

A logical condition is an expression that (after a possible calculation) returns


the true or false value.

What types can be used in the case value in the switch statement?

These can be as follows:

 byte, short, char and int types


 relevant wrapper classes: Byte, Short, Character and Integer
 enumeration constants (Enum)
 character strings (String)

What is a ternary operator?

This is an abbreviated form of the if - else statement, yet it returns the value. It is expressed as:
<logical -expression>? <value-1> : <value-2>

When is it advisable to use the switch statement instead of the if statement?

When we have many options to choose from or there is one option for multiple values. rezumat
Ce ai învățat în acest capitol?
Care sunt instrucțiunile condiționate în Java?
Acestea sunt declarațiile if și switch. Declarația if are câteva forme: if, if - else
și if, else if - else.
Ce este o condiție logică?
O condiție logică este o expresie care (după un posibil calcul) returnează
valoarea adevărată sau falsă.
Ce tipuri pot fi utilizate în valoarea casei din instrucțiunea switch?
Acestea pot fi după cum urmează:
• tipuri byte, short, char și int
• clase de wrapper relevante: Byte, Short, Character și Integer
• constante de enumerare (Enum)
• șiruri de caractere (String)
Ce este un operator ternar?

85
Aceasta este o formă prescurtată a instrucțiunii if - else, dar returnează valoarea.
Se exprimă astfel:
<expresie logică>? <valoare-1> : <valoare-2>
Când este recomandabil să folosiți instrucțiunea switch în loc de instrucțiunea
if?
Când avem multe opțiuni din care să alegem sau există o singură opțiune pentru
mai multe valori.
Exercises
 The following code simulates the roll of a dice
 int result = (int) (Math.random() * 6 + 1);

 will display whether the result is even or odd

 if the result is 6, write additionally the word WON

 Using a class that offers date and time operations, download:

 current time

 number of the day of the week

 number of the day of the month

 number of the month

 based on these data, choosing the optimal conditional statement, display:

 information about the time of day (setting arbitrarily): morning, noon, afternoon,
evening, night

 information about the day: working, free, holiday

 information whether it is already after the payment (assuming that the payment
comes by the 10th of each month)

 information about the season: spring, summer, autumn, winter

 Exerciții
 • Următorul cod simulează aruncarea unui zar
 • rezultat int = (int) (Math.random() * 6 + 1);
 • va afișa dacă rezultatul este par sau impar
 • dacă rezultatul este 6, scrieți suplimentar cuvântul CÂȘTIGAT
 • Folosind o clasă care oferă operații de dată și oră, descărcați:
 • ora curentă
 • numărul zilei săptămânii
 • numărul zilei lunii
 • numărul lunii
 • pe baza acestor date, alegerea instrucțiunii condiționale optime, afișați:

86
 • informații despre ora din zi (setare arbitrară): dimineața, prânzul, după-
amiaza, seara, noaptea
 • informatii despre zi: lucru, liber, concediu
 • informații dacă este deja după plată (presupunând că plata vine până la
data de 10 a fiecărei luni)
 • informatii despre anotimp: primavara, vara, toamna, iarna
Loops
When writing a program, we often need to perform a certain operation multiple times, e.g. display
a Java string three times or perform an operation until a condition is met, e.g. to withdraw coins
from the wallet until we collect the required amount. To repeat the operations in Java, we can use a
loop. There are several of them.

The for loop


The for loop is used to iterate (that is, to repeat statements or a group of statements).

Structure of the for loop


for (<initialization>; <logic-condition>; <step>) {
// operations
}

Bucle
Când scriem un program, de multe ori trebuie să efectuăm o anumită operație de
mai multe ori, de ex. afișați un șir Java de trei ori sau efectuați o operație până
când este îndeplinită o condiție, de ex. pentru a retrage monede din portofel
până când colectăm suma necesară. Pentru a repeta operațiunile în Java, putem
folosi o buclă. Sunt mai multe dintre ele.
Bucla pentru
Bucla for este folosită pentru a repeta (adică pentru a repeta instrucțiuni sau un
grup de instrucțiuni).
Structura buclei for
pentru (<inițializare>; <condiție-logică>; <pas>) {
// operațiuni
}

Example of a loop that displays text Java four times


for (int i=1; i<=4; i++) {
System.out.println("Java");
}

87
The result of running the program
Java
Java
Java
Java

The loop is executed as long as the logical condition is met; in this case, until i is less than or equal
to 4. The initialization section is performed only once: at the beginning, before the loop is
executed. The step section is performed at the end of each turn of the loop; after
each operations section.

Bucla este executată


To better illustrate this, I will write the previous code in a different form.

atâta timp cât condiția logică este îndeplinită; în acest caz, până când i este mai
mic sau egal cu 4. Secţiunea de iniţializare se execută o singură dată: la început,
înainte de executarea buclei. Secțiunea de pas este efectuată la sfârșitul fiecărei
ture a buclei; după fiecare secţiune de operaţii.
Pentru a ilustra mai bine acest lucru, voi scrie codul anterior într-o formă
diferită.
An example of writing the same loop in other way
int i=1;
for ( ; i<=4; ) {
System.out.println("Java");
i++
}

 the assignment (initialization) of the value to the variable takes place at the beginning, before
the loop is started
 after each operation (in this case, after the text is displayed), the step is performed

Tip

For loops, it is accepted to use short variable names (e.g. i, j, k etc.) as loop counters. In other
cases, it is recommended to use more descriptive variable names.

The for loops are used primarily when we know how many times the operations are to be
performed. If necessary, we can also save the for loop so that it can be repeated endlessly.

Un exemplu de scriere a aceleiași bucle în alt mod


int i=1;
pentru ( ; i<=4; ) {
System.out.println("Java");
i++
}
• atribuirea (inițializarea) valorii variabilei are loc la început, înainte de
începerea buclei
• dupa fiecare operatie (in acest caz, dupa afisarea textului), pasul este efectuat
Bacsis

88
Pentru bucle, este acceptată utilizarea numelor scurte de variabile (de exemplu,
i, j, k etc.) ca contoare de bucle. În alte cazuri, se recomandă utilizarea unor
nume de variabile mai descriptive.
Buclele for sunt folosite în primul rând atunci când știm de câte ori urmează să
fie efectuate operațiunile. Dacă este necesar, putem salva și bucla for, astfel
încât să se poată repeta la nesfârșit

Example of an infinite loop


for ( ; ; ) {
System.out.println("Java");
}

Now, the word Java will be displayed infinitely on the screen. To end the operation of this program,

press the red square on the right of ( ).

The for loop may not be executed even once if the first logical condition is false!
for (int i=5; i<3; i++) {
System.out.println(i);
}

The advantage of the for loop is that during iteration we have access to the current value of the
variable (the so-called loop counter), in our case it is variable i. For example, we can quickly enter
all values from 1 to 10.

Exemplu de buclă infinită


pentru ( ; ; ) {
System.out.println("Java");
}
Acum, cuvântul Java va fi afișat la infinit pe ecran. Pentru a încheia
funcționarea acestui program, apăsați pătratul roșu din dreapta ( ).
Bucla for poate să nu fie executată nici măcar o dată dacă prima condiție logică
este falsă!
pentru (int i=5; i<3; i++) {
System.out.println(i);
}
Avantajul buclei for este că în timpul iterației avem acces la valoarea curentă a
variabilei (așa-numitul contor de bucle), în cazul nostru este variabila i. De
exemplu, putem introduce rapid toate valorile de la 1 la 10.

Example of a loop that writes numbers from 1 to 10

89
for (int i=1; i<=10; i++) {
System.out.println(i);
}

The result displayed on the screen will be as follows:


1
2
3
4
5
6
7
8
9
10
We can use the print() function (instead of println()) to display the values in one line.

Exemplu de buclă care scrie numere de la 1 la 10


pentru (int i=1; i<=10; i++) {
System.out.println(i);
}
Rezultatul afișat pe ecran va fi următorul:
1
2
3
4
5
6
7
8
9
10
Putem folosi funcția print() (în loc de println()) pentru a afișa valorile pe o
singură linie.

Example of using the print() function


for (int i=1; i<=10; i++) {
System.out.print(i + " ");
}

We will then see on the screen:


1 2 3 4 5 6 7 8 9 10

These values can also be displayed from the end, that is, from 10 to 1.

Exemplu de utilizare a funcției print().


pentru (int i=1; i<=10; i++) {
90
System.out.print(i + " ");
}
Vom vedea apoi pe ecran:
1 2 3 4 5 6 7 8 9 10
Aceste valori pot fi afișate și de la sfârșit, adică de la 10 la 1.

Example of a loop with decrement


for (int i=10; i>=1; i--) {
System.out.print(i + " ");
}

Result:
10 9 8 7 6 5 4 3 2 1
You can also perform some calculations for the i variable. For instance, you can display individual
numbers and their squares.

Exemplu de buclă cu decrementare


pentru (int i=10; i>=1; i--) {
System.out.print(i + " ");
}
Rezultat:
10 9 8 7 6 5 4 3 2 1
De asemenea, puteți efectua câteva calcule pentru variabila i. De exemplu,
puteți afișa numere individuale și pătratele lor.

Example of using a loop counter for additional calculations


for (int i=1; i<=10; i++) {
System.out.println("i=" + i + "i^2=" + (i*i));
}

The result will be as follows:


i=1, i^2=1
i=2, i^2=4
i=3, i^2=9
i=4, i^2=16
i=5, i^2=25
i=6, i^2=36
i=7, i^2=49
i=8, i^2=64
i=9, i^2=81
i=10, i^2=100

With the loop, you can easily sum all numbers from 1 to 10.

Exemplu de utilizare a unui contor de bucle pentru calcule suplimentare


pentru (int i=1; i<=10; i++) {

91
System.out.println("i=" + i + "i^2=" + (i*i));
}
Rezultatul va fi următorul:
i=1, i^2=1
i=2, i^2=4
i=3, i^2=9
i=4, i^2=16
i=5, i^2=25
i=6, i^2=36
i=7, i^2=49
i=8, i^2=64
i=9, i^2=81
i=10, i^2=100
Cu bucla, puteți însuma cu ușurință toate numerele de la 1 la 10.

Example of the operation of adding numbers in a loop


int sum = 0;
for (int i=1; i<=10; i++) {
sum += i;
}
System.out.println("Suma = " + sum);

Result:
Sum = 55

The use of conditional statements with loops opens up further possibilities. For example, you can
add only even numbers from 1 to 10.

Exemplu de operație de adunare a numerelor într-o buclă


int suma = 0;
pentru (int i=1; i<=10; i++) {
suma += i;
}
System.out.println("Suma = " + suma);
Rezultat:
Suma = 55
Utilizarea instrucțiunilor condiționate cu bucle deschide posibilități
suplimentare. De exemplu, puteți adăuga numai numere pare de la 1 la 10
Example of the operation of adding numbers in a loop using a conditional statement
int sum = 0;

92
for (int i=1; i<=10; i++) {
if (i%2 == 0) {
sum += i;
}
}
System.out.println("Sum = " + sum);

 you can define any restrictions as needed by changing this condition

Result:
Sum = 30

A step does not need to change by 1. You can, for example, write all multiples of digit 5 in the
range from 5 to 100.

Exemplu de operație de adăugare de numere într-o buclă folosind o instrucțiune


condiționată
int suma = 0;
pentru (int i=1; i<=10; i++) {
dacă (i%2 == 0) {
suma += i;
}
}
System.out.println("Suma = " + suma);
• puteți defini orice restricții după cum este necesar schimbând această condiție
Rezultat:
Suma = 30
Un pas nu trebuie să se modifice cu 1. Puteți, de exemplu, să scrieți toți multiplii
cifrei 5 în intervalul de la 5 la 100.

Example of a loop with a step incremented by 5


for (int i=5; i<=100; i=i+5) {
System.out.print(i + " ");
}

The result will be as follows:


5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

Exemplu de buclă cu un pas incrementat cu 5


pentru (int i=5; i<=100; i=i+5) {
System.out.print(i + " ");
}
Rezultatul va fi următorul:
5 10 15 20 25 30 35 40 45 50 55 60 65 70 75 80 85 90 95 100

93
The break and continue commands
For loops, in addition to conditional statements, we can use statements that change the control
flow.

To stop the iteration at a given moment, you can use the break statement that definitively
terminates the loops. This can be useful, for example, in a situation where you sum up values and
you want to stop the iteration after a certain value is exceed. You can additionally display the
number of the summed values and the value itself.

Comenzile pauză și continuare


Pentru bucle, pe lângă instrucțiunile condiționate, putem folosi instrucțiuni care
modifică fluxul de control.
Pentru a opri iterația la un moment dat, puteți utiliza instrucțiunea break care
termină definitiv buclele. Acest lucru poate fi util, de exemplu, într-o situație în
care însumați valori și doriți să opriți iterația după depășirea unei anumite
valori. În plus, puteți afișa numărul valorilor însumate și valoarea în sine.
Example of a loop using the break statement
int sum=0;
int count=0;
for (int i=1; i<=200; i++) {
sum += i;
count++;
if (sum >= 50) {
break;
}
}
System.out.println("Sum = " + sum);
System.out.println("Number of summed values = " + count);

 summing up the values


 increment of the number of summed values
 if a sum greater than or equal to 50 has been achieved, the entire loop is stopped

If, on the other hand, you would like to ignore several turns of the loop for the set values, then you

can use the continue statement. Let us assume you want to display numbers from 1 to 20, but

without the values from 13 to 15. You can achieve this in the following way: însumarea
valorilor
• creşterea numărului de valori însumate
• dacă a fost realizată o sumă mai mare sau egală cu 50, întreaga buclă este
oprită
Dacă, pe de altă parte, doriți să ignorați mai multe ture ale buclei pentru valorile
setate, atunci puteți utiliza instrucțiunea continue. Să presupunem că doriți să
afișați numere de la 1 la 20, dar fără valorile de la 13 la 15. Puteți realiza acest
lucru în felul următor:

94
Example of a loop using the continue statement
for (int i=1; i<=20; i++) {
if (i>=13 && i<=15) {
continue;
}
System.out.print(i + " ");
}

 if the i value is between 13 and 15

it interrupts the current turn (iteration) of the loop and goes to the next one Exemplu de buclă
folosind instrucțiunea continue
pentru (int i=1; i<=20; i++) {
dacă (i>=13 && i<=15) {
continua;
}
System.out.print(i + " ");
}
• dacă valoarea i este între 13 și 15
• întrerupe turnarea curentă (iterația) a buclei și trece la următoarea

The (enhanced) for loop


In Java, there is one more kind of for loop, sometimes also called an “improved” or “enhanced”
loop, or a for each loop. It allows you to browse (iterate) arrays and collections without using the
index (loop counter).

Structure of the for each loop


for (<variable> : <collection/array>) {
// oparations
}

During each loop rotation, consecutive value from the collection or array is passed to

Bucla for (îmbunătățită).


the variable and you can access it in the individual iteration.

În Java, există încă un fel de buclă for, uneori numită și buclă „îmbunătățită”
sau „îmbunătățită”, sau o buclă pentru fiecare buclă. Vă permite să răsfoiți
(iterați) matrice și colecții fără a utiliza indexul (contorul de bucle).
Structura pentru fiecare buclă
pentru (<variabilă>: <colecție/matrice>) {
// oparații
}
În timpul fiecărei rotații de buclă, valoarea consecutivă din colecție sau matrice
este transmisă variabilei și o puteți accesa în iterația individuală.
Bucla for (îmbunătățită).
95
În Java, există încă un fel de buclă for, uneori numită și buclă „îmbunătățită”
sau „îmbunătățită”, sau o buclă pentru fiecare buclă. Vă permite să răsfoiți
(iterați) matrice și colecții fără a utiliza indexul (contorul de bucle).
Structura pentru fiecare buclă
pentru (<variabilă>: <colecție/matrice>) {
// oparații
}
În timpul fiecărei rotații de buclă, valoarea consecutivă din colecție sau matrice
este transmisă variabilei și o puteți accesa în iterația individuală.
Example of iterating over a 10-element array Exemplu de iterare pe o matrice de 10

elemente

int[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};


for (int i : digits) {
System.out.print(i + " ");
}

This loop type is very convenient when you want to view the entire collection or array and you do
not care about controlling how to do it, i.e. on defining the scope and order of the elements to which
you want to have access.

When you use the for each loop but you would like to have access to a counter, you need to program

Acest tip de buclă este foarte convenabil atunci când doriți să


it by yourself.

vizualizați întreaga colecție sau matrice și nu vă pasă să controlați cum să o


faceți, adică să definiți sfera și ordinea elementelor la care doriți să aveți acces.
Când utilizați pentru fiecare buclă, dar doriți să aveți acces la un contor, trebuie
să îl programați singur.
Example of the for each loop with its own counter Exemplu pentru fiecare buclă cu

propriul contor
int[] digits = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
int oddCount = 0;
int allCount = 0;
for (int i : digits) {
allCount++;
if (i%2 != 0) {
oddCount++;
System.out.println(i + " is odd");
}
}
System.out.println("Count: all=" + allCount + ", odd=" + oddCount);

The result will be as follows:


1 is odd
3 is odd
5 is odd
7 is odd
9 is odd

96
Count: all=10, odd=5

The while loop Bucla while


The while loop allows you to execute specific statements for as long as the logical condition for

Bucla while vă permite să executați anumite


the loop is met (its value is true).

instrucțiuni atâta timp cât condiția logică pentru buclă este îndeplinită (valoarea
acesteia este adevărată).
Structure of the while loop

Structura buclei while


while (<logical-condition>) {
// operations

} în timp ce (<condiție-logică>) {
// operațiuni
}
Example that lists numbers from 1 to 10 Exemplu care enumeră numerele de la 1 la 10
int max=10;
int i=1;
while (i<=max) {
System.out.print(i + " ");
i++;
}

The while loop statements can be never executed if the logical condition for the loop is false at
the beginning.

The while loop is used most often when the number of repetitions is not known in advance, but you
know the condition that must be met for the loop.

As for the for loop, the while loop also can be performed endlessly.

int max=10;
int i=1;
în timp ce (i<=max) {
System.out.print(i + " ");
i++;
}
Instrucțiunile de buclă while nu pot fi niciodată executate dacă condiția logică
pentru buclă este falsă la început.
Bucla while este folosită cel mai des atunci când numărul de repetări nu este
cunoscut în prealabil, dar cunoașteți condiția care trebuie îndeplinită pentru
buclă.
În ceea ce privește bucla for, și bucla while poate fi efectuată la nesfârșit.

97
Example of an infinite while loop Exemplu de buclă while infinită
while (true) {
System.out.println("Java");
}

You can also apply conditional statements such as break and continue.

în timp ce (adevărat) {
System.out.println("Java");
}
De asemenea, puteți aplica instrucțiuni condiționate, cum ar fi break and
continue.

The do while loop Bucla do while


The do while loop (similarly as the while loop) allows you to execute specific instructions as long as
the logical condition for the loop is met (its value is true).

Structure of the do while loop


do {
// operations
} while (logical-condition>);

Unlike the while loop, the do while loop will always be executed at least once, even if the logical

condition is not met at the beginning.

Bucla do while (în mod similar cu bucla while) vă permite să executați


instrucțiuni specifice atâta timp cât condiția logică pentru buclă este îndeplinită
(valoarea acesteia este adevărată).
Structura buclei do while
face {
// operațiuni
} while (condiție-logică>);
Spre deosebire de bucla while, bucla do while va fi întotdeauna executată cel
puțin o dată, chiar dacă condiția logică nu este îndeplinită la început.
Example of the do while loop
do {
System.out.println("Java is great!!!");
} while (false);

The result will be as follows:


Java is great!!!

As in the case of the for and while loops, the do while loop also can be performed endlessly, and

you can apply conditional statements such as break and continue. Exemplu de buclă do while
face {

98
System.out.println("Java este grozav!!!");
} în timp ce (fals);
Rezultatul va fi următorul:
Java este grozav!!!
Ca și în cazul buclelor for și while, și bucla do while poate fi efectuată la
nesfârșit și puteți aplica instrucțiuni condiționate precum break și continue.
Nested loops
It is possible to enclose a loop in another loop's body.

Example of nested loops


for (int i=1; i<=10; i++) {
for (int j=1; j<=20; j++) {
System.out.print("*");
}
System.out.println();
}

 outer loop - it loops 10 times; it is responsible for generating individual lines


 internal loop - it loops 20 times; it is responsible for generating individual characters in the
line
 the print() method prints the * character as many times as the inner loop is executed

in this place, after the execution of all rotations of the inner loop, a new line mark is printed for one

Bucle imbricate
rotation of the outer loop

Este posibil să includeți o buclă în corpul altei bucle.


Exemplu de bucle imbricate
pentru (int i=1; i<=10; i++) {
pentru (int j=1; j<=20; j++) {
System.out.print("*");
}
System.out.println();
}
• bucla exterioară - se face bucla de 10 ori; este responsabil pentru generarea
liniilor individuale
• buclă internă - se face buclă de 20 de ori; este responsabil pentru generarea
caracterelor individuale în rând
• metoda print() imprimă caracterul * de câte ori este executată bucla interioară
• în acest loc, după executarea tuturor rotațiilor buclei interioare, se imprimă un
nou semn de linie pentru o rotație a buclei exterioare
Rezultat:

99
Result:
********************
********************
********************
********************
********************
********************
********************
********************
********************
********************

Important

Analyze the operation of these two nested loops carefully to understand the code above. Change
the values of the i and j variables. Replace the print() function with println() (and opposite) and
see how the operation of the program will change. Add conditional statements or
the break and continue statements.

Thanks to the nested loops you can, for example, draw a “checkerboard”.
for (int i=1; i<=10; i++) {
for (int j=1; j<=10; j++) {
if ((i % 2 == 0 && j % 2 == 1) || (i % 2 == 1 && j % 2 == 0)) {
System.out.print("#");
} else {
System.out.print(" ");
}
}
System.out.println();
}

the # sign is to be printed alternately; if you are in an even row and an odd column or in an odd row

Important
and an even column. In other cases, a space is to be printed.

Analizați cu atenție funcționarea acestor două bucle imbricate pentru a înțelege


codul de mai sus. Modificați valorile variabilelor i și j. Înlocuiți funcția print()
cu println() (și opus) și vedeți cum se va schimba funcționarea programului.
Adăugați instrucțiuni condiționate sau instrucțiuni break and continue.
Datorită buclelor imbricate, puteți, de exemplu, să desenați o „tablă de șah”.
pentru (int i=1; i<=10; i++) {
pentru (int j=1; j<=10; j++) {
dacă ((i % 2 == 0 && j % 2 == 1) || (i % 2 == 1 && j % 2 == 0)) {
System.out.print("#");
} altfel {
System.out.print(" ");
}
}
System.out.println();

100
}
• semnul # se imprimă alternativ; dacă vă aflați într-un rând par și o coloană
impară sau într-un rând impar și o coloană pară. În alte cazuri, se va imprima un
spațiu.
Rezultatul va fi următorul
The result will be as follows:
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #

Warning

In programming, you will often encounter situations where the loop counter starts from 0. In IT,

Avertizare
the 0 value is encountered much more often than in mathematics :)

În programare, veți întâlni adesea situații în care contorul buclei începe de la 0.


În IT, valoarea 0 este întâlnită mult mai des decât la matematică :)
Summary
What have you learned in this chapter?

What loops are there in Java?

There are several types of loops available:

 for
 (enhanced) for
 while
 do while

When should you use the for loop and when the while / do while loop?

We use the for loop most often when we know the number of elements or the number of repetitions
of a given statement. In addition, we use it when we want to have an (easy) access to the loop
counter. We use the while / do while loop when we do not know in advance how many times we will
iterate since it depends on some factor.

rezumat
Ce ai învățat în acest capitol?
Ce bucle există în Java?
Există mai multe tipuri de bucle disponibile:
• pentru
101
• (imbunatatit) pentru
• in timp ce
• face în timp ce
Când ar trebui să utilizați bucla for și când bucla while / do while?
Folosim bucla for cel mai des atunci când cunoaștem numărul de elemente sau
numărul de repetări ale unei declarații date. În plus, îl folosim atunci când dorim
să avem un acces (ușor) la contorul de bucle. Folosim bucla while / do while
atunci când nu știm dinainte de câte ori vom repeta, deoarece depinde de un
anumit factor.
What is the difference between the for loop and the (enhanced) for loop?

The for loops allows you to declare the iteration method by controlling the loop count. If we want
only to go through a given set (without probing into the iteration method), we choose
the for (enhanced loop that is also called the foreach loop).

What is the difference between the while loop and do while loop?

The do while loop will always be executed at least once, even if the logical condition is false at the
beginning; the while loop will not be executed in this case.

Exercises
 List numbers from -20 to20 using a loop. Then write out:
 first 6 numbers
 last 6 numbers
 all even numbers
 all numbers except for number 5
 all numbers up to and including 7
 all numbers divisible by 3
 sum of all numbers
 sum of all numbers greater or equal 4
 all numbers and their powers
Exerciții
all numbers and their value modulo 10

• Listează numerele de la -20 la 20 folosind o buclă. Apoi scrieți:


• primele 6 numere
• ultimele 6 numere
• toate numerele pare
• toate numerele cu excepția numărului 5
• toate numerele până la 7 inclusiv
• toate numerele divizibile cu 3
• suma tuturor numerelor

102
• suma tuturor numerelor mai mare sau egală 4
• toate numerele și puterile lor
• toate numerele și valoarea lor modulo 10

 Using a class that offers operations on date and time, get the current time (hour, minute, and
second) and write these values using the characters \*, whose number equals the given value.
To make it difficult, one line can contain up to 10 * characters.

Example for values 15:03:28.


Current time: 15:03:28

Folosind o clasă care oferă operații pe dată și oră, obțineți ora curentă (oră,
minut și secundă) și scrieți aceste valori folosind caracterele \*, al căror număr
este egal cu valoarea dată. Pentru a îngreuna, o linie poate conține până la 10 *
caractere.
Exemplu pentru valorile 15:03:28.
Ora curentă: 15:03:28
Hour:
**********
*****

Minute:
***

Second:
**********
**********
********

A calendar page for January with January 1 being Wednesday, for the current date January 16, it

O pagină de calendar pentru ianuarie, cu 1 ianuarie fiind


might look like this:

miercuri, pentru data curentă 16 ianuarie, ar putea arăta astfel:



Mo Tu We Th Fr Sa Su
\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-\-
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15[16]17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

 display the above page using loops and additional instructions


 customize the code so January 1 can be any day of the week

download data (using a class that offers operations on date and time) about the current date and

display a page for it from the calendar afișați pagina de mai sus folosind bucle și
instrucțiuni suplimentare
• personalizați codul, astfel încât 1 ianuarie să fie în orice zi a săptămânii

103
• descărcați date (folosind o clasă care oferă operațiuni pe dată și oră) despre
data curentă și afișați o pagină pentru aceasta din calendar
Arrays
An array is a data structure that allows you to store multiple elements of the same type. Instead of
creating several, a dozen or several dozen variables that are somehow related to each other, you
can group them to be stored in one array. You can access each element of an array through
its index (position in the array), which is a number of the int type.

When creating an array, you must specify its size. The size of an array cannot be modified. If it
turns out that you need a larger array, you must create a new (larger) one and copy the data from
the smaller array to it.

Indexes of an array are numbered from 0. Thus, the first element is the element with index 0 , and
the last one is the element with index n-1 , where n is the size of the array.

Elements of the array can be both primitive and object-oriented types. An array (of whatever

Matrice
type) is an object! Arrays can be single- or multidimensional.

O matrice este o structură de date care vă permite să stocați mai multe elemente
de același tip. În loc să creați mai multe, o duzină sau câteva zeci de variabile
care sunt într-un fel legate între ele, le puteți grupa pentru a fi stocate într-o
singură matrice. Puteți accesa fiecare element al unei matrice prin indexul său
(poziția în matrice), care este un număr de tip int.
Când creați o matrice, trebuie să specificați dimensiunea acesteia. Dimensiunea
unei matrice nu poate fi modificată. Dacă se dovedește că aveți nevoie de o
matrice mai mare, trebuie să creați una nouă (mai mare) și să copiați datele din
matricea mai mică în ea.
Indicii unui tablou sunt numerotați de la 0. Astfel, primul element este
elementul cu indicele 0, iar ultimul este elementul cu indicele n-1, unde n este
dimensiunea matricei.
Elementele matricei pot fi atât de tip primitiv, cât și de tip orientat pe obiect. O
matrice (de orice tip) este un obiect! Matricele pot fi unidimensionale sau
multidimensionale.
Creating arrays
Pattern of array declaration
type[] variable;

Example of array declaration


int[] numbers;
boolean[] switches;
String[] names;
Double[] values;

104
Tip

Sometimes you can encounter alternative declarations of array variables. Equivalent declarations of
array variables.

Equivalent declarations of array variables


int[] a;
int []b;
int c[];

The recommended record is int[] a.

Crearea de matrice
Model de declarare a matricei
tip[] variabilă;
Exemplu de declarație de matrice
int[] numere;
comutatoare booleene[];
Nume șir[];
Valori duble[];
Bacsis
Uneori puteți întâlni declarații alternative ale variabilelor matrice. Declarații
echivalente ale variabilelor matrice.
Declarații echivalente ale variabilelor matrice
int[] a;
int []b;
int c[];
Înregistrarea recomandată este int[] a.
Pattern of array declaration and initialization
type[] variable = new type[N];
type[] variable = new type[]{value1, value2, ..., valueN};
type[] variable = {value1, value2, ..., valueN};

 creating an N-element array without filling it with data; each element now has a default value
relevant for the array type

 creating an array and filling it in with data; based on their quantity, Java knows the size of the
array

shortened (recommended) entry of the above declaration Model de declarare și inițializare


a matricei
tip[] variabilă = tip nou[N];
tip[] variabilă = tip nou[]{valoare1, valoare2, ..., valoareN};
tip[] variabilă = {valoare1, valoare2, ..., valoareN};

105
• crearea unui tablou cu N elemente fără a-l completa cu date; fiecare element
are acum o valoare implicită relevantă pentru tipul de matrice
• crearea unui tablou și completarea acestuia cu date; pe baza cantității lor, Java
cunoaște dimensiunea matricei
• introducerea scurtată (recomandată) a declarației de mai sus
Examples of array declaration and initialization
int[] numbers = new int[10];
String[] labels = new String[2];
String[] names = new String[]{"Sandra", "Tom", "Kate", "WoBarttek"};
Double[] values = {3.1415D, 2.7182D};

 we have created a 10 - element array of the int type; we have not filled it with values,
therefore it has been filled with default values for the int type, that is 0

 we have created a 2 - element array of the String type; we have not filled it with values,
therefore it has been filled with default values for the String type, that is, null

 we have created a 4 - element array of the String type and provided 4 elements

 we have created a 2 - element array of the Double type and provided 2 values

 If at the time of creating the array you know how many elements you want to store (you know
the array size, but you do not know the values yet), then use the following pattern:
 type[] variable = new type[N];

np.
int[] numbersFromLottery = new int[7];

 However, if at the time of creating the array you know all the values to be stored (their
number is the size of the array), then use the following record:
 type[] variable = {value1, value2, ..., valueN};

e.g.

String[] seasons = {"Spring", "Summer", "Fall", "Winter"}; Exemple de declarare și


inițializare a matricei
int[] numere = new int[10];
String[] labels = String[2] nou;
String[] names = String nou[]{"Sandra", "Tom", "Kate", "WoBarttek"};
Valori duble[] = {3,1415D, 2,7182D};
• am creat o matrice de 10 elemente de tip int; nu l-am umplut cu valori, prin
urmare a fost umplut cu valori implicite pentru tipul int, adică 0
• am creat o matrice cu 2 elemente de tip String; nu l-am completat cu valori,
prin urmare a fost umplut cu valori implicite pentru tipul String, adică nul
• am creat o matrice cu 4 elemente de tip String și am furnizat 4 elemente
• am creat o matrice cu 2 elemente de tip Double și am furnizat 2 valori

106
• Dacă în momentul creării matricei știți câte elemente doriți să stocați (știți
dimensiunea matricei, dar nu cunoașteți încă valorile), atunci utilizați următorul
model:
• variabilă tip[] = tip nou[N];
np.
int[] numbersFromLottery = new int[7];
• Cu toate acestea, dacă în momentul creării matricei cunoașteți toate valorile
care trebuie stocate (numărul lor este dimensiunea matricei), atunci utilizați
următoarea înregistrare:
• tip[] variabilă = {valoare1, valoare2, ..., valoareN};
de exemplu.
String[] anotimpuri = {"Primăvara", "Vara", "Toamna", "Iarna"};
Operations on arrays
Let us try to first display the content of the created (declared and initialized) arrays.

Example of displaying the array contents


int[] numbers = new int[5];
int[] luckyNumbers = {1, 3, 7, 17, 21};
String[] names = new String[10];
String[] seasons = {"Spring", "Summer", "Fall", "Winter"};

System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(luckyNumbers));
System.out.println(Arrays.toString(names));
System.out.println(Arrays.toString(seasons));

System.out.println(luckyNumbers);
System.out.println(seasons);

Result:
[0, 0, 0, 0, 0]
[1, 3, 7, 17, 21]
[null, null, null, null, null, null, null, null, null, null]
[Spring, Summer, Fall, Winter]
[I@610455d6

Operații pe matrice
[Ljava.lang.String;@511d50c0

Să încercăm să afișăm mai întâi conținutul matricelor create (declarate și


inițializate).
Exemplu de afișare a conținutului matricei
int[] numere = new int[5];
int[] luckyNumbers = {1, 3, 7, 17, 21};
String[] names = new String[10];
String[] anotimpuri = {"Primăvara", "Vara", "Toamna", "Iarna"};

107
System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(luckyNumbers));
System.out.println(Arrays.toString(nume));
System.out.println(Arrays.toString(sezoane));

System.out.println(luckyNumbers);
System.out.println(sezoane);
Rezultat:
[0, 0, 0, 0, 0]
[1, 3, 7, 17, 21]
[nul, nul, nul, nul, nul, nul, nul, nul, nul, nul, nul]
[Primăvară vară toamnă iarnă]
[I@610455d6
[Ljava.lang.String;@511d50c0
Tip

To display the contents of the entire array, we have used the Arrays.toString() method. If this method
is underlined in red on your screens, add the following line above the class declaration:
import java.util.Arrays;

It allows you to apply methods from the Arrays class in our code.

If you try to display the arrays with the System.out.println() method, you will get an poorly legible
result.

You can also download and modify individual elements. Access to an element is obtained through

its index. Bacsis


Pentru a afișa conținutul întregii matrice, am folosit metoda Arrays.toString().
Dacă această metodă este subliniată cu roșu pe ecranele dvs., adăugați
următoarea linie deasupra declarației de clasă:
import java.util.Arrays;
Vă permite să aplicați metode din clasa Arrays în codul nostru.
Dacă încercați să afișați matricele cu metoda System.out.println(), veți obține un
rezultat slab lizibil.
De asemenea, puteți descărca și modifica elemente individuale. Accesul la un
element se obține prin indexul acestuia
Pattern of access to the element of the array Model de acces la elementul matricei

108
variable[index]

Example of operations on individual elements of arrays


int[] numbers = new int[5];
String[] seasons = {"Spring", "Summer", "Fall", "Winter"};

System.out.println(Arrays.toString(numbers));
System.out.println(Arrays.toString(seasons));

numbers[0] = 25;
System.out.println(Arrays.toString(numbers));
System.out.println(numbers[0]);
numbers[4] = -200;
System.out.println(Arrays.toString(numbers));

seasons[1] = "";
seasons[2] = null;
System.out.println(Arrays.toString(seasons));
System.out.println(seasons[3]);

Result:
[0, 0, 0, 0, 0]
[Spring, Summer, Fall, Winter]
[25, 0, 0, 0, 0]
25
[25, 0, 0, 0, -200]
[Spring, , null, Winter]
Winter

It is useful to know the size of the array (if, for example, you do not remember its size or you were

only given an array variable). The size of the array is obtained by referring to a field called length.

Este util să cunoașteți dimensiunea matricei (dacă, de exemplu, nu vă amintiți


dimensiunea acesteia sau vi s-a dat doar o variabilă matrice). Mărimea matricei
se obține prin referire la un câmp numit lungime.
Example of access to the array size
int[] numbers = new int[5];
String[] seasons = {"Spring", "Summer", "Fall", "Winter"};

System.out.println(numbers.length);
System.out.println(seasons.length);

Result:
5
4
Tip

Thus, the first element of the array is the element with index 0, and the last element is the one

Bacsis
with index variable. length - 1

Astfel, primul element al tabloului este elementul cu indice 0, iar ultimul


element este cel cu variabilă indice. lungime - 1
Important

109
If you try to refer to an index outside the range (0, variable.length-1), the program will end its

Important
operation and an error will appear.

Dacă încercați să vă referiți la un index în afara intervalului (0,


variabilă.lungime-1), programul își va încheia funcționarea și va apărea o
eroare.
Examples of incorrect references
String[] seasons = {"Spring", "Summer", "Fall", "Winter"};
System.out.println(seasons[-1]);
System.out.println(seasons[5]);

Arrays and loops


Matrice și bucle
Loops are very common when working with arrays.

Buclele sunt foarte frecvente atunci când lucrați cu matrice.


An example of using loops with arrays
String[] seasons = {"Spring", "Summer", "Fall", "Winter"};
int[] numbers = {34, 23, 89, 14, 63, 2, 55};

for (int i = 0; i < seasons.length; i++) {


System.out.println(seasons[i]);
}

for (int i = numbers.length - 1; i >= 0; i--) {


System.out.print(numbers[i] + " ");
}

System.out.println();

for (String season : seasons) {


System.out.println(season);
}

Result:
Spring
Summer
Fall
Winter
55 2 63 14 89 23 34
Spring
Summer
Fall
Winter

Summary
What have you learned in this chapter?

What are arrays?

Arrays are data structures that allow you to store several elements of the same type. You can
access individual elements of the array through the index.

110
What is an index in an array?

Index is the position of an element in an array. Indexes are numbered from 0. This means that the
first element of the array is the element with index 0. The last element of the n-element array is the
element with index n-1.

Is it possible to change the size of the array?

No, an array once declared has a fixed size that cannot be changed. If you need a larger (or smaller)
array, you must create a new array and move elements to it.

How should I display the array contents?

To display the contents of the array, you can use the Arrays.toString(<arraya>) function, e.g.
String[] seasons = {"Spring", "Summer", "Fall", "Winter"};

System.out.println(Arrays.toString(seasons)); rezumat
Ce ai învățat în acest capitol?
Ce sunt matricele?
Matricele sunt structuri de date care vă permit să stocați mai multe elemente de
același tip. Puteți accesa elemente individuale ale matricei prin intermediul
indexului.
Ce este un index într-o matrice?
Indexul este poziția unui element într-o matrice. Indicii sunt numerotați de la 0.
Aceasta înseamnă că primul element al matricei este elementul cu indicele 0.
Ultimul element al matricei cu n elemente este elementul cu indicele n-1.
Este posibil să schimbați dimensiunea matricei?
Nu, o matrice odată declarată are o dimensiune fixă care nu poate fi modificată.
Dacă aveți nevoie de o matrice mai mare (sau mai mică), trebuie să creați o
matrice nouă și să mutați elemente în ea.
Cum ar trebui să afișez conținutul matricei?
Pentru a afișa conținutul matricei, puteți utiliza funcția
Arrays.toString(<arraya>), de ex.
String[] anotimpuri = {"Primăvara", "Vara", "Toamna", "Iarna"};
System.out.println(Arrays.toString(sezoane));
Important

Remember about the import declaration:


import java.util.Arrays;

How should I get information about the size of the array?

Every array contains a field called length that defines its size. Important
Amintiți-vă despre declarația de import:

111
import java.util.Arrays;
Cum ar trebui să obțin informații despre dimensiunea matricei?
Fiecare matrice conține un câmp numit lungime care îi definește dimensiunea.

Exercises
 There is an array of 10 elements of the int type:
 int[] integers = {1, 3, 5, 2, 5, 6, 7, 4, 9, 7};

Using one of the loops, write a code fragment that displays:

 all numbers

 first 6 numbers

 last 6 numbers

 all even numbers

 all digits at odd indexes

 all numbers backwards

 all numbers except 5

 all digits up to and including 7

 all digits divisible by 3

 sum of all digits

 sum of all digits greater or equal 4

 the smallest and largest digit

 There is a board storing the denominations of money:


 int[] money = {1, 2, 5, 10, 20};

and a code example that randomizes one of the indexes of this array:
int idx = (int) (Math.random() * money.length + 1);

Next, there is a program that:

 will loop randomly until it "accumulates" a value of 100

 each downloaded value is to be displayed

 each component sum is to be displayed

 at the end, the number of withdrawals of money necessary to collect 100 and the amount
collected (because it can exceed 100) should be displayed

 try to modify this program so that it allows you to collect the exact amount (not allow it to
be exceeded)

 Exerciții
 • Există o matrice de 10 elemente de tip int:
 • int[] numere întregi = {1, 3, 5, 2, 5, 6, 7, 4, 9, 7};
 Folosind una dintre bucle, scrieți un fragment de cod care afișează:

112
 • toate numerele
 • primele 6 numere
 • ultimele 6 numere
 • toate numerele pare
 • toate cifrele la indici impari
 • toate numerele invers
 • toate numerele cu excepția 5
 • toate cifrele până la 7 inclusiv
 • toate cifrele divizibile cu 3
 • suma tuturor cifrelor
 • suma tuturor cifrelor mai mare sau egală 4
 • cea mai mică și cea mai mare cifră
 • Există o tablă care stochează valorile nominale de bani:
 • int[] bani = {1, 2, 5, 10, 20};
 și un exemplu de cod care randomizează unul dintre indecșii acestei
matrice:
 int idx = (int) (Math.random() * bani.lungime + 1);
 În continuare, există un program care:
 • se va bucla aleatoriu până când „acumulează” o valoare de 100
 • fiecare valoare descărcată trebuie să fie afișată
 • fiecare sumă de componente trebuie să fie afișată
 • la sfarsit trebuie afisat numarul de retrageri de bani necesare colectarii a
100 si suma incasata (deoarece poate depasi 100)
 • încercați să modificați acest program astfel încât să vă permită să
colectați suma exactă (nu lăsați să fie depășită)

Object-oriented programming
Java is an object-oriented language. Except for primitive types everything in Java is an object.

Basic concepts:

 Class
A rule for an object. It is a template (pattern) according to which you can create various
objects. It defines a new data type.
 Object
An instance, an item, a specific example of the class. A programming way of presenting an
entity.

113
 Field
A feature of a given object describing a given property of an object in terms of its type.
 Method
An operation performed on the class object.

 The body of the class is enclosed in braces { i }.


 These are fields (status, data) and methods (operations, behavior).
 Java does not allow you to create fields and methods outside of the class!
 The class field can have a default value.
 If you do not specify a default value, it will be set by a compiler.

Class names are capitalized; field and method names are lowercase. Programare orientată pe
obiecte
Java este un limbaj orientat pe obiecte. Cu excepția tipurilor primitive, totul în
Java este un obiect.
Noțiuni de bază:
• Clasa
O regulă pentru un obiect. Este un șablon (pattern) după care poți crea diverse
obiecte. Acesta definește un nou tip de date.
• Obiect
O instanță, un articol, un exemplu specific al clasei. O modalitate de programare
de a prezenta o entitate.
• Camp
O caracteristică a unui obiect dat care descrie o proprietate dată a unui obiect în
termeni de tipul său.
• Metoda
O operație efectuată pe obiectul clasei.
• Corpul clasei este cuprins între acolade { i }.
• Acestea sunt câmpuri (stare, date) și metode (operații, comportament).
• Java nu vă permite să creați câmpuri și metode în afara clasei!
• Câmpul de clasă poate avea o valoare implicită.
• Dacă nu specificați o valoare implicită, aceasta va fi setată de un compilator.
• Numele claselor sunt scrise cu majuscule; numele câmpurilor și metodelor
sunt litere mici.

We have used and created classes before. In the chapter on [data types]

(../../e-coursebook/java_basicsy/data_types_variables_and_constants) we created instances of simple

type wrappers. Now we will learn how to create our own classes that will have fields and provide

methods. Am folosit și creat clase înainte. În capitolul despre [tipuri de date]

114
(../../e-coursebook/java_basicsy/data_types_variables_and_constants) am creat
instanțe de wrapper-uri de tip simplu. Acum vom învăța cum să ne creăm
propriile clase care vor avea câmpuri și vor oferi metode.

An example of a 'Car' class for describing a car.


public class Car {

private String model;


private int productionYear;
private String color;
private long distance = 0;
private boolean used = false;

public Car() {

public String getModel() {


return model;
}

public void setModel(String model) {


this.model = model;
}

public void drive(int km) {


distance += km;
}
}

 Carclass declaration; { bracket declares the beginning of the class body


 class fields (attributes)
 class constructor declaration; pay attention to the name consistent with the class name and
the lack of a return type declaration
 a method (the so-called getter) that provides a field value; in this case, the model field
 a method (so-called setter) that allows to set the value of a field; in this case, the model field
 a method that performs an operation on an object (changes the state of the object); by calling
it, we pass the number of kilometers to travel, and the method changes the value of
the distance field by a given value
 } bracket ending the body of class Car

 Un exemplu de clasă „Mașină” pentru descrierea unei mașini.


 mașină de clasă publică {

 model String privat;
 private int productYear;
 culoare privată șir;
 distanță lungă privată = 0;
 boolean privat folosit = fals;

115
 masina publica() {

 }

 public String getModel() {
 model de retur;
 }

 public void setModel(String model) {
 asta.model = model;
 }

 mașină public void(int km) {
 distanta += km;
 }
 }
 • Declaratie Carclass; { paranteza declară începutul corpului clasei
 • câmpuri de clasă (atribute)
 • declararea constructorului de clasă; acordați atenție numelui în
concordanță cu numele clasei și lipsei unei declarații de tip returnat
 • o metodă (așa-numita getter) care furnizează o valoare de câmp; în acest
caz, câmpul model
 • o metodă (așa-numita setter) care permite setarea valorii unui câmp; în
acest caz, câmpul model
 • o metodă care efectuează o operaţie asupra unui obiect (schimbă starea
obiectului); apelând-o, trecem numărul de kilometri de parcurs, iar
metoda schimbă valoarea câmpului de distanță cu o valoare dată
 • } suport care se termină cu caroseria clasei Car

Classes and objects


The key is to understand the difference between a class and an object. For the record:

Class is a template, formula, recipe for an object. Definition of a new data type. The class has
features (fields) and defines methods (activities). Object is an instance of the class.

116
This is best shown with examples. Classes can be e.g. Car, Human, Ticket, Movie etc.

 Car
When we think (of a class) Car, we do not mean a specific car, but only a vehicle that has the
characteristics of a car, e.g., model, brand, registration number, year of manufacture, color,
number of doors, body type, mileage etc. Additionally, the car has a behavior, such as moving
(forward, backward), opening doors, windows, playing music, and closing and opening. What
can the 'Car' class objects be like? Objects are all specific cars that we can clearly identify. It
can be, for example, a red Toyota Yaris from 2016 with the registration number GD 98744, a
silver Mercedes CLK from 2018 with the registration number WE 66655.
 Human
When I say: "I see a man", you do not know exactly which person I see. All we know is that it is
a creature with human characteristics. These characteristics define a person and at the same
time distinguish individuals from one another. Thus, the 'Human' class can define such
characteristics as: date of birth, first name, surname, address, eye color, hair color, weight,
height or gender. Only * giving * these features can clearly indicate a specific person. Any
person is an instance of the 'Human' class, eg each of us.

 Clase și obiecte
 Cheia este să înțelegem diferența dintre o clasă și un obiect. Pentru
evidență:
 Clasa este un șablon, formulă, rețetă pentru un obiect. Definirea unui nou
tip de date. Clasa are caracteristici (câmpuri) și definește metode
(activități). Object este o instanță a clasei.
 Acest lucru este cel mai bine arătat cu exemple. Clasele pot fi de ex.
Mașină, uman, bilet, film etc.
 • Mașină
 Când ne gândim (la o clasă) Autoturism, nu ne referim la o anumită
mașină, ci doar la un vehicul care are caracteristicile unei mașini, de
exemplu, model, marcă, număr de înmatriculare, an de fabricație, culoare,
număr de uși, caroserie tip, kilometraj etc. În plus, mașina are un
comportament, cum ar fi deplasarea (înainte, înapoi), deschiderea ușilor,
geamurilor, redarea muzicii și închiderea și deschiderea. Cum pot fi
obiectele din clasa „Mașină”? Obiectele sunt toate mașini specifice pe
care le putem identifica clar. Poate fi, de exemplu, o Toyota Yaris roșie
din 2016 cu numărul de înmatriculare GD 98744, un Mercedes CLK
argintiu din 2018 cu numărul de înmatriculare WE 66655.
 • Uman
 Când spun: „Văd un bărbat”, nu știi exact pe ce persoană văd. Tot ce știm
este că este o creatură cu caracteristici umane. Aceste caracteristici
definesc o persoană și, în același timp, disting indivizii unul de celălalt.
Astfel, clasa „Uman” poate defini astfel de caracteristici precum: data

117
nașterii, prenume, prenume, adresă, culoarea ochilor, culoarea părului,
greutatea, înălțimea sau sexul. Doar * oferirea * acestor caracteristici
poate indica în mod clar o anumită persoană. Orice persoană este o
instanță a clasei „Umane”, de exemplu fiecare dintre noi.

 Film
In order to clearly indicate a specific film, you can give its title, director, year of production,
etc. Examples (objects of the "Film" class) may be, for example, "The Matrix" by the
Wachowski brothers from 1999 or "Terminator" by James Cameron from 1984.

We, as programmers, define what features of the objects we want to store and define them in

Film
classes - this is called abstraction.

Pentru a indica clar un anumit film, îi puteți da titlul, regizorul, anul de


producție etc. Exemple (obiecte din clasa „Film”) pot fi, de exemplu, „The
Matrix” de frații Wachowski din 1999 sau „Terminator” de James Cameron din
1984.
Noi, ca programatori, definim ce caracteristici ale obiectelor dorim sa stocam si
le definim in clase - aceasta se numeste abstractizare.

When do we create classes?


If several variables often appear close to each other, if several variables together constitute a
whole, it is worth grouping them and creating (naming) a class. For example, if we work with first
name, surname and social security number, it is worth grouping these data into the
class Human orPerson and store this data under one type.

When, for example, we work with geometric figures, instead of storing a lot of variables - it is worth
creating classes with appropriate fields and methods in them. E.g:

 Wheel
We have a variable r holding the radius. We can create a Wheel class with anr field and
the getField() and getPerimeter() methods.
 Square
We have a variable a that stores the length of the side. We can create a class Square with a
fielda and methods getField () and getPerimeter()
 Rectangle
We have variables a andb that store the side lengths. We can create a class Rectangle with a
field a and methods getField() and getPerimeter().
 Triangle
We have variables a andh which store the length of the side and the height (lowered to that
side) respectively. We can create a class Triangle with the a and h fields and
thegetField()method.

 Când creăm clase?


 Dacă mai multe variabile apar adesea aproape una de alta, dacă mai multe
variabile împreună constituie un întreg, merită să le grupezi și să creăm

118
(numiți) o clasă. De exemplu, dacă lucrăm cu prenume, prenume și
numărul de securitate socială, merită să grupăm aceste date în clasa Om
sau Persoană și să stocăm aceste date sub un singur tip.
 Când, de exemplu, lucrăm cu figuri geometrice, în loc să stocăm o
mulțime de variabile - merită să creăm clase cu câmpuri și metode
adecvate în ele. De exemplu:
 • Roata
 Avem o variabilă r care ține raza. Putem crea o clasă Wheel cu câmpul
anr și metodele getField() și getPerimeter().
 • Pătrat
 Avem o variabilă a care stochează lungimea laturii. Putem crea o clasă
Square cu un câmp și metode getField() și getPerimeter()
 • Dreptunghi
 Avem variabilele a și b care stochează lungimile laturilor. Putem crea o
clasă Rectangle cu un câmp a și metode getField() și getPerimeter().
 • Triunghi
 Avem variabilele a andh care stochează lungimea laturii și respectiv
înălțimea (coborâtă în acea parte). Putem crea o clasă Triunghi cu
câmpurile a și h și metoda getField().

Object creation - constructors


A constructor is a special method that creates an instance of a class, or an object. In the example
with the Car class, the constructor was defined like this:
public Car() {

It is a method with the same name as class, which does not declare the return type! At first

glance, it differs from the other methods. We call this constructor argumentless. The constructor is

Crearea obiectelor - constructori


a good place to initialize the state of an object.

Un constructor este o metodă specială care creează o instanță a unei clase sau a
unui obiect. În exemplul cu clasa Car, constructorul a fost definit astfel:
masina publica() {

119
Este o metodă cu același nume ca și class, care nu declară tipul de returnare! La
prima vedere, diferă de celelalte metode. Numim acest constructor fără
argument. Constructorul este un loc bun pentru a inițializa starea unui obiect.

Defining constructors
Let us consider a class representing a dice that only stores the result of the dice roll. Let's call her
'Dice'.
public class Dice {

private int value;


}

If we define a constructor (no arguments) like below


public class Dice {

private int value;

public Dice() {

}
}

then it will be possible to create an object of class Dice, which (once created) will be in an"
undefined "state. Therefore, constructors are often defined in such a way that they allow setting
all required, important, unambiguous properties. For the 'Dice' class, it might look like this
public class Dice {

private int value;

public Dice(int value) {


this.value = value;
}
}

 the constructor takes a value parameter

Definirea constructorilor
we assign the value of the variable value to a class field namedvalue

Să considerăm o clasă care reprezintă un zar care stochează doar rezultatul


aruncării zarurilor. Să-i spunem „Zarurile”.
zaruri de clasă publică {

valoare int privat;


}
Dacă definim un constructor (fără argumente) ca mai jos
zaruri de clasă publică {

valoare int privat;

120
zaruri publice() {
}
}
atunci va fi posibil să se creeze un obiect din clasa Dice, care (odată creat) va fi
într-o stare "nedefinită". Prin urmare, constructorii sunt adesea definiți în așa fel
încât să permită stabilirea tuturor proprietăților necesare, importante și lipsite de
ambiguitate. Pentru clasa „Zaruri”, ar putea arăta așa
zaruri de clasă publică {

valoare int privat;

public Dice(int value) {


aceasta.valoare = valoare;
}
}
• constructorul preia un parametru valoare
• atribuim valoarea valorii variabilei unui câmp de clasă numit valoare
Important

The notation this.value means that we point to the field of this class namedvalue.

Note

The public keyword before a constructor name means that it is "public", "accessible from
everywhere". The access levels (the public andprivate modifiers) are beyond the scope of this
manual.

Now, when creating an instance of the Dice class, we need to provide a value (result). This
prevents us from creating a cube object with an undefined result.

When designing the constructor, think about what fields should be set right after creating the!

Note

A class can have several constructors, but they must differ in the number (and / or type) of

parameters.Important
Notația this.value înseamnă că indicăm câmpul acestei clase numitevalue.
Notă
Cuvântul cheie public înaintea numelui unui constructor înseamnă că este
„public”, „accesibil de oriunde”. Nivelurile de acces (modificatorii public și
privat) depășesc domeniul de aplicare al acestui manual.
121
Acum, când creăm o instanță a clasei Dice, trebuie să furnizăm o valoare
(rezultat). Acest lucru ne împiedică să creăm un obiect cub cu un rezultat
nedefinit.
Când proiectați constructorul, gândiți-vă la ce câmpuri ar trebui setate imediat
după crearea!
Notă
O clasă poate avea mai mulți constructori, dar aceștia trebuie să difere prin
numărul (și/sau tipul) de parametri.

Calling the constructors


Constructor is a special method. To call the constructor, we use the new keyword. We have already
created instances of classes provided by Java
String text = new String("Hello, World!");
Integer i = new Integer(15);
Character c = new Character('a');

To create an object (instance) of the Dice class, just type


Dice dice = new Dice(6);

In the dice variable we store a reference to an object of theDice class. Additionally (in the

constructor) we set the value of the value field to6. Now we can call methods on the variable dice.

Apelarea constructorilor
Constructorul este o metodă specială. Pentru a apela constructorul, folosim
cuvântul cheie nou. Am creat deja instanțe de clase furnizate de Java
String text = new String ("Bună ziua, lume!");
Integer i = new Integer(15);
Caracterul c = caracter nou('a');
Pentru a crea un obiect (instanță) din clasa Dice, trebuie doar să tastați
zaruri zaruri = zaruri noi(6);
În variabila zar stocăm o referință la un obiect din clasa zaruri. În plus (în
constructor) setăm valoarea câmpului de valoare la 6. Acum putem apela
metode pe zarul variabil.

Fields and methods


Now let's go back to the fields (attributes, state) and methods (actions) of classes. We will define
the (mentioned) class describing the triangle - Triangle.
public class Triangle {

private int a;

122
private int b;
private int c;

public Triangle(int a, int b, int c) {


this.a = a;
this.b = b;
this.c = c;
}
}

We have defined three variables (class fields) of the type int that store the lengths of the sides of

Domenii și metode
the triangle.

Acum să revenim la câmpurile (atribute, stare) și metode (acțiuni) ale claselor.


Vom defini clasa (menționată) care descrie triunghiul - Triunghi.
triunghi de clasă publică {

private int a;
private int b;
private int c;

public Triunghi(int a, int b, int c) {


aceasta.a = a;
aceasta.b = b;
aceasta.c = c;
}
}
Am definit trei variabile (câmpuri de clasă) de tip int care stochează lungimile
laturilor triunghiului
Note

Class fields will usually be prefixed with the private keyword (modifier). Access levels are beyond
the scope of this Coursebook, but let me just mention that the point is that the class members are
not directly "visible" to the outside, because we would then have no control over who reads them
and when and - most of all - modifies!

When creating a new data type, we declare its components (attributes) that will characterize it.
These are the * fields of the * class in which we store the state of the objects.

We can now create several instances of the Triangle class.


Triangle equilateral = new Triangle(6, 6, 6); // equilateral
Triangle isosceles = new Triangle(6, 6, 4); // isosceles
Triangle pythagorean = new Triangle(3, 4, 5); // pythagorean
Triangle triangle = new Triangle(1, 3, 10); // a triangle for sure?

Class fields are used to store the state of objects. Methods for performing operations on an object.

123
We can define a method that checks whether the given values are correct, i.e. whether the given
side lengths can form a triangle.
public boolean isValid() {
if ((a + b) > c && (a + c) > b && (b + c) > a) {
return true;
} else {
return false;
}
}

A triangle has the property that the sum of any two sides must be greater than the remaining side.

Let's call this method on the created objects. We will create a new class with a main method in

Notă
which we will create objects and call methods.

Câmpurile de clasă vor fi de obicei prefixate cu cuvântul cheie privat


(modificator). Nivelurile de acces depășesc domeniul de aplicare al acestui
Manual de curs, dar permiteți-mi doar să menționez că ideea este că membrii
clasei nu sunt direct „vizibili” în exterior, pentru că atunci nu am avea nici un
control asupra cine le citește și când și - majoritatea toate - se modifică!
La crearea unui nou tip de date, declarăm componentele (atributele) acestuia
care îl vor caracteriza. Acestea sunt câmpurile * ale clasei * în care stocăm
starea obiectelor.
Acum putem crea mai multe instanțe ale clasei Triunghi.
Triunghi echilateral = triunghi nou(6, 6, 6); // echilateral
Triunghi isoscel = triunghi nou(6, 6, 4); // isoscel
Triunghi pitagoreic = triunghi nou(3, 4, 5); // pitagoreică
Triunghi triunghi = triunghi nou(1, 3, 10); // un triunghi sigur?
Câmpurile de clasă sunt folosite pentru a stoca starea obiectelor. Metode de
efectuare a operațiunilor asupra unui obiect.
Putem defini o metodă care verifică dacă valorile date sunt corecte, adică dacă
lungimile laturilor date pot forma un triunghi.
public boolean isValid() {
dacă ((a + b) > c && (a + c) > b && (b + c) > a) {
returnează adevărat;
} altfel {
returnează fals;
}
}
Un triunghi are proprietatea că suma oricăror două laturi trebuie să fie mai mare
decât latura rămasă.

124
Să numim această metodă pe obiectele create. Vom crea o nouă clasă cu o
metodă principală în care vom crea obiecte și metode de apelare.

public class TriangleApp {

public static void main(String[] args) {


Triangle equilateral = new Triangle(6, 6, 6);
Triangle isosceles = new Triangle(6, 6, 4);
Triangle pythagorean = new Triangle(3, 4, 5);
Triangle triangle = new Triangle(1, 3, 10);

System.out.println(equilateral.isValid());
System.out.println(isosceles.isValid());
System.out.println(pythagorean.isValid());
System.out.println(triangle.isValid());
}
}

Result
true
true
true
false

So in the variable triangle we are storing an object of classTriangle, which is "degenerate", invalid.

Deci, în triunghiul variabil


We will continue to use only the remaining, valid objects.

stocăm un obiect din classTriangle, care este „degenerat”, invalid. Vom


continua să folosim doar obiectele rămase, valabile
Note

We do not cover the exception mechanism in this coursebook, which would be useful in this case to
prevent the creation of an invalid object. I'm just mentioning it so you know that Java is prepared
for this type of situation.

Now let's define another methods for calculating the area and perimeter of the triangle.
public double getField() {
// Heron's formula
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}

public int getPerimeter() {


return a + b + c;
}

By running these methods we get


18
16
12

Notă
Nu acoperim mecanismul de excepție în acest manual de curs, care ar fi util în
acest caz pentru a preveni crearea unui obiect nevalid. Îl menționez doar ca să
știți că Java este pregătit pentru acest tip de situație.
125
Acum să definim alte metode pentru calcularea ariei și perimetrului triunghiului.
public dublu getField() {
// Formula lui Heron
dublu p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}

public int getPerimeter() {


returnează a + b + c;
}
Prin rularea acestor metode obținem
18
16
12
Getters and setters
So far, we can define fields, methods, constructors and create objects. There are also special
methods, which we call getter (accessor) and setter (mutator).

When we define a class field, we can also create a method to return the value of that field and/or a

method * to set the value of that field. The first method is getter and the second issetter. Getters
și setters
Până acum, putem defini câmpuri, metode, constructori și crea obiecte. Există și
metode speciale, pe care le numim getter (accesor) și setter (mutator).
Când definim un câmp de clasă, putem crea și o metodă pentru a returna
valoarea acelui câmp și/sau o metodă * pentru a seta valoarea acelui câmp.
Prima metodă este getter și a doua issetter.

Getters
For example, if we wanted to get and display the lengths of the sides of a triangle,
then getter methods would be useful.

Methods of type getter are named by adding ``get``to the field name, and the first letter of the field
name is capitalized. The method returns the value stored in the field, and the return type matches
the field type. Methods of the type getter are argumentless.

For example, for a field


private String name;

a getter method looks as follows

126
public String getName() {
return name;

} Getters
De exemplu, dacă dorim să obținem și să afișăm lungimile laturilor unui
triunghi, atunci metodele getter ar fi utile.
Metodele de tip getter sunt denumite prin adăugarea ``get``la numele câmpului,
iar prima literă a numelui câmpului este scrisă cu majuscule. Metoda returnează
valoarea stocată în câmp, iar tipul returnat se potrivește cu tipul câmpului.
Metodele de tip getter sunt fără argumente.
De exemplu, pentru un câmp
nume șir privat;
o metodă getter arată după cum urmează
public String getName() {
returnează numele;
}

Note

It has been assumed that for boolean fields, in thegetter methods, the prefix \ is \ is added instead
of get.
private boolean active;

public boolean isActive() {


return active;

}Notă
S-a presupus că pentru câmpurile booleene, în metodele getter, prefixul \ is \
este adăugat în loc de get.
boolean privat activ;

public boolean isActive() {


returnează activ;
}

An example of getter methods for theTriangle class.


public int getA() {
return a;
}

public int getB() {


return b;
}

public int getC() {

127
return c;
}

Let’s use the following methods:


Triangle pythagorean = new Triangle(3, 4, 5);

System.out.println("side A: " + pythagorean.getA());


System.out.println("side B: " + pythagorean.getB());
System.out.println("side C: " + pythagorean.getC());
System.out.println("correct: " + (pythagorean.isValid() ? "yes" : "no"));
if (pythagorean.isValid()) {
System.out.println("field: " + pythagorean.getField());
System.out.println("perimeter: " + pythagorean.getPerimeter());
}

Triangle triangle = new Triangle(1, 3, 10);

System.out.println("side A: " + triangle.getA());


System.out.println("side B: " + triangle.getB());
System.out.println("side C: " + triangle.getC());
System.out.println("correct: " + (triangle.isValid() ? "yes" : "no"));
if (triangle.isValid()) {
System.out.println("field: " + triangle.getField());
System.out.println("perimeter: " + triangle.getPerimeter());
}

Result:
Side A: 3
side B: 4
side C: 5
correct: yes
field: 6.0
perimeter: 12
side A: 1
side B: 3
side C: 10
correct: no

Setters
For example, if we wanted to change the values of the side lengths of a triangle,
then setter methods would be useful.

Methods of type setter are named by adding the prefix ``set``to the field name, and the first letter of
the field name is capitalized. The method returns the type of void, and its (only) argument type
matches the type of the field.

For example, for a field


private String name;

A setter method looks as follows


public void setName(String name) {
this.name = name;

}Setters
De exemplu, dacă dorim să schimbăm valorile lungimii laturilor unui triunghi,
atunci metodele de setare ar fi utile.
Metodele de tip setter sunt denumite prin adăugarea prefixului ``set``la numele
câmpului, iar prima literă a numelui câmpului este scrisă cu majuscule. Metoda
128
returnează tipul de void, iar tipul său de argument (singurul) se potrivește cu
tipul câmpului.
De exemplu, pentru un câmp
nume șir privat;
O metodă setter arată după cum urmează
public void setName(Nume șir) {
this.name = nume;
}

Note

Again, I emphasize the difference between: this.name andname.


this.name points to thename field of the current (this) class.
name points to the name of the parameter of thesetName (String name)method.

Notă
This provision is used to prevent name collisions.

Din nou, subliniez diferența dintre: acest.nume și nume.


this.name indică câmpul de nume al clasei curente (această).
name indică numele parametrului metodei thesetName (nume șir).
Această prevedere este folosită pentru a preveni coliziunile de nume.

An example of setter methods for the Triangle class.


public void setA(int a) {
this.a = a;
}

public void setB(int b) {


this.b = b;
}

public void setC(int c) {


this.c = c;
}

With these methods, we can "fix" the triangle defined in the variable triangle.
Triangle triangle = new Triangle(1, 3, 10);
System.out.println("correct: " + (triangle.isValid() ? "yes" : "no"));
triangle.setA(8);
System.out.println("correct: " + (triangle.isValid() ? "yes" : "no"));

Result
correct: no

correct: yes Un exemplu de metode setter pentru clasa Triangle.

129
public void setA(int a) {
aceasta.a = a;
}

public void setB(int b) {


aceasta.b = b;
}

public void setC(int c) {


aceasta.c = c;
}
Cu aceste metode, putem „repara” triunghiul definit în triunghiul variabil.
Triunghi triunghi = triunghi nou(1, 3, 10);
System.out.println ("corect: " + (triangle.isValid() ? "da": "nu"));
triunghi.setA(8);
System.out.println ("corect: " + (triangle.isValid() ? "da": "nu"));
Rezultat
corect: nu
corect: da
Note

As a programmer, you decide which fields you want to make getters available to and

which setters. If you don't want an outsider to change the value of the field - don't generate

a setter. If you don't want an outsider to be able to read the value of a given field - don't generate

a getter.Notă
În calitate de programator, tu decideți pentru ce câmpuri doriți să puneți getters
la dispoziție și pentru care setari. Dacă nu doriți ca un străin să schimbe
valoarea câmpului - nu generați un setter. Dacă nu doriți ca un străin să poată
citi valoarea unui anumit câmp - nu generați un getter.
toString() method
The toString() method is another "special" method. Its task is textual representation of the state of
the object. All relevant information should be included in this representation. We can call
the toString() method explicitly (just like the other methods), but we often pass a variable to
the System.out.println() method, which - on a reference variable - automatically calls its toString()
method.

Coming back to the Dice class for a moment, you could define the following toString()method for it:

130
public class Dice {

private int value;

public Dice(int value) {


this.value = value;
}

public String toString() {


return "[" + value + "]";
}
}

Creating several instances and calling toString()


public class DiceApp {

public static void main(String[] args) {


Dice one = new Dice(1);
Dice six = new Dice(6);

System.out.println(one.toString());
System.out.println(one);
System.out.println(six.toString());
System.out.println(six);
}
}

Result:
[1]
[1]
[6]

[6]metoda toString().
Metoda toString() este o altă metodă „specială”. Sarcina sa este reprezentarea
textuală a stării obiectului. Toate informațiile relevante ar trebui incluse în
această reprezentare. Putem apela metoda toString() în mod explicit (la fel ca și
celelalte metode), dar adesea trecem o variabilă metodei System.out.println(),
care - pe o variabilă de referință - își apelează automat metoda toString().
Revenind la clasa Dice pentru un moment, puteți defini următoarea metodă
toString() pentru aceasta:
zaruri de clasă publică {

valoare int privat;

public Dice(int value) {


aceasta.valoare = valoare;
}

public String toString() {

131
returnează „[” + valoare + „]”;
}
}
Crearea mai multor instanțe și apelarea toString()
clasă publică DiceApp {

public static void main(String[] args) {


Dice one = nou Dice(1);
Dice six = nou Dice(6);

System.out.println(one.toString());
System.out.println(unul);
System.out.println(six.toString());
System.out.println(sase);
}
}
Rezultat:
[1]
[1]
[6]
[6]

Note

Every class in Java has a toString () method declared. What we did above is to * override * this
default method. Try not to override the toString () method in the Dice class and call it; something
similar to
Dice@71318ec4

where:

 Dice - is the class name


 71318ec4 - stands for hash code (numeric value) written in hexadecimal form

Overriding or overriding methods and the hashCode () and equals () methods are beyond the scope of

Notă
this manual.

Fiecare clasă din Java are o metodă toString () declarată. Ceea ce am făcut mai
sus este să * suprascriem * această metodă implicită. Încercați să nu suprascrieți
metoda toString () din clasa Dice și să o apelați; ceva asemănător cu
Dice@71318ec4
132
Unde:
• Dice - este numele clasei
• 71318ec4 - reprezintă codul hash (valoare numerică) scris în formă
hexazecimală
Metodele de suprascrie sau de suprascrie și metodele hashCode () și equals ()
sunt în afara domeniului de aplicare al acestui manual.

Summary
What have we learned in this chapter?

Q: What is a class?

A: It's a recipe for an object. A template, a pattern according to which we can create various
objects.

Q: What is an object?

A: Instance, concrete example of a given class.

Q: What is the class field?

A: A feature of a given object describing the type of a given property of the object.

Q: What is the classroom method?

A: This is an operation performed on the class object.

Q: What's the naming convention for classes, methods and fields?

A: The names of the classes are written with a capital letter; methods and fields - small. If the
name consists of several words, we write it together, but we start each word with a capital letter.

Q: When do we create classes?

A: When we want to name some entity; when several variables together constitute a whole.

Q: What is a constructor?

A: This is a special method that creates an instance of the class, ie an object. It has the same
name as the class and does not declare a return type.

Q: What does the word this mean (in the context of constructors)?

rezumat
Ce am învățat în acest capitol?
Î: Ce este o clasă?

133
R: Este o rețetă pentru un obiect. Un șablon, un model după care putem crea
diverse obiecte.
Î: Ce este un obiect?
A: Exemplu, exemplu concret al unei clase date.
Î: Care este câmpul de clasă?
R: O caracteristică a unui obiect dat care descrie tipul unei proprietăți date a
obiectului.
Î: Care este metoda de clasă?
R: Aceasta este o operație efectuată pe obiectul clasei.
Î: Care este convenția de denumire pentru clase, metode și câmpuri?
R: Numele claselor sunt scrise cu majuscule; metode şi domenii – mici. Dacă
numele este format din mai multe cuvinte, îl scriem împreună, dar începem
fiecare cuvânt cu o literă mare.
Î: Când creăm clase?
R: Când vrem să numim o entitate; când mai multe variabile împreună
constituie un întreg.
Î: Ce este un constructor?
R: Aceasta este o metodă specială care creează o instanță a clasei, adică un
obiect. Are același nume ca și clasa și nu declară un tip de returnare.
Î: Ce înseamnă cuvântul asta (în contextul constructorilor)?

A: You can often see this.value = value in constructors. This means that the value (constructor
parameter) is assigned to thevalue variable (class field). To distinguish a constructor parameter
name from a class field name, the word this is used to indicate that it is a field of that class.

Q: How do we call constructors in Java?

A: Constructors in Java are special methods that we call in a special way. The word 'new' is used
for this. For example
String text = new String("Hello, World!");
Date today = new Date();

Q: What are getters?

A: Getters (accessors) are methods that return the value of a given field. They are created by
appending the \ get \ prefix to the field name, and the first letter of the field name is capitalized.
The method returns the value stored in the field and the return type matches the field type. Methods
of the type getter are * argumentless . It has been assumed that for boolean fields in
thegetter methods, the prefix \ is * \ is added instead of get.

Q: What are setters?

134
A: Setters (mutators) are methods that set the value of a given field. They are created by appending
the ``set`` prefix to the field name, and the first letter of the field name is capitalized. The method
returns the type of void, and its (only) argument type matches the type of the field.

Q: What is the toString() method?

A: This is a "special" method. Its task is textual representation of the state of the object. All

relevant information should be included in this representation. Every class in Java has

R: Puteți vedea adesea this.value = value în


a toString() method declared.

constructori. Aceasta înseamnă că valoarea (parametrul constructorului) este


atribuită variabilei valoare (câmpul de clasă). Pentru a distinge un nume de
parametru constructor de numele unui câmp de clasă, cuvântul this este folosit
pentru a indica faptul că este un câmp al acelei clase.
Î: Cum numim constructori în Java?
R: Constructorii din Java sunt metode speciale pe care le numim într-un mod
special. Cuvântul „nou” este folosit pentru aceasta. De exemplu
String text = new String ("Bună ziua, lume!");
Data azi = data noua();
Î: Ce sunt getters?
R: Getters (accesorii) sunt metode care returnează valoarea unui anumit câmp.
Acestea sunt create prin adăugarea prefixului \ get \ la numele câmpului, iar
prima literă a numelui câmpului este scrisă cu majuscule. Metoda returnează
valoarea stocată în câmp, iar tipul returnat se potrivește cu tipul câmpului.
Metodele de tip getter sunt * fără argumente. S-a presupus că pentru câmpurile
booleene din metodele getter, prefixul \ este * \ este adăugat în loc de get.
Î: Ce sunt setterii?
R: Setarii (mutatorii) sunt metode care stabilesc valoarea unui anumit câmp.
Acestea sunt create prin adăugarea prefixului ``set`` la numele câmpului, iar
prima literă a numelui câmpului este scrisă cu majuscule. Metoda returnează
tipul de void, iar tipul său de argument (singurul) se potrivește cu tipul
câmpului.
Î: Ce este metoda toString()?
R: Aceasta este o metodă „specială”. Sarcina sa este reprezentarea textuală a
stării obiectului. Toate informațiile relevante ar trebui incluse în această
reprezentare. Fiecare clasă din Java are o metodă toString() declarată.
Exercises
 Create a Person class

135
 add fields: name, surname, gender, age, pesel
 add a method to check whether a given person has reached retirement age
(e.g. hasReachedRetirementAge()); for women, let's assume the retirement age is >=60 years, and
for men >=65 years
 add a method that returns the age difference from one person to another
 let the method take a parameter of type Person
 it should not return negative values as the difference of years
 add a method that calculates and returns how many years are left before retirement
 Create a Computerclass
 public class Computer {

 // mandatory fields
 private String motherboard; // motherboard
 private String processor; // "i5", "i7", "intel", "amd"
 private int cores; // number of cores
 private int ram; // amount of RAM

 // additional fields
 private int hd; // disk size in GB
 private String monitor; // producer name
 private String printer; // printer name

 public Computer(String motherboard, String processor, int cores, int ram) {

 }
 }

 complete the constructor with value assignment


 add a toString()method
 add methods getter and setter
 test how it works
 the processor and cores fields merge with each other - let's create a separate class for them
 public class Processor {

 private String name; // procesor name
 private int cores; // number of cores
 }

 add a proper constructor


 add methods getter and setter
 add a toString() method
 change the Computer class to use theProcessor class now `
 public class Computer {

 Exerciții
 • Creați o clasă Persoană
 • adăugați câmpuri: nume, prenume, sex, vârstă, pesel
 • adăugați o metodă pentru a verifica dacă o anumită persoană a atins
vârsta de pensionare (de exemplu, hasReachedRetirementAge()); pentru
femei, să presupunem că vârsta de pensionare este >=60 de ani, iar pentru
bărbați >=65 de ani
136
 • adăugați o metodă care returnează diferența de vârstă de la o persoană la
alta
 • lasă metoda să ia un parametru de tip Person
 • nu ar trebui să returneze valori negative ca diferență de ani
 • adăugați o metodă care calculează și returnează câți ani au mai rămas
înainte de pensionare
 • Creați o clasă de computere
 • calculator de clasă publică {
 •
 • // câmpuri obligatorii
 • placă de bază String privată; // placa de baza
 • procesor String privat; // "i5", "i7", "intel", "amd"
 • nuclee int private; // numărul de nuclee
 • private int ram; // cantitatea de RAM
 •
 • // câmpuri suplimentare
 • private int hd; // dimensiunea discului în GB
 • monitor String privat; // numele producătorului
 • imprimantă String privată; // numele imprimantei
 •
 • Computer public (placă de bază String, procesor String, int nuclee, int
ram) {
 •
 •}
 •}
 • completați constructorul cu atribuirea valorii
 • adăugați o metodă toString().
 • adăugați metode getter și setter
 • testați cum funcționează
 • câmpurile procesor și nuclee se îmbină unele cu altele - să creăm o clasă
separată pentru ele
 • Procesor de clasă publică {
 •
 • nume String privat; // numele procesorului

137
 • nuclee int private; // numărul de nuclee
 •}
 • adăugați un constructor adecvat
 • adăugați metode getter și setter
 • adăugați o metodă toString().
 • schimbați clasa Computer pentru a utiliza clasa Processor acum `
 • calculator de clasă publică {
 // mandatory fields
 private String motherboard; // motherboard
 private Processor processor;
 private int ram; // amount of RAM

 // additional fields
 private int hd; // disk size in GB
 private String monitor; // producer name
 private String printer; // printer name

 public Computer(String motherboard, Processor processor, int ram) {

 }
 }

 // câmpuri obligatorii
 • placă de bază String privată; // placa de baza
 • procesor procesor privat;
 • private int ram; // cantitatea de RAM
 •
 • // câmpuri suplimentare
 • private int hd; // dimensiunea discului în GB
 • monitor String privat; // numele producătorului
 • imprimantă String privată; // numele imprimantei
 •
 • computer public (placă de bază String, procesor procesor, int ram) {
 •
 •}
 •}

 RAM chips can come in various configurations, create a class


RAM and put the appropriate
fields in it (e.g.name and size)
 suppose there can be 4 RAM bones on the board - create a 4-element array for
elements of the RAM class

138
 public class Computer {

 // mandatory fields
 private String motherboard; // motherboard
 private Processor processor;
 private RAM[] ramSlots; // RAM chips

 // additional fields
 private int hd; // disk size in GB
 private String monitor; // producer name
 private String printer; // printer name

 public Computer(String motherboard, Processor processor, Ram ram) {

 }

 in the constructor put a variable Ram ram that specifies a single RAM chip given when
creating the computer; remember to initialize the ramSlots array
 add a method that allows you to add more RAM dice - watch out for slot restrictions;
in case of insufficient space, you can e.g. remove the smallest bone and replace it
with the given one (if it is not smaller)
 on the basis of RAM, perform a similar change with hard disks - there may also be several
of them in the computer; have a different capacity and manufacturer (and e.g. type and
speed)
 other variables (monitor, printer) can also be converted into classes - a computer can have
several monitors and printers, each of them has its own parameters
 add more peripherals to the computer
 run and test every time
 customize the toString() method to display the required data
 consider a method that compares two computer sets

Cipurile
for example, assign some weights to the parts and calculate a score based on them

RAM pot veni în diferite configurații, pot crea o clasă RAM și pot pune
câmpurile corespunzătoare în ea (de exemplu, nume și dimensiune)
• să presupunem că pot exista 4 oase RAM pe placă - creați o matrice de 4
elemente pentru elementele clasei RAM
• calculator de clasă publică {

• // câmpuri obligatorii
• placă de bază String privată; // placa de baza
• procesor procesor privat;
• RAM private[] ramSlots; // cipuri RAM

• // câmpuri suplimentare
• private int hd; // dimensiunea discului în GB
• monitor String privat; // numele producătorului

139
• imprimantă String privată; // numele imprimantei

• Computer public (placă de bază String, procesor procesor, RAM ram) {

•}
• în constructor puneți o variabilă Ram ram care specifică un singur cip RAM
dat la crearea computerului; nu uitați să inițializați matricea ramSlots
• adăugați o metodă care vă permite să adăugați mai multe zaruri RAM - aveți
grijă la restricțiile de slot; în caz de spațiu insuficient, puteți de ex. scoateți cel
mai mic os și înlocuiți-l cu cel dat (dacă nu este mai mic)
• pe baza memoriei RAM, efectuați o schimbare similară cu hard disk-urile - pot
exista și mai multe dintre ele în computer; au o capacitate și un producător
diferit (și, de exemplu, tip și viteză)
• alte variabile (monitor, imprimantă) pot fi, de asemenea, convertite în clase -
un computer poate avea mai multe monitoare și imprimante, fiecare dintre ele
având propriii parametri
• adăugați mai multe periferice la computer
• rulați și testați de fiecare dată
• personalizați metoda toString() pentru a afișa datele necesare
• luați în considerare o metodă care compară două seturi de calculatoare
• de exemplu, atribuiți niște ponderi părților și calculați un scor pe baza acestora

Conclusion
Conclusion
Object-oriented programming was the last topic covered by this Handbook. At this point, you should
be able to use basic Java components and build simple programs from them. You already know that
Java provides many types of data that you can use in your programs. If necessary, you can define
your own data type and provide operations in it. These operations can use conditional statements,
operators or loops.

Now you are ready for the next part of information about Java that have not been included in this
Handbook:

 interfaces, abstract classes and enumeration types


 file management
 inheritance, composition and polymorphism

140
 collections
 cohesive and parallel programming
 exception mechanism
 functional programming

 Concluzie
 Concluzie
 Programarea orientată pe obiecte a fost ultimul subiect acoperit de acest
manual. În acest moment, ar trebui să puteți utiliza componente Java de
bază și să construiți programe simple din acestea. Știți deja că Java oferă
multe tipuri de date pe care le puteți utiliza în programele dvs. Dacă este
necesar, vă puteți defini propriul tip de date și puteți furniza operațiuni în
el. Aceste operațiuni pot folosi instrucțiuni condiționale, operatori sau
bucle.
 Acum sunteți pregătit pentru următoarea parte a informațiilor despre Java
care nu au fost incluse în acest manual:
 • interfeţe, clase abstracte şi tipuri de enumerare
 • gestionarea fișierelor
 • moștenirea, compoziția și polimorfismul
 • colecţii
 • programare coerentă și paralelă
 • mecanism de excepţie
 • programare funcţ

Literature
 James Gosling, Henry McGilton. The Java Language Environment. A White Paper. 1996.
 Code Conventions for the Java™ Programming Language. 1999.
 Cay S. Horstman. Java. Podstawy. Edition X. Helion. 2016.
 Cay S. Horstman. Java. Techniki zaawansowane. Edition X. Helion. 2017.

Assignments
Sarcini
Write a program that will display a multiplication table to one hundred.

1. Scrieți un program care va afișa o tabelă de înmulțire la o sută.


1.
2. 1 2 3 4 5 6 7 8 9 10
3. 2 4 6 8 10 12 14 16 18 20
4. 3 6 9 12 15 18 21 24 27 30
5. 4 8 12 16 20 24 28 32 36 40
6. 5 10 15 20 25 30 35 40 45 50
7. 6 12 18 24 30 36 42 48 54 60

141
8. 7 14 21 28 35 42 49 56 63 70
9. 8 16 24 32 40 48 56 64 72 80
10. 9 18 27 36 45 54 63 72 81 90
11. 10 20 30 40 50 60 70 80 90 100

For formatting, you can use the String.format() function:


String.format("%4s", <value-to-display>)

 displays
%4s the value on 4 characters aligning to the right.
WYou can find more information about the format() function here

Extend the multiplication table with horizontal and vertical lines and borders composed of

characters |, - and +. For the table to 9 it could look like below. Pentru formatare, puteți
folosi funcția String.format():
String.format(„%4s”, <valoare de afișat>)
• %4s afișează valoarea pe 4 caractere aliniate la dreapta.
WPuteți găsi mai multe informații despre funcția format() aici
12. Extindeți tabelul înmulțirii cu linii orizontale și verticale și margini compuse
din caractere |, - și +. Pentru tabelul până la 9 ar putea arăta ca mai jos.
12.
13. +---+---+---+
14. | 1 | 2 | 3 |
15. +---+---+---+
16. | 2 | 4 | 6 |
17. +---+---+---+
18. | 3 | 6 | 9 |
19. +---+---+---+

Write a program that would draw the following patterns 20. Scrieți un program care să
deseneze următoarele modele
20.

a. Triangle 1
b. #
c. # #
d. # # #
e. # # # #
f. # # # # #
g. # # # # # #
h. # # # # # # #
i. # # # # # # # #

j. Triangle 2
k. # # # # # # # #
l. # # # # # # #
m. # # # # # #
n. # # # # #
o. # # # #
p. # # #
q. # #
r. #

s. Triangle 3

142
t. #
u. # #
v. # # #
w. # # # #
x. # # # # #
y. # # # # # #
z. # # # # # # #
aa. # # # # # # # #

bb. Triangle 4
cc. # # # # # # # #
dd. # # # # # # #
ee. # # # # # #
ff. # # # # #
gg. # # # #
hh. # # #
ii. # #
jj. #

kk. Square
ll. # # # # # # #
mm. # #
nn. # #
oo. # #
pp. # #
qq. # #
rr. # # # # # # #

ss. Letter S
tt. # # # # # # #
uu. #
vv. #
ww. #
xx. #
yy. #
zz. # # # # # # #
aaa. Letter Z
bbb. # # # # # # #
ccc. #
ddd. #
eee. #
fff. #
ggg. #
hhh. # # # # # # #

iii. Hourglass
jjj. # # # # # # #
kkk. # #
lll. # #
mmm. #
nnn. # #
ooo. # #
ppp. # # # # # # #

qqq. Square with diagonals


rrr. # # # # # # #

143
sss. # # # #
ttt. # # # #
uuu. # # #
vvv. # # # #
www. # # # #
xxx. # # # # # # #

yyy. Based on the above figures, propose your own ones; try also to fill in the selected
parts of the figures.

zzz. Transfer the logic displaying the above figures to separate methods that take the
size (e.g. a parameter named size) of the figure (the number of characters in the figure) as
a parameter.

Write a program multiplies the digits for a given number (as String) until the result is a one-digit

aaa. Pe baza cifrelor de mai sus, propune-le propriile tale; încercați,


number. E.g.

de asemenea, să completați părțile selectate ale figurilor.


zzz. Transferați logica care afișează cifrele de mai sus în metode separate care
iau dimensiunea (de exemplu, un parametru numit dimensiune) figurii (numărul
de caractere din figură) ca parametru.
21. Scrie un program înmulțește cifrele pentru un număr dat (sub formă de șir)
până când rezultatul este un număr de o cifră. De exemplu.

Example for "123".


123
123 → 1x2x3 = 6

Example for "277777788888899".


277777788888899
277777788888899 → 2x7x7x7x7x7x7x8x8x8x8x8x8x9x9 = 4996238671872
4996238671872 → 4x9x9x6x2x3x8x6x7x1x8x7x2 = 438939648
438939648 → 4x3x8x9x3x9x6x4x8 = 4478976
4478976 → 4x4x7x8x9x7x6 = 338688
338688 → 3x3x8x6x8x8 = 27648
27648 → 2x7x6x4x8 = 2688
2688 → 2x6x8x8 = 768
768 → 7x6x8 = 336
336 → 3x3x6 = 54
54 → 5x4 = 20
20 → 2x0 = 0

Use the code below to implement the reduce(String number) method.


public class Reducer {

public static void main(String[] args) {


Reducer reducer = new Reducer();
String numberToReduce = "<enter value here>";
int reducedValue = reducer.reduce(numberToReduce);
System.out.println("Number to reduce: " + numberToReduce);
System.out.println("After reduce: " + reducedValue);
}

public int reduce(String number) {


return 0;
}
}

144
Consider how to optimize this program. Hint: digit zero. Utilizați codul de mai jos pentru a
implementa metoda reduce(String number).
reductor de clasă publică {

public static void main(String[] args) {


Reductor reductor = reductor nou();
String numberToReduce = "<introduceți valoarea aici>";
int reducedValue = reducer.reduce(numberToReduce);
System.out.println("Număr de redus: " + numberToReduce);
System.out.println("După reducere: " + reducedValue);
}

public int reduce(Număr șir) {


returnează 0;
}
}
. Luați în considerare cum să optimizați acest program. Sugestie: cifra zero.
a.
Write a program that checks who won a Tic-Tac-Toe game.
a. The status of the board is presented as a String, e.g.
OX_OOXO_X
+ where: * X means a cross * O means a circle * _ mean an empty field

1. Replace the above entry with a two-dimensional array:


OX_
OOX
O_X

1. Determine who won or whether that was a tie.

2. Sample input data:


XOXXXOOOX
XOXXOOXXO
XOXXOOOXO
OX_OOXO_X
XOOXOXOXO
OXOXOOXXX

1. Adjust the program to handle uppercase and lowercase letters ( x, o, X, O) and 0 (zero) as
a circle.

a. Write a program that shortens the contents of text messages. The program should:

 remove unnecessary blank characters at the beginning and end of the contents

145
remove empty characters between words and start each word with a capital letter Example of

program operation 22. Scrieți un program care verifică cine a câștigat un joc Tic-
Tac-Toe.
. Starea tablei este prezentată ca șir, de ex.
OX_OOXO_X
+ unde: * X înseamnă o cruce * O înseamnă un cerc * _ înseamnă un câmp gol
1. Înlocuiți intrarea de mai sus cu o matrice bidimensională:
BOU_
OOX
BOU
1. Stabiliți cine a câștigat sau dacă a fost egalitate.
2. Exemplu de date de intrare:
XOXXXOOOX
XOXXOOXXO
XOXXOOOXO
OX_OOXO_X
XOOXOXOXO
OXOXOOXXX
1. Reglați programul pentru a gestiona literele mari și mici (x, o, X, O) și 0
(zero) ca un cerc.
A. Scrieți un program care scurtează conținutul mesajelor text. Programul ar
trebui să:
• eliminați caracterele goale inutile la începutul și la sfârșitul conținutului
• eliminați caracterele goale dintre cuvinte și începeți fiecare cuvânt cu o literă
majusculă Exemplu de funcționare a programului

Example of program operation
Alice has a cat, and a cat has Alice!
AliceHasACat,AndACatHasAlice!

Hey, I will be back later tonight. Do not wait with dinner for me.
Hey,IWillBebackLaterTonight.DoNotWaitWithDinnerForMe.

In addition, make the program display: * the number of characters of the original message * the
number of characters after compression * the price for sending a text message, assuming that 1
text message is 160 characters, and each message costs 25 cents.

1. Write a program that validates the correctness of a given personal ID number.


The personal ID number has the following form:
2. RRMMDDXXXXK

146
where:

 YY - year

 MM - month

 DD - day

 XXXX - ordinal number

 C - control digit

Assign the values to variables, e.g.


RRMMDDXXXXK
abcdefghijk

result = ``1``x``a`` + ``3``x``b`` + ``7``x``c`` + ``9``x``d`` + ``1``x``e`` + ``3``x``f`` + ``7``x``g`` +


``9``x``h`` + ``1``x``i`` + ``3``x``j`` + ``1``x``k``

If result % 10 = 0, the personal ID number is correct!

a.Suggest a signature for the method of validation of the personal ID number


correctness
3. A Car class is provided
4. public class Car {
5. private String model;
6. private int productionYear;
7. private String color;
8. private boolean used = false;

}Exemplu de funcționare a programului


Alice are o pisică, iar o pisică o are pe Alice!
AliceHasACat,AndACatHasAlice!

Hei, mă voi întoarce mai târziu în seara asta. Nu mă aștepta cu cina.


Hei, mă voi întoarce mai târziu în seara asta. Nu așteptați cu cina pentru mine.
În plus, faceți ca programul să afișeze: * numărul de caractere al mesajului
original * numărul de caractere după comprimare * prețul pentru trimiterea unui
mesaj text, presupunând că 1 mesaj text este de 160 de caractere, iar fiecare
mesaj costă 25 de cenți.
1. Scrieți un program care validează corectitudinea unui număr de identificare
personal dat.
Numărul de identificare personal are următoarea formă:
2. RRMMDDXXXXK
Unde:
• YY - an
• MM - luna
• DD - zi
• XXXX - număr ordinal

147
• C - cifră de control
Atribuiți valorile variabilelor, de ex.
RRMMDDXXXXK
abcdefghijk
rezultat = ``1``x``a`` + ``3``x``b`` + ``7``x``c`` + ``9``x``d`` + ``1``x``e`` +
``3``x``f`` + ``7``x``g`` + ``9``x``h`` + `` 1``x``i`` + ``3``x``j`` + ``1``x``k``
Dacă rezultatul % 10 = 0, numărul de identificare personal este corect!
A. Propuneți o semnătură pentru metoda de validare a corectitudinii codului
personal
3. Se asigură o clasă de mașini
4. mașină de clasă publică {
5. model String privat;
6. private int productYear;
7. culoare privată String;
8. boolean privat folosit = false;
9.}
9.

a. Generate getter and setter methods for all fields; use key shortcuts Alt+Ins
b. Test the Car class using the CarApplication class
c. public class CarApplication {
d. public static void main(String[] args) {
e. Car audi = new Car();
f. audi.setModel("A8");
g. audi.setColor("red");
h. audi.setProductionYear(2018);
i. audi.setUsed(true);
j. System.out.println(audi.getModel());
k. System.out.println(audi.getColor());
l. System.out.println(audi.getProductionYear());
m. System.out.println(audi.isUsed());
n. }
o. }
p. Add a field to store the mileage (int mileage) to the Car program; set the default value to 0

q. Add (generate) a getter type method for this field (getMileage())


r. Add the drive(int mileage) method that increases the mileage

s. Test the program operation


t. Modify the drive(int mileage) method to set the used field to the appropriate value; if
the mileage is positive, the used field should have value true

A. Generați metode getter și setter pentru toate câmpurile;


Test the operation

utilizați comenzile rapide Alt+Ins


148
b. Testați clasa Car folosind clasa CarApplication
c. CarApplication de clasă publică {
d. public static void main(String[] args) {
e. Car audi = masina noua();
f. audi.setModel("A8");
g. audi.setColor(„roșu”);
h. audi.setProductionYear(2018);
i. audi.setUsed(true);
j. System.out.println(audi.getModel());
k. System.out.println(audi.getColor());
l. System.out.println(audi.getProductionYear());
m. System.out.println(audi.isUsed());
n. }
o. }
p. Adăugați un câmp pentru a stoca kilometrajul (înt kilometraj) în programul
Auto; setați valoarea implicită la 0
q. Adăugați (generați) o metodă de tip getter pentru acest câmp (getMileage())
r. Adăugați metoda drive(int mileage) care crește kilometrajul
s. Testați funcționarea programului
t. Modificați metoda drive(int mileage) pentru a seta câmpul utilizat la valoarea
corespunzătoare; dacă kilometrajul este pozitiv, câmpul utilizat ar trebui să aibă
valoarea adevărată
u. Testați funcționarea

The Calculator and CalculatorApplication classes are provided


public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
public class CalculatorApplication {
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println(calc.add(5, 12));
}

}0. Sunt furnizate clasele Calculator și CalculatorApplication


11. Calculator de clasă publică {
12. public int add(int a, int b) {
13. returnează a + b;

149
14.}
15.}
16. clasă publică CalculatorApplication {
17. public static void main(String[] args) {
18. Calculator calc = nou Calculator();
19. System.out.println(calc.add(5, 12));
20.}
21.}

a. Based on the add(int a, int b) method, implement the subsequent methods:

i. int subtract(int a, int b) - subtraction: a - b

ii. int multiply(int a, int b) - multiplication: a * b

iii. double divide(int a, int b) - division: a / b

iv. boolean isPositive(int a) - checks whether the number is positive

v. boolean isNegative(int a) - checks whether the number is negative

vi. boolean isOdd(int a) - checks whether the number is odd

vii. int min(int a, int b) - returns the smaller of the numbers

viii. int max(int a, int b) - returns the greater of the numbers

ix. double average(int a, int b) - returns the average for the numbers

x. int power(int a, int x) - returns a^m^ (a to the power m)

b. Based on the solution from point a, implement 3-argument versions of these methods (try
to use 2 - argument versions of these methods):

i. int add(int a, int b, int c)

ii. int subtract(int a, int b, int c)

iii. int multiply(int a, int b, int c)

iv. double divide(int a, int b, int c)

v. int min(int a, int b, int c)

vi. int max(int a, int b, int c)

double average(int a, int b, int c) Pe baza metodei add(int a, int b), implementați metodele
ulterioare:
i. int subtract(int a, int b) - scadere: a - b
ii. int multiplicare(int a, int b) - înmulțire: a * b
iii. împărțire dublă (int a, int b) - împărțire: a / b
iv. boolean isPositive(int a) - verifică dacă numărul este pozitiv
v. boolean isNegative(int a) - verifică dacă numărul este negativ
vi. boolean isOdd(int a) - verifică dacă numărul este impar

150
vii. int min(int a, int b) - returnează cel mai mic dintre numere
viii. int max(int a, int b) - returnează cel mai mare dintre numere
ix. double average(int a, int b) - returnează media numerelor
X. int putere(int a, int x) - returnează a^m^ (a la puterea m)
A. Pe baza soluției de la punctul a, implementați versiuni cu 3 argumente ale
acestor metode (încercați să utilizați versiuni cu 2 argumente ale acestor
metode):
. int add(int a, int b, int c)
i. int scade (int a, int b, int c)
ii. int multiplicare (int a, int b, int c)
iii. dublu împărțire (int a, int b, int c)
iv. int min(int a, int b, int c)
v. int max(int a, int b, int c)
vi. medie dublă (int a, int b, int c)
vii.

Implement a stack to store Integer type numbers.


public class Stack {
public Stack(int count) {}
public void push(Integer e) {}
public Integer pop() {}
public boolean isEmpty() {}
public boolean isFull() {}
public String toString() {}
}

a. the constructor creates a count element array for storing Integer type elements

b. the push() method throws the element onto the stack (to the first free position). If the
stack is empty, a relevant message is displayed and nothing happens

c. the pop() method deletes (returns and removes from the stack) the first element from the
“top” of the stack. If the stack is empty, the method displays an appropriate message and
nothing is done (null to be returned)

d. the isEmpty() methods checks whether the stack is empty, i.e. whether there is no element
in the array

e. the isFull() method checks whether the stack is full, i.e. for example at a 5 - element
stack, all 5 array elements have a value (other than null)

f. the toString() method displays the stack contents

hint: enter an additional variable that stores the index of the current or next item in the array and

modify its value when implementing the push() and pop() methods` 22. Implementați o stivă
pentru a stoca numere de tip întreg.
23. clasă publică Stack {
24. public Stack(int count) {}

151
25. public void push(Integer e) {}
26. public Integer pop() {}
27. public boolean isEmpty() {}
28. public boolean isFull() {}
29. public String toString() {}
30.}
. constructorul creează o matrice de elemente de numărare pentru stocarea
elementelor de tip Integer
A. metoda push() aruncă elementul pe stivă (în prima poziție liberă). Dacă stiva
este goală, este afișat un mesaj relevant și nu se întâmplă nimic
b. metoda pop() șterge (returnează și scoate din stivă) primul element din „sus”-
ul stivei. Dacă stiva este goală, metoda afișează un mesaj adecvat și nu se face
nimic (nulul va fi returnat)
c. metodele isEmpty() verifică dacă stiva este goală, adică dacă nu există niciun
element în matrice
d. metoda isFull() verifică dacă stiva este plină, adică, de exemplu, la o stivă de
5 elemente, toate cele 5 elemente ale matricei au o valoare (alta decât nulă)
e. metoda toString() afișează conținutul stivei
f. indiciu: introduceți o variabilă suplimentară care stochează indexul articolului
curent sau următor în matrice și modificați valoarea acesteia atunci când
implementați metodele push() și pop()`
g.
Based on the task above, write a program that will "mimic" an array of any size that can hold
values of type Integer. There is a class:
public class IntArray {

public IntArray() {
}

public void add(Integer value) {


}

public void add(Integer value, int idx) {


}

public Integer get(int idx) {


return null;
}

public void remove(int idx) {


}

public void swap(int from, int to) {


}

152
public String toString() {
return "";
}
}

Functionalities:

 IntArray() - constructor, it should create an initial array with an initial, default size

 void add(Integer value) - adds an element to the next position; enlarges the array if necessary

 creates a new, bigger one

 rewrites the current values

 adds a new item

 - adds an element to the indicated position; if necessary, this


void add(Integer value, int idx)
is done by the method above

 Integer get(int idx) - returns the item at position idx; if not there, it returns null

 void remove(int idx) - removes the item at position idx

 void swap(int from, int to) - swap items in the from andto positions; enlarges the array if
necessary

String toString() 31. Pe baza sarcinii de mai sus, scrieți un


- displays the entire array

program care va „imita” o matrice de orice dimensiune care poate conține valori
de tip Integer. Există o clasă:
32. clasă publică IntArray {
33.
34. public IntArray() {
35.}
36.
37. public void add(Valoare întreagă) {
38.}
39.
40. public void add(Valoare întreagă, int idx) {
41.}
42.
43. public Integer get(int idx) {
44. return nul;
45.}
46.
47. public void remove(int idx) {
48.}
49.
153
50. public void swap(int from, int to) {
51.}
52.
53. public String toString() {
54. returnare „”;
55.}
56.}
Functionalitati:
• IntArray() - constructor, ar trebui să creeze o matrice inițială cu o dimensiune
inițială, implicită
• void add(Integer value) - adaugă un element la următoarea poziție; mărește
matricea dacă este necesar
• creează una nouă, mai mare
• rescrie valorile curente
• adaugă un articol nou
• void add(Integer value, int idx) - adaugă un element la poziția indicată; dacă
este necesar, acest lucru se face prin metoda de mai sus
• Integer get(int idx) - returnează elementul la poziția idx; dacă nu există,
returnează null
• void remove(int idx) - elimină elementul din poziția idx
• void swap(int from, int to) - schimbă articole în pozițiile de la și către; mărește
matricea dacă este necesar
• String toString() - afișează întregul tablou

Additional functionalities:

 have each method display additional messages, e.g..


 I return item 5 from position 78
 I replace item 23 from item 3 with item 55 from item 14
 I put element 98 at position 56 (I enlarge the array)

 have the toString () method display additional information about the number of
elements and the size of the array

Accountand AccountApplication classes are provided


public class Account {
private String name;
private int balance;
}
public class AccountApplication {
public static void main(String[] args) {
Account account = new Account();
account.setName("Premium Account");

154
System.out.println("Name: " + account.getName());
System.out.println("Account balance: " + account.getBalance());
}
}

a. Set a default value 0 for the balance field

b. Add (generate) getter and setter type methods for the name field

c. Add (generate) a getter type method for the balance field

Add a (private) debit field of the boolean type that determines whether the account balance is

Funcționalități suplimentare:
negative; set the default value to false

• cereți fiecărei metode să afișeze mesaje suplimentare, de ex.


• Retur articolul 5 din pozitia 78
• Înlocuiesc articolul 23 de la articolul 3 cu articolul 55 de la articolul 14
• Am pus elementul 98 la poziția 56 (măresc matricea)
• au ca metoda toString () să afișeze informații suplimentare despre numărul de
elemente și dimensiunea matricei
57. Sunt furnizate clasele Account și AccountApplication
58. public class Account {
59. nume String privat;
60. sold int privat;
61.}
62. Public class AccountApplication {
63. public static void main(String[] args) {
64. cont cont = cont nou();
65. account.setName(„Cont Premium”);
66. System.out.println("Nume: " + account.getName());
67. System.out.println("Soldul contului: " + account.getBalance());
68.}
69.}
. Setați o valoare implicită 0 pentru câmpul de sold
A. Adăugați (generați) metode de tip getter și setter pentru câmpul de nume
b. Adăugați (generați) o metodă de tip getter pentru câmpul de sold
c. Adăugați un câmp de debit (privat) de tip boolean care determină dacă soldul
contului este negativ; setați valoarea implicită la false

d. Add the possibility to deposit and withdraw money


e. public void deposit(int amount) {
f.

155
g. }
h.
i. public void withdraw(int amount) {
j.
k. }
i. Implement the above methods

ii. The withdraw method is to set the debit field to true when the account balance is
negative

iii. Check the operation of the method

l. Add validation of the amount parameter in the deposit and withdraw methods;

i. the methods are to perform the logics only when the amount value is positive

ii. otherwise they are to display the following message: "The deposit/withdrawal amount must be
positive!"

m. For the withdraw method, add the message display: "Negative account balance" if the debit field
value is true

n. For the deposit and withdraw methods, add a summary display like the one below (e.g.
for deposit and withdraw, respectively)
o. "Account balance: 300 | Deposit: 250 | After operation: 550"
p. "Account balance: 200 | Withdrawal: 500 | After operatio: -300"
q. Add a function to support the maximum debit, e.g. 1000. If the amount after the operation is
lower, do not execute withdrawal but display the message: "You cannot perform an operation
exceeding the debit"

r. Implement the transfer method for transfers from the current account to another one.
s. public void transfer(Account other, int amount) {
t.
u. }
i. The amount is to be withdrawn from the current account

ii. The amount should be paid to the other account

v. Add the toString method


w. public String toString() {
x. return " Account{name: " + name + ", balance: " + balance + "}";
y. }
and invoke it as below:
public class AccountApplication {
public static void main(String[] args) {
Account account = new Account();
account.setName("Premium Account");
System.out.println(account);
}

} c. Adăugați posibilitatea de a depune și retrage bani


d. depozit public nul (suma int) {
e.
f. }
g.
h. public void retrage (suma int) {

156
i.
j. }
. Implementați metodele de mai sus
i. Metoda de retragere este de a seta câmpul de debit la adevărat atunci când
soldul contului este negativ
ii. Verificați funcționarea metodei
k. Adăugați validarea parametrului sumei în metodele de depunere și retragere;
. metodele sunt de a efectua logica numai atunci când valoarea cantității este
pozitivă
i. în caz contrar, trebuie să afișeze următorul mesaj: „Suma de
depunere/retragere trebuie să fie pozitivă!”
l. Pentru metoda de retragere, adăugați afișarea mesajului: „Sold cont negativ”
dacă valoarea câmpului debit este adevărată
m. Pentru metodele de depunere și retragere, adăugați un afișaj rezumat ca cel
de mai jos (de exemplu, pentru depunere și, respectiv, retragere)
n. "Soldul contului: 300 | Depozit: 250 | După operare: 550"
o. "Soldul contului: 200 | Retragere: 500 | După operațiune: -300"
p. Adăugați o funcție care să accepte debitul maxim, de exemplu 1000. Dacă
suma după operațiune este mai mică, nu executați retragere ci afișați mesajul:
„Nu puteți efectua o operațiune care depășește debitul”
q. Implementați metoda de transfer pentru transferurile din contul curent în
altul.
r. transfer public void(Altul cont, suma int) {
s.
t. }
. Suma urmează să fie retrasă din contul curent
i. Suma trebuie plătită în celălalt cont
u. Adăugați metoda toString
v. public String toString() {
w. returnează " Cont{nume: " + nume + ", sold: " + sold + "}";
X. }
și invocă-l după cum urmează:
Clasa publica AccountApplication {
public static void main(String[] args) {

157
cont cont = cont nou();
account.setName(„Cont Premium”);
System.out.println(cont);
}
}

CONGRATULATIONS!

You have completed learning the basics of Java programming.

FELICITĂRI!
Ați terminat de învățat elementele de bază ale programării Java.

158

S-ar putea să vă placă și