Documente Academic
Documente Profesional
Documente Cultură
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.
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
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.
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.
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.
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.
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:
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
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.
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
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
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).
Î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
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).
To execute exercises and assignments, you will need the following: Pentru a executa exerciții
și sarcini, veți avea nevoie de următoarele:
IDE (Integrated Development Environment) - the environment in which writing a code in the
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
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.
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.
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!
Does it look complicated? Below we will discuss step by step what is happening in the individual
lines.
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
(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
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,
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ă.
created. Please notice the opening brace ({) that defines the beginning of the class
o Notice the opening brace at the end of the line—it defines the beginning of
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.
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
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.
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.
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.
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.
Accesați Declarație
Navigate to the initial declaration of the instantiated class, called method, or field.
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
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
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.
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.
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
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
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
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 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.
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 {
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
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
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
} 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
(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!
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.
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
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) .
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.
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.
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 #
# #
########################
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.
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.
Before a variable can be used, a value must be assigned to it. The code below will result in an error!
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.
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)
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
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.
Java features strict type control. Each variable must be of a specific type that has been once
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
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
`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
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.
- `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;
Î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
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
multiplying int type values, the range is exceeded and the result becomes incorrect (it is still
To avoid such a situation, it is enough to add letter L to one of the values, which will allow Java to
- `double`
37
a double precision format on 64 bits; **the default type for floating point values**; to increase
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
fraction 1/10, just like in the decimal system there is no exact representation of fraction 1/3.
Tip
Bacsis
For storing financial values, use the BigDecimal class.
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
\'
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");
Logical type
booleana logical type that can store one of two values: false or true. It is used to verify logic
conditions
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.
41
type siz description default
e value
Primitive types—summary
*
) boolean type stores 1 bit of information, but according to the documentation its size is not
precisely specified
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
Note
Instances of classes (objects) of object-oriented types are created using a key word: new.
Important
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.
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
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.
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
brackets we pass arguments to the method - in this case we invoked the argumentless (non-
parametric) method.
26
- 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)
If we try to invoke an operation, i.e., refer after the dot (.) on an uninitialized variable, a runtime
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
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();
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
(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.
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.
LocalDate
LocalTime
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:
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:
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
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.
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.
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
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);
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
conversion between primitive types and the corresponding object-oriented types (wrappers).
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.
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.
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)
•
variable value is null. If this is the case, an error will appear.
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
56
Java copes quite well with adjusting the types. Only in some cases we must use additional
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
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;
57
int d = 5;
byte e = (byte) d;
long f = (long) c;
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
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
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
a String type to a primitive type. These are methods in the parseXXX(String s) form.
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 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.
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.
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 #
# #
############################
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.
+ 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;
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
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
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.
Result:
true
false
true
true
true
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));
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.
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
Important
Important
Operator = means assignment Operator == means comparison
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
x y x \|\
|y
70
x ``!``x
tru fal
e se
fal tru
se e
Summary
What have you learned in this chapter?
arithmetic
comparisons
logical
— addition
— subtraction
— multiplication
/ — division
% — remainder (modulo)
++ — increase by 1
-- — decrease by 1
71
The modulo operator (%) returns the remainder of the division. For instance:
These are operators that enable performing an action and changing the value of the variable at the
same time.
72
= - subtraction with assignment
*= - multiplication with assignment
/= - division with assignment
%= - modulo with assignment
The operator of Strings concatenation (+) combines two texts together to form one new text.
== - equal to
!= - not equal to
< - less than
<= - less than or equal to
greater than
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:
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 }.
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
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
true
false
age + 1
price = 7.45
dayNr % 2
1
A logical condition can be complex and consist of several expressions, but the result must still be a
76
Example of a complex logic condition
if ((age > 18 && dayNr == 6) || amount > 1000) {
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”);
}
77
Structure of the if - else if - else statement
if (<logical-condition- 1>) {
// operations
} else if (<logical-condition- 2>) {
// operations
...
} else {
// operations
}
...
} altfel {
// operațiuni
}
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;
}
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.
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;
Declarația switch
Structure of the switch statement
switch (<variable>) {
case <value-1>:
// operations
break;
case <value-2>:
// operations
break;
...
default:
// operations
}
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
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!
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:
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
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!");
}
84
Summary
What have you learned in this chapter?
These are the if and switch statements. The if statement has a few
forms: if, if - else and if, else if - else.
What types can be used in the case value in the switch statement?
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 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);
current time
information about the time of day (setting arbitrarily): morning, noon, afternoon,
evening, night
information whether it is already after the payment (assuming that the payment
comes by the 10th of each month)
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.
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
}
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.
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.
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
Now, the word Java will be displayed infinitely on the screen. To end the operation of this program,
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.
89
for (int i=1; i<=10; i++) {
System.out.println(i);
}
These values can also be displayed from the end, that is, from 10 to 1.
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.
With the loop, you can easily sum all numbers from 1 to 10.
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.
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.
92
for (int i=1; i<=10; i++) {
if (i%2 == 0) {
sum += i;
}
}
System.out.println("Sum = " + sum);
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.
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.
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 + " ");
}
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
During each loop rotation, consecutive value from the collection or array is passed to
Î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
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
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);
96
Count: all=10, odd=5
instrucțiuni atâta timp cât condiția logică pentru buclă este îndeplinită (valoarea
acesteia este adevărată).
Structure of the while loop
} î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.
Unlike the while loop, the do while loop will always be executed at least once, even if the logical
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.
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
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.
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 :)
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
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.
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
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;
104
Tip
Sometimes you can encounter alternative declarations of array variables. Equivalent declarations of
array variables.
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
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.
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.
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
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
108
variable[index]
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.
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
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.
System.out.println();
Result:
Spring
Summer
Fall
Winter
55 2 63 14 89 23 34
Spring
Summer
Fall
Winter
Summary
What have you learned in this chapter?
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.
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.
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
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};
all numbers
first 6 numbers
last 6 numbers
and a code example that randomizes one of the indexes of this array:
int idx = (int) (Math.random() * money.length + 1);
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.
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]
type wrappers. Now we will learn how to create our own classes that will have fields and provide
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.
public Car() {
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
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.
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.
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().
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
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 {
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 {
Definirea constructorilor
we assign the value of the variable value to a class field namedvalue
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ă {
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.
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.
private int a;
122
private int b;
private int 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.
private int a;
private int b;
private int c;
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.
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.
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.
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.
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));
}
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));
}
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.
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;
}Notă
S-a presupus că pentru câmpurile booleene, în metodele getter, prefixul \ is \
este adăugat în loc de get.
boolean privat activ;
127
return c;
}
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.
}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
Notă
This provision is used to prevent name collisions.
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
129
public void setA(int a) {
aceasta.a = a;
}
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 {
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ă {
131
returnează „[” + valoare + „]”;
}
}
Crearea mai multor instanțe și apelarea toString()
clasă publică DiceApp {
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:
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: A feature of a given object describing the type of a given property of the object.
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.
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.
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();
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.
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.
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
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) {
}
}
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) {
•
•}
•}
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:
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.
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
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. # # # # # # #
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
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ă {
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.
146
where:
YY - year
MM - month
DD - day
C - control digit
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
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.}
ix. double average(int a, int b) - returns the average for the numbers
b. Based on the solution from point a, implement 3-argument versions of these methods (try
to use 2 - argument versions of these methods):
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.
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)
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() {
}
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
Integer get(int idx) - returns the item at position idx; if not there, it returns null
void swap(int from, int to) - swap items in the from andto positions; enlarges the array if
necessary
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 the toString () method display additional information about the number of
elements and the size of the array
154
System.out.println("Name: " + account.getName());
System.out.println("Account balance: " + account.getBalance());
}
}
b. Add (generate) getter and setter type methods for the name 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
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
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
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!
FELICITĂRI!
Ați terminat de învățat elementele de bază ale programării Java.
158