Sunteți pe pagina 1din 13

Un program este un set de instructiuni pe care un pc trebuie sa le urmeze.

Aceste instructiuni sunt


scrise intrun limbaj de programare care este foarte asemanator cu engleza.
Din punct de vedere tehnic pcrile pot executa numai doua tipuri de calcule - adunari si scaderi.
Creierul matematic al pc unitatea aritmetica si logica ALU poate efectua doua categorii de operatii
elementare. Prima categorie este formata de operatiile aritmetice respectiv adunarea, scaderea,
inmultirea cu 2, impartirea cu 2 si altele. A doua categorie de operatii elementare este formata din
comparatii - avand doua numere unitatea aritmetica si logica poate stabili daca acestea sunt egale si
daca nu care dintre ele este mai mare.
Sunteti gata pt primul test ? De unde stiti daca doua numere sunt egale ? Le scadeti.
Daca diferenta este zero numerele sunt egale. Daca diferenta este un numar pozitiv primul numar
este mai mare decat al doilea. Daca diferenta este un numar negativ primul numar este mai mic
decat al doilea. Aceasta este metoda prin care pc iau deciziile logice.
Un programator instruieste un pc sa efectueze calcule si sa ia decizii prin scrierea unui program pt
pc. Un program pt pc contine toate etapele care trebuie urmate intro anumita ordine pt efectuarea
unui calcul specific sau pt luarea unei decizii logice.

Date
Multe instructiuni cer unui pc sa manipuleze informatii furnizate de programator sau de un alt pc.
Aceste informatii sunt numite date.
Furnizati date unui program de fiecare data cand introduceti numele de identificare si parola in pc.
Programul primeste aceste informatii si le valideaza inainte de a va permite accesul la pc. Iata un alt
test: ce calcule sunt folosite pt validarea numelui de identificare si a parolei ? Scaderea ! Programul
scade numele de identificare si parola furnizate din cele valide. Daca diferenta este zero inseamna
ca acestea se potrivesc si accesul este permis.
Un programator poate introduce date direct intro instructiune daca trebuie sa furnizeze date.
De exemplu iata o instructiune care cere pc sa adune doua numere (numerele au fost plasate in
instructiune de programator): 10 + 15
De multe ori in momentul in care scrie programul programatorul nu are la dispozitie datele care vor
fi folosite in instructiuni - cum ar fi identificatorul si parola unui utilizator.
Persoana care foloseste programul trebuie sa introduca aceste date in timpul rularii programului.
Totusi instructiunile din program trebuie sa tina seama de aceste date asa ca programatorul
foloseste un inlocuitor pt acestea. Puteti sa va ganditi la acesti inlocuitori ca la un fel de etichete
temporare pt date. Programatorii numesc aceste etichete variabile despre care veti invata mai tarziu
in carte. Exemplul urmator ilustreaza aceeasi instructiune folosita pt adunarea a doua numere
exceptand faptul ca literele A si B sunt folosite ca inlocuitori pt numere: A + B
Pc inlocuieste aceste litere cu numere atunci cand persoana care foloseste programul introduce
numere in timpul rularii programului sau cand numerele sunt furnizate de un alt program.

Limbaje de programare
Un limbaj de programare precum Java permite programatorului sa scrie mai usor instructiunile pt pc
deoarece aceste instructiuni sunt scrise folosind cuvinte asemanatoare cu cele din limba engleza.
Totusi pc nu intelege cuvintele din limba engleza. Pc intelege numai instructiunile scrise in limbaj
masina.
Instructiunile in limbaj masina sunt formate din serii de zero si unu care sunt intelese de unitatea
centrala de prelucrare CPU componenta in care au loc toate procesele de prelucrare dintrun pc.
Desi programatorii au tendinta de a vorbi despre un singur limbaj de programare de fapt exista mai
multe variante ale limbajului masina. Ganditiva ca toate aceste variante sunt dialecte ale limbajului
masina. Fiecare unitate centrala de prelucrare intelege un singur limbaj masina. Aceasta inseamna
ca un program scris intrun dialect poate fi rulat numai pe pc echipate cu un CPU care intelege
dialectul respectiv. Din aceasta cauza programele sunt dependente de pc sau dependente de masina.
Ca urmare un program in limbaj masina scris pt un pc nu poate fi rulat pe un alt tip de pc. Nu este
nevoie sa fiti om de stiinta pt a vedea care sunt problemele scrierii unui program in limbaj masina.
In primul rand ce om sanatos ar vrea sa scrie un program folosind numai siruri de zero si unu ? Noi
gandim in cuvinte nu in numere. De asemenea cine ar vrea sa scrie un program care poate fi rulat pe
un singur tip de pc ?
Aparitia limbajului de asamblare a rezolvat cel putin una dintre aceste probleme.
Limbajul de asamblare este un alt limbaj de programare care foloseste abrevieri ale cuvintelor din
engleza numite instructiuni in limbaj de asamblare fiecare reprezentand o operatie elementara
executata de pc.
Programatorul trebuie mai intai sa decida ce operatie este necesara apoi sa foloseasca instructiunea
in limbaj de asamblare care cere pc sa execute operatia respectiva.
Totusi pc nu intelege decat siruri de zero si unu asa ca este folosit un program numit asamblor
(assembler) care transforma instructiunile din limbaj de asamblare in limbaj masina.
Iata un exemplu de program in limbaj de asamblare care cere pc sa efectueze o operatie de adunare.
Mai exact instructiunea de mai jos insumeaza numerele 10 si 15. ADD 10, 15
Trebuie sa recunoasteti ca limbajul de asamblare are un mare avantaj fata de limbajul masina
programatorul poate sa foloseasca cuvinte asemanatoare cu cele din engleza pt a scrie instructiuni.
Totusi exista si o serie de dezavantaje critice.
Programatorii sunt nevoiti sa invete din limbajul de asamblare o multime de abrevieri care nu sunt
foarte intuitive cum ar fi POP si PUSH. De asemenea sunt necesare multe instructiuni pt executarea
unor operatii fundamentale. Dar cea mai mare problema este portabilitatea. Fiecare tip de pc
intelege propriul dialect al limbajului de asamblare ceea ce face aproape imposibila scrierea unui
program in limbaj de asamblare care sa ruleze pe diferite tipuri de pc fara sa fie necesara rescrierea
programului sursa.
Limbajul de asamblare a evoluat in limbaje de nivel inalt care sunt intuitive deoarece folosesc
cuvinte asemanatoare cu cele din engleza instructiuni (propozitii) si semne de punctuatie care va
permit sa instruiti pc sa faca un anumit lucru. C++ si Java sunt limbaje de nivel inalt folosite pe
scara larga in prezent.
In plus puteti scrie instructiuni care executa un set de operatii inrudite. Nu mai este nevoie ca
programatorul sa scrie o instructiune pt fiecare operatie. De asemenea programele scrise in limbaje
de nivel inalt pot fi rulate pe diferite tipuri de pc fara sa fie necesara rescrierea programelor sursa.
Iata cum functioneaza un limbaj de nivel inalt: programatorul foloseste cuvinte cheie din limbajul
de programare pt a cere pc sa faca ceva. Cuvintele cheie sunt similare cu cuvintele din engleza cu
ajutorul carora puteti forma propozitii prin care cereti cuiva sa faca ceva.
Asa cum probabil ati ghicit deja pc nu intelege un program scris intrun limbaj de nivel inalt
deoarece pc inteleg numai limbajul masina.
Ca urmare programul scris intrun limbaj de nivel inalt trebuie sa fie transformat in limbaj masina.
Acest proces de translatie implica doua etape. Mai intai programul este translatat intro etapa
intermediara numita fisier obiect. Apoi fisierul obiect este transformat in limbaj masina care poate fi
rulat pe pc.
Translatarea unui program intrun fisier obiect este numita compilare si este facuta de un program de
translatie numit compilator. Procesul de transformare a unui fisier obiect in limbaj masina se
numeste editarea legaturilor (linking) si este executat de un program numit editor de legaturi
(linker).
Probabil va intrebati de ce programul nu este compilat direct in limbaj masina. Motivul este faptul
ca un program are de obicei doua sau mai multe fisiere obiect care trebuie sa fie legate laolalta pt a
forma programul in limbaj masina. Din acest motiv programatorii numesc procesul de combinare a
fisierelor editarea legaturilor.
Compilarea si editarea legaturilor sunt caracteristici importante ale unul limbaj de nivel inalt
deoarece aceste doua procese permit rularea unui program pe tipuri diferite de pc fara sa fie necesar
ca programatorul sa rescrie programul.
Acest lucru este posibil datorita faptului ca exista compilatoare si editoare de legaturi diferite pt
fiecare tip de pc capabile sa translateze un anumit limbaj de programare de nivel inalt in limbajul
masina al fiecarui tip de pc. De exemplu pt un program scris in C++ puteti face compilarea si
editarea legaturilor astfel incat programul sa ruleze pe diferite tipuri de pc fara a fi rescris.
Iata versiunea intrun limbaj de programare de nivel inalt a exemplului in limbaj de asamblare
prezentat mai devreme in aceasta sectiune: 10 + 15

Desi limbajul de programare C a rezolvat problemele din BCPL si B unii programatori au ramas cu
senzatia ca acesta nu are posibilitatea de a imita modul in care vedem lumea reala. Acesta este un
dezavantaj important deoarece programele sunt concepute sa simuleze lumea reala in interiorul pc.
Ca urmare limbajul de programare C nu putea simula lumea reala conform dorintelor
programatorilor.
Vedem lumea reala ca o multime de obiecte aceste obiecte au atribute (date) si comportamente.
Sa luam ca exemplu o fereastra. Dimensiunile ferestrei sunt atributele obiectului. Fereastra poate fi
inchisa sau deschisa iar acestea sunt functii asociate ferestrei.
Limbajul de programare C este un limbaj procedural care imita comportamentul din lumea reala in
interiorul pc. Din nefericire limbajul de programare C nu ofera o modalitate de a combina
comportamentul cu atributele.
Bjarne Stroustrup a dezvoltat un nou limbaj de programare numit C++. Cea mai importanta evolutie
din C++ a fost capacitatea de a combina atributele si functiile in obiecte. Odata cu aceasta
capacitate sau dezvoltat si modelul orientat spre obiecte si programarea orientata spre obiecte.

Toate limbajele de programare sunt formate din cuvinte cheie si functionalitati.


Un cuvant cheie seamana cu un cuvant din engleza. Prin functionalitate intelegem actiunea
executata de pc atunci cand un cuvant cheie este folosit intrun program. Ganditiva ca
functionalitatea este definitia cuvantului cheie.
Primul pas in dezvoltarea unui limbaj de programare consta in elaborarea unei liste de cuvinte cheie
impreuna cu actiunile asociate acestora. Ideal ar fi ca noul limbaj de programare sa asigure o
imbunatatire necesara fata de un limbaj de programare existent altfel nimeni nu va folosi noul
limbaj cu exceptia dv.
Pasul urmator este sa faceti publica aparitia noului limbaj in cadrul unei comunitati tehnice si sa
starniti interesul membrilor acestei comunitati. Dupa stabilirea standardelor producatorii de
instrumente software dezvolta compilatoare, editoare de legaturi si alte instrumente software care
recunosc programele scrise in noul limbaj de programare si translateaza aceste programe in limbaj
masina astfel incat sa poata fi rulate pe diferite tipuri de pc. De asemenea noul limbaj de programare
este predat in institutii de invatamant sunt publicate carti despre el iar programatorii il folosesc pt
scrierea programelor.

Apoi Java
C++ si alte limbaje de nivel inalt au un dezavantaj comun: programele scrise in aceste limbaje
trebuie sa fie recompilate pt a putea fi rulate pe diferite tipuri de pc. Organizatiile comerciale aveau
nevoie de un limbaj de programare care sa le permita dezvoltarea unui program care sa poata fi rulat
pe orice pc fara a fi necesara recompilarea programului.

Sa vedem cateva elemente de baza ale limbajului Java. Un program este o serie de instructiuni
scrise intrun limbaj de programare care cere unui pc sa execute anumite sarcini. Acestea sunt
asemanatoare cu indicatiile pe care le scrieti unui prieten ca sa-i explicati cum sa ajunga la dv acasa.
Fiecare instructiune trebuie sa fie exacta astfel incat pc sa inteleaga ce vreti sa faca.
Fara indoiala ati mai auzit termenul aplicatie pt pc. O aplicatie este de obicei un grup de programe
inrudite care colectiv arata pc cum sa emuleze lumea reala. De exemplu un supermagazin local are
o aplicatie de prelucrare a tranzactiilor folosita pt inregistrarea, prelucrarea si raportarea vanzarilor.
Cea mai vizibila parte a aplicatiei de prelucrare a tranzactiei este scanerul de la casa. Aplicatia este
insa compusa din multe programe.
Un program Java este format din una sau mai multe clase scrise in limbajul de programare Java.
O clasa seamana cu o forma de prajituri folosita pt a defini in interiorul pc un obiect din lumea
reala. La fel cum o forma de prajituri defineste aspectul unei prajituri o clasa defineste aspectul unui
obiect. La fel ca o forma de prajituri o clasa este folosita pt crearea obiectelor propriu-zise in
program. Aceste clase contin instructiuni care spun unui pc ce sa faca si in acelasi timp ii furnizeaza
datele de care are nevoie pt a-si indeplini sarcinile. Clasele sunt scrise intrun fisier de cod sursa Java
folosind un editor. Un fisierde cod sursa Java este asemanator cu un document dintrun procesor de
text dar in loc de text codul sursa contine instructiuni scrise in limbajul de programare Java. Un
editor este un procesor de text mai simplu care nu are toate functiile de formatare a textului pe care
le gasiti de obicei intrun procesor de text.
Dv scrieti codul sursa Java care devine un program Java. Codul sursa trebuie sa fie salvat pe disc
intrun fisier cu extensia • java.
Java functioneaza altfel decat C++ si alte limbaje de nivel inalt. Limbajele de nivel inalt trebuie sa
fie compilate in cod obiect care apoi este editat de un editor de legaturi (linker) pt a forma
programul in limbaj masina rulat pe pc.
Codul sursa Java nu este compilat in cod obiect ci in cod de octeti salvat intrsun fisier cu extensia
• class. Compilatorul Java este o componenta a pachetului Java Development Kit JDK.
Codul de octeti generat de compilatorul Java este interpretat de masina virtuala Java Virtual
Machine JVM care translateaza codul de octeti in limbajul masina rulat pe pc.
Masina virtuala Java este cheia succesului cunoscut de acest limbaj intrucat codul de octeti produs
de compilatorul Java poate fi citit de orice masina JVM indiferent de tipul pc pe care este rulata.
Vechiul obiectiv al programatorilor a fost in sfarsit atins un program poate fi compilat o singura data
si rulat practic pe orice pc fara a fi recompilat sau modificat.

Scrierea unui program Java pornind de la zero


Inainte de a intra in detaliile limbajului Java sa tragem aer in piept si sa scriem, sa compilam si sa
rulam traditrionalul program Hello World care este primul program scris de orice programator.
Acesta contine toate elementele de baza ale unui program Java si va va ajuta sa deveniti mai
increzator pe masura ce veti invata toate subtilitatile limbajului de-a lungul acestei carti.
Salvati fisierul cu numele Hello World.java. Asigurativa ca numele este scris exact ca aici. Altfel va
fi generata o eroare de compilare. Java face diferenta intre literele mari si cele mici in numele
fisierelor si ale c1aselor.
class HelloWorld {
public static void main ( String args[]
{
System.out.println("Hello world!");
Figura 1-1 Programul HelloWorld
Daca folositi programul Notepad selectati optiunea Save As. Observati ca numele prestabilit este *.
txt. Inlocuiti acest nume cu HelloWorld.java. Pt a deschide acest fisierin Notepad alegeti optiunea
All Files (*. *) in loc de Text Document (* .txt) din lista File Type astfel incat sa vedeti si fisierele
care nu au extensia * . txt.

Compilarea unui program Java


Vom discuta fiecare parte a programului HelloWorld. java in sectiunea urmatoare.
Acum vom compila si vom rula programul. Daca folositi un pc Windows deschideti o fereastra
Command Prompt. Daca folositi un pc Linux deschideti o fereastra de consola.
Scrieti urmatoarea comanda in linia de comanda apoi apasati tasta Enter:
javac HelloWorld.java
Daca programul este compilat cu succes pe ecran apare din nou promptul de comanda.
Daca afisati directorul de lucru veti vedea un nou fisier HelloWorld.class care contine codul de
octeti al programului. Pe un pc Windows afisati continutul directorului scriind comanda dir si
apasand tasta ENTER. Pe un pc Linux scrieti comanda ls si apasati tasta ENTER.
Daca programul nu a fost compilat cu succes pe ecran apar diferite mesaje de eroare.
Rularea unui program Java
Dupa ce ati reusit sa compilati programul Java este timpul sa-l rulati. Scrieti urmatoarea comanda si
apasati tasta ENTER: java HelloWorld
Ar trebui sa vedeti mesajul "Hello world!" afisat pe ecran in fereastra Command Prompt.

Analiza pe componente a unui program Java


Ati compilat si rulat primul dv program Java asa ca acum este timpul sa studiem cu mai mare
atentie modul de functionare a programului HelloWorld. Programul este format din trei parti:
Clasa, Metoda si instructiune.

Clasa
Definitia clasei din programul Hello World contine toate elementele necesare programului pt a afisa
pe ecran mesajul "Hello world !". Definitia clasei este compusa din urmatoarele elemente:
• Cuvantul cheie class
• Numele clasei
• Corpul clasei
Cuvantul cheie class informeaza compilatorul ca definiti o clasa. Cuvantul cheie class trebuie sa fie
urmat de numele clasei. In acest exemplu numele clasei este Hello World. Numele clasei din
programul Hello World trebuie sa fie exact acelasi cu numele de fisier al programului. Cele doua
nume trebuie sa fie identice altfel este generata o eroare atunci cand compilati programul.
Observati ca numele clasei este format din doua cuvinte: Hello si World. Java nu permite folosirea
spatiilor in numele claselor totusi este bine se scrieti cu majuscula initiala fiecare cuvant din numele
clasei. In acest fel numele sunt mai usor de citit atat pt dv cat si pt alti programatori.
Corpul clasei este locul in care sunt declarate atributele si sunt definite metodele.
Corpul clasei incepe cu o acolada deschisa { si se termina cu o acolada inchisa } .
Cuvantul cheie class
Numele clasei
Acolada deschisa
class HelloWorld {
Acolada illchisa
Definitia clasei trebuie sa contina aceste elemente.
} Corpul c1asei

Metoda
o clasa are doua componente, atributele si comportamentele care sunt numite metode. Un atribut
este un element de date asociat clasei in timp ce o metoda reprezinta functionalitatea clasei.
Atributele sunt o parte optionala a claselor dar orice aplicatie Java trebuie sa defineasca o metoda
main( ).
Metoda main( ) este locul din care incepe orice program Java.
Definitia unei metode include urmatoarele elemente:
• Numele metodei
• Argumentele metodei
• Corpul metodei
• Valoarea returnata de metoda
Numele metodei este folosit pt identificarea metodei si pt apelarea acesteia ori de cate ori programul
trebuie sa execute functionalitatea asigurata de metoda. retineti doar ca masina virtuala Java
apeleaza metoda main( ) atunci cand rulati un program.
Argumentele metodei sunt datele identificate intre parantezele din dreapta numelui metodei si
folosite de metoda pt a asigura functionalitatea necesara. Metoda main din programul HelloWorld
are un singur argument: String args[ ].
Corpul metodei este locul in care plasati instructiunile care cer calculatorului sa execute
functionalitatea specifica. Corpul metodei este delimitat de o pereche de acolade similare celor
folosite pt corpul clasei. Instructiunile continute in corpul metodei sunt executate secvential.
Programul se termina atunci cand este executata ultima instructiune din metoda main( ).
Numele metodei
Lista de argumente a metodei
class HelloWorld {
public static void main
String args[]
Corpul metodei { }
Metoda nu retumeaza nicio valoare
Toate aplicatiile Java au o metoda main( ) deoarece acesta este punctul de intrare al aplicatiei.
Valoarea returnata de metoda reprezinta informatiile returnate de metoda catre partea de program
care ia cerut sa execute ceva. Asa cum veti invata in capitolul 6 nu toate metodele returneaza valori.
In acest exemplu metoda main( ) nu returneaza nicio valoare.
Ca urmare trebuie sa precedati numele metodei cu cuvantul cheie void care indica faptul ca nu
exista o valoare returnata.
Veti observa alte doua cuvinte cheie folosite impreuna cu numele metodei main( ): public si static.
Cuvantul cheie public inseamna ca metoda poate fi apelata din afara definitiei clasei.
Metoda main( ) este publica deoarece este apelata de masina virtuala Java. Cuvantul cheie static
este un subiect avansat despre care vom discuta in capitolul 6. Pt moment este suficient sa retineti
ca acest cuvant cheie trebuie sa apara in definitia metodei main( ).

Instructiuni
o instructiune va permite sa cereti pc sa faca ceva. Exemplul nostru contine o singura instructiune
care cere pc sa afiseze pe ecran textul "Hello world!". Dupa cum se poate vedea aceasta instructiune
apeleaza una din metodele standard din Java: println( ).
este important sa intelegeti ca rolul metodei println( ) este de a afisa date pe ecran. Totusi trebuie sa-
i spuneti metodei println( ) ce date vreti sa afiseze.
Faceti acest lucru specificand datele respective intre paranteze atunci cand apelati metoda println( ).
In acest caz intre paranteze sunt plasate cuvintele "Hello world !" care sunt apoi afisate pe ecran.
In sfarsit toate instructiunile dintrun program Java trebuie sa se termine cu un caracter punct si
virgula ; Altfel compilatorul nu va recunoaste instructiunea si probabil va afisa un mesaj de eroare
atunci cand incercati sa compilati programul.
class HelloWorld {
public static void main ( String args[] ) {

Instructiune
System.out.println("Hello world!"); } }
Apelarea unei metode pt afisarea unui text
Caracter punct si virgula
Textul afisat pe ecran
Aceasta instructiune cere masinii Java sa afiseze pe ecran textul "Hello world!"

Java fara mistere intrebari recapitulative

1. Ce este un compilator ? Un compilator este un program care translateaza un program scris intrun
limbaj de programare de nivel inalt in cod de octeti sau cod obiect in functie de limbajul in care este
scris programul.
2. Ce este un limbaj de programare de nivel inalt ? Un limbaj de programare de nivel inalt contine
cuvinte asemanatoare cu cele din limba engleza folosite de programatori pt a instrui pc sa execute
functii specifice.
3. Ce este limbajul masina ? Limbajul masina este singurul limbaj inteles de un pc. Instructiunile
scrise in limbaj masina sunt formate din siruri de zero si unu.
4. Care este principala diferenta dintre C si Java ? Principala diferenta dintre C si Java este faptul ca
Java permite programatorilor sa defineasca clase. In C nu pot fi definite clase.
5. Care este principala diferenta dintre C++ si Java ? Principala diferenta dintre C++ si Java este
faptul ca un program Java poate fi rulat pe diferite tipuri de pc fara a fi recompilat. Un program C+
+ trebuie sa fie recompilat pt a fi rulat pe un alt tip de pc.
6. Ce este codul de octeti ? Codul de octeti este cod Java compilat care poate fi executat pe orice pc
pe care ruleaza o masina virtuala Java.
7. Ce este masina virtuala Java ? Masina virtuala Java este un program care interpreteaza codul de
octeti Java.
8. Care este scopul metodei main( ) dintro aplicatie Java ? Metoda main( ) dintro aplicatie Java este
punctul de intrare al aplicatiei.
9. Este obligatoriu ca orice clasa Java sa aibe declarat un atribut ? Nu. Puteti defini o clasa Java fara
sa declarati un atribut ca membru al clasei.
10. Ce se intampla dupa ce este executata ultima instructiune din metoda main( ) ? Dupa ce este
executata ultima instructiune din metoda main( ) aplicatia Java se termina.

INTRODUCTION
Inside Java
A pc program is a set of instructions for the computer to follow. Those instructions are written in a
programming language that is very similar to English.

Computer Programs
Technically computers perform only two kinds of computations — addition and subtraction.
Ready for your first quiz ? How would you know whether two numbers are the same number ?
Subtract them. If the difference is zero the numbers are the same. If the difference is a positive
number the first number is larger than the second number.
If the difference is a negative number the first number is smaller than the second number. This is the
way a computer makes a logical decision.
A computer programmer instructs a computer how to perform a computation and how to make a
logical decision by writing a computer program. A computer program contains all the steps that
must be followed in a specific order to perform a computation and to reach a logical decision.

Data
Many pc instructions require the pc to manipulate information that is provided by the programmer
by a person who uses the pc or by another pc. This information is called data. You provide a
program with data each time you enter your ID and password into your pc. The program receives
your ID and password and then validates them before giving you access to your pc. Here’s another
quiz. What computation is used to validate your ID and password ? Subtraction ! The program
subtracts the ID and password that you enter into your pc from the valid ID and password. If the
difference is zero they match and access is granted.
A programmer can enter data directly into an instruction if the programmer provides the data. For
example here is an instruction telling the computer to add two numbers (the programmer placed
these numbers into the instruction): 10 + 15
Surprised to see how simple a pc instruction can be ? If so you’re in for a treat because many of the
instructions you write using the Java programming language are simple to understand and simple to
write. Many times the programmer doesn’t have data for an instruction at the time when the
program is written such as a user’s ID and password. The person who uses the program must then
enter this data when the program runs. However the instruction still must be aware of the data when
the program is written so the programmer uses a placeholder for data in the instruction. You can
think of a placeholder as a temporary label for the data. Programmers call these labels variables
which you’ll learn more about later in this book. The following example is the same instruction
used to add two numbers except the letters A and B are placeholders for the numbers: A + B
The pc replaces these letters with numbers when the person who uses the program enters numbers
into the program or when the numbers are provided to the program by another computer program.

Programming Languages
A pc programming language such as Java makes it easy for a programmer to write instructions for a
computer because those instructions are written using English-like words. However a pc doesn’t
understand those English-like words. Instead a pc understands instructions written in machine
language. Machine language instructions consist of a series of zeros and ones that are understood by
the computer’s central processing unit CPU which is the part of the pc where all the processing
occurs.
Although programmers tend to refer to machine language as a single language there are actually
different versions of machine language. Think of these versions as dialects. A CPU understands
only one dialect of a machine language. This means that a program written in one dialect can be run
only on pc that have a CPU that understands that dialect. This makes the program pc dependent
sometimes referred to as machine dependent. That is a machine language program written for one
kind of pc cannot run on a different kind of pc.
You don’t need to be a rocket scientist to see problems writing programs using machine language.
First who in their right mind wants to write a program using only a series of zeros and ones ?
We think in words not numbers. Also who would want to spend all this time writing a program
when it can run on only one kind of pc ?
The introduction of assembly language addressed at least one of these problems. Assembly
language is another programming language that consists of English abbreviations called assembly
language instructions each of which represents an elementary operation of the pc.
A programmer first decided what operation needed to be performed and then used the assembly
language instruction to tell the pc to perform the operation. The pc still only understands zeros and
ones so a program called an assembler is used to translate assembly language instructions into
machine language.
Here is an example of an assembly language program. You can probably figure out what operation
the pc is being told to perform. The pc is being told to sum 10 and 15. ADD 10, 15
You must admit that assembly language had a big advantage over machine language the
programmer could use English-like words to write instructions for the pc. However there were
critical disadvantages too. The programmers had to learn many assembly language abbreviations
that weren’t intuitive such as POP and PUSH. Also many instructions were necessary to carry out
fundamental operations. And the biggest headache was portability. Each kind of pc understood its
own dialect of assembly language making it practically impossible to write an assembly language
program that could run on different kinds of pc without having to rewrite the program.
Assembly language evolved into high-level programming languages that are intuitive because they
use English-like words, statements (sentences) and punctuation to instruct the pc to do something.
C++ and Java are popular highlevel programming languages used today.
In addition a single instruction can be written to perform a related set of operations. No longer must
a programmer write one instruction for each operation. Also programs written in a high-level
programming language can be run on different pc without the programmers having to rewrite them.
Here’s how a high-level programming language works: A programmer uses keywords of a
programming language to form statements that tell a pc to do something. Keywords are similar to
English words that you use to form sentences to tell someone to do something.
You’ve probably surmised that the pc doesn’t understand a program written in a high-level pc
language because pc only understand machine language. Therefore the high-level pc language
program must be translated into machine language.
This translation process involves two steps. First the program is translated into an intermediate
stage called an object file. Second the object file is converted into the machine language program
that can be run on the pc.
Translating the program into an object file is called compiling and is performed by a translator
program called a compiler. The process of converting an object file into a machine language
program is called linking and is performed by a program called a linker.
You might be wondering why the program isn’t compiled directly to machine language.
The reason is because a typical program has two or more object files that must be joined together to
form the machine language program. Programmers call joining object files linking.
Compiling and linking are important features of a high-level programming language because these
two processes enable a program to run on different kinds of pc without the programmer having to
rewrite the program.
This is made possible because there is a different compiler and linker for each kind of pc that is
capable of translating a specific high-level programming language into machine language for a
specific kind of pc. For example a program written in C++ can be compiled and linked so that it
runs on different kinds of pc without having to be rewritten.
Here is the high-level programming language version of the assembly language example shown
previously in this section: 10 + 15

Although the C programming language addressed the drawbacks of BCPL and B some
programmers felt that it lacked the capability to mimic the way we look at the real world. This is an
important drawback because pc programs are designed to simulate the real word inside a pc.
Therefore the C programming language couldn’t simulate the real world to meet the desire of
programmers.
We look at the real world as objects. Those objects have attributes (data) and behaviors. Take a
window for example. The dimensions of the window are attributes Also the window can be opened
and closed which are functionalities associated with a window.
The C programming language is a procedural language that is focused on mimicking real-world
behavior inside a pc. Unfortunately the C programming language doesn’t provide a way to combine
behavior with attributes.
Bjarne Stroustrup developed a new programming language called C++. The most outstanding
advancement of C++ was the capability to combine attributes and functionality into objects.

How a pc Language Becomes a Standard


Did you ever wonder how a pc language is developed ? It takes a lot of perseverance and luck. Let’s
backtrack a bit and recall the components of a programming language. All programming languages
consist of keywords and functionality.
A keyword is an English-like word. Functionality is the action performed by the pc when the
keyword is used in a program. Think of functionality as the definition of the keyword.
The initial step in developing a programming language is to come up with a list of keywords and
functionality. Ideally the keywords and functionality of your programming language provide a
much-needed improvement over an existing programming language otherwise no one except you
will use your new language.
Next get the word out among the members of the technical community and stir up an interest in the
new programming language. If there is enough of a buzz and a real benefit leaders in technology
and industry will push to standardize the new programming language.
Once standards are established software tools manufacturers develop compilers linkers and other
software tools that recognize programs written in the new programming language and converts
those programs to machine language programs so they can run on different kinds of pc. The new
programming language is also taught in institutions written about in books and used by
programmers to write programs.
And Then Java
C++ and the other high-level programming languages all had one drawback: Programs written in
those languages had to be recompiled in order to run on different kinds of pc. Organizations wanted
a programming language that enables them to develop a program that can run on all pc without
having to recompile the program.
In a round about way Sun met this demand with the introduction of the Java.
Java ran on practically any kind of pc without having to be recompiled.

An Inside Look at Java


Let’s get down to some basics about Java. A program is a series of instructions written in a language
that tell a pc to perform specific tasks. This is like directions you write telling a friend how to drive
to your house. Each instruction must be precisely written so that the pc understands what you want
it to do. No doubt you’ve heard the term pc application. A pc application is typically a group of
related programs that collectively tell a pc how to mimic the real world. For example your local
supermarket has a transaction processing application that is used to record, process and report on
purchases. The most visible part of the transaction-processing application is the scanner at the
checkout counter.
The transaction-processing application used by your supermarket consists of many programs.
A Java program consists of one or more Java classes that are written using the Java programming
language. A class is like a cookie cutter that is used to define a real-world object inside your pc.
Much like a cookie cutter defines what a cookie looks like, a class defines what an object looks like.
And like a cookie cutter, a class is used to make a real object in your program.
These classes contain instructions that tell a pc what to do as well as the data necessary for the pc to
carry out the task. Classes are written into a Java source code file using an editor. A Java source
code file is similar to a word processing document. However instead of containing text the Java
source code file has instructions written in the Java. An editor is a barebones word processor that
doesn’t have all the fancy formatting capabilities you typically find in a word processor.
You write Java source code which becomes a Java program. The source code must be saved to a
disk in a file that has the file extension .java.
Java works differently than C++. High-level programming languages must be compiled into object
code that is linked by a linker to form the machine language program that runs on a computer.
Java source code is not compiled into object code. Instead Java source code is compiled into
bytecode and saved in a file that has the file extension .class.
The bytecode that is generated by the Java compiler is interpreted by the Java Virtual Machine JVM
which translated bytecode into machine language that runs on the pc.
The Java Virtual Machine is key to the success of Java because the bytecode produced by the Java
compiler is readable by every Java Virtual Machine regardless of the kind of pc that is running the
Java Virtual Machine. The goal of the industry has been finally achieved. A program can be
compiled once and run on practically any pc without having to be recompiled or modified in any
way.

Writing a Java Program from Scratch


Before getting into the details of Java let’s jump into the waters and write, compile and run the
traditional HelloWorld program which is the first program every programmer writes. It contains all
the basic elements of a Java program and will help to build your confidence as you learn all the ins
and outs of Java throughout this book.
Make sure that you add the /bin subdirectory to your path so you can compile your Java program in
any directory on your pc.
After the J2SDK is installed on your pc you are ready to write your first Java program. You’ll need
to write Java instructions into an editor. Most pc come with an editor. If you are using a Windows
pc open Notepad. If you are using a Linux-based pc open vi. Enter Figure 1-1 into your editor. This
is the HelloWorld Java program. Save the file as HelloWorld.java. Make sure that the filename is
spelled exactly the same way as shown here. Otherwise, you’ll receive a compiler error. The class
name and filename are case sensitive.
Figure 1-1 The HelloWorld program
If you are using Notepad select Save As. You’ll notice that the default file name is *.txt. Replace
this with HelloWorld.java. To open this file in Notepad you’ll need to change File Type from Text
Document (*.txt) to All Files (*.*) in order to see files that have extensions other than *.txt.

Compiling a Java Program


I’ll explain the parts of the HelloWorld.java program in the next section. For now let’s compile and
run the program. You run the compiler from the command line. If you are using a Windows pc open
a Command Prompt window. If you are using a Linux pc you’ll need to open a shell window. Type
following at the prompt and then press ENTER: javac HelloWorld.java
A new command prompt appears on the screen if the Java program successfully compiled. If you
display the directory you’ll see HelloWorld.class, which is the bytecode file of your program. On a
Windows pc you display the directory at the command prompt by typing dir then pressing ENTER.
On a Linux pc type ls and press ENTER.
If compiling was not successful you might see a variety of things on the screen.

Running a Java Program


Once you’ve successfully compiled your Java program it’s time to run it. Type the following line at
the command prompt and press ENTER: java HelloWorld
You should see “Hello world!” displayed on the screen in the Command Prompt window. If you
don’t see it one of two common problems has occurred.

Taking Apart a Java Program


Now that you’ve compiled and run your first Java program let’s take a closer look at it to see how
the HelloWorld program works. There are three parts to this program:
Class, Method and Statement.

Class - definition
The class definition in the HelloWorld program contains all the pieces of the program necessary to
display “Hello world!” on the screen. The class definition consists of the following:
• The class keyword
• The class name
• The class body
The keyword class informs the compiler that you are defining a class. The keyword class must be
followed by the name of the class. In this example HelloWorld is the class name. The class name in
the HelloWorld program must be the same as the program’s filename. Both names must match
exactly otherwise you’ll receive a compiler error when you compile the program.
Notice that the name of this class is made up of two words: Hello and World.
Java doesn’t permit you to use spaces in a class name however it is a good idea to capitalize the first
letter of each word used in the class name. This makes it easier for you and other programmers to
read.
The class body is where attributes are declared and methods defined.
The class body begins with a left brace { called an open brace and ends with a right brace } called a
close brace.
Class keyword
Class name
Open brace
Class body
Close brace
Figure 1-2 The class definition must have these components.
Method - definition
a class has two elements, attributes and behaviors which are called methods. An attribute is data that
is associated with the class and a method is a functionality of the class. An attribute isn’t a required
part of a class but every Java application must define one method the main( ) method. The main( )
method is where the Java program begins.
A method definition consists of the following items:
• Method name
• Method argument
• Method body
• Method return value
The method name is used to identify the method and to call the method whenever you need the
program to perform the functionality provided by the method.
For now, simply understand that the Java Virtual Machine calls the main( ) method when the
program runs.
The method argument is the data identified between the parentheses to the right of the method name
and is used by the method to provide the necessary functionality.
The main( ) method in the HelloWorld program has one method argument:
String args[]. For now we’ll hold off discussing it because the HelloWorld program doesn’t use it.
The method body is where you place statements that instruct the computer to perform specific
functionality. A pair of braces similar to the class body defines the method body. Statements
contained in a method body are executed sequentially. The program terminates when the last
statement in the main( ) method executes.
Method name
Method argument list
Method body
No method return value
All Java applications must have a main( ) method because the main( ) method is the entry point to
the application.
The method’s return value is the data returned to the part of the program that requested the method
to perform its functionality. Not all methods have a return value which you’ll learn about in Chapter
5. In this example the main( ) method doesn’t have a return value. Therefore we must precede the
name of the method with the keyword void which indicates there isn’t a return value.
You’ll notice that two other keywords are used alongside the name of the main( ) method. These are
public and static. The keyword public means that the method can be called from outside the class
definition. The main( ) method is also public because it is called by the Java Virtual Machine.
For now simply know that the static keyword must appear in the method definition.

Statement
As you learned earlier in this chapter a statement is an instruction to the computer to do something.
This example contains one statement that tells the computer to display the words “Hello world!”
on the screen.
As shown this statement calls one of Java’s standard methods: println( ).
For now it is important to understand that the functionality of the println( ) method is to display data
on the screen. However you must tell the println( ) method what data you want displayed. You do
this by placing the data between the parentheses when calling the println( ) method. In this case the
words “Hello world!” are placed between the parentheses and appear on the screen.
Finally every statement in a Java program must end in a semicolon ; otherwise the compiler won’t
recognize the statement and is likely to display an error message when you try to compile the
program.
Statement Semicolon Calling a method to display text on the screen
Text displayed on the screen
This statement tells Java to display “Hello world!” on the screen.
Quiz
1. What is a compiler ? A compiler is a program that translates a program written in a high-level
programming language into bytecode or object code depending on the language used to write the
program.
2. What is a high-level programming language ? A high-level programming language contains
English-like words used by programmers to instruct a pc to perform specific functionality.
3. What is machine language ? Machine language is the only language a pc understands.
Instructions written in machine language are written as a series of zeros and ones.
4. What is a key difference between C and Java ? The key difference between C and Java is that
Java enables a programmer to define classes. Classes cannot be defined in C.
5. What is a key difference between C++ and Java ? The key difference between C++ and Java is
that a Java program can run on different kinds of pc without having to be recompiled, a C++
program must be recompiled to run on different kinds of pc.
6. What is bytecode ? Bytecode is compiled Java code that can be executed on any pc that is
running the Java Virtual Machine.
7. What is the Java Virtual Machine ? The Java Virtual Machine is a program that interprets Java
bytecode.
8. What is the purpose of the main( ) method in a Java application ? The main( ) method in a Java
application is the entry point into the application.
9. Must all Java classes have at least one attribute declared ? No. You can define a Java class
without declaring an attribute as a member of the class.
10. What happens after the last statement in the main( ) method executes ? A Java application
terminates after the last statement in the main( ) method executes.

S-ar putea să vă placă și