Documente Academic
Documente Profesional
Documente Cultură
● JVM - masina virtuala care executa codul Java. Ruleaza pe partea de sus a OS.
Transforma byte code in cod masina
● JDK - java developer kit, este necesar pentru dezvoltare deoarece contine JRE +
instrumentele de dezvoltare (compilatorul java - javac, este inclus numai in JDK)
● JRE - mediul de executie al codului Java. JVM este inclus in JRE. Nu contine
compiler, debugger etc.
Mostenire multipla
● Java nu suporta mostenirea multipla din cauza “problemei diamantului” care apare in
alte limbaje cum ar fi C++. B si C extinde A, D extinde B si C
● Totusi mostenirea multipla este posibila in Java prin Interfete.
Metoda main()
● Public static void main(String[] args)
● Este punctul de intrare al oricarei aplicatii Java.
● Public si static => pentru a fi accesata de Java fara initializare.
● String[] args => array de String prin care putem pasa argumente la runtime
Overloading vs overriding
● Overloading => metoda cu semnatura diferita ( argumente diferite )
● Overriding => metoda cu aceeasi semnatura, specifica mostenirii, clasa copil
suprascrie metoda din clasa parinte.
● Putem avea mai multe metode main dar una singura e main()
Pachete Java
● Modalitatea de organizare a claselor Java
● Pachetul java.lang e importat default.
Modificatori de acces
● O clasa Java poate avea doar public sau default
Final keyword
● La clase inseamna ca acea clasa nu poate fi mostenita - (clasa String e final).
● La metode inseamna k nu poate fi suprascrisa.
● La variabile inseamna k le pot fi atribuite valori o singura data => constante.
● Intefetele => static si final by default
Static keyword
● La nivel de clasa => o face globala => toate obiectele vor sharui aceeasi variabila
● La metode => o metoda statica poate accesa doar variabile statice ale clasei.
Finally si Finalize
● Blocul finally se foloseste intr`un bloc try,catch => se executa intotdeauna*
● finalize() => metoda ce poate fi suprascrisa pentru a notifica Garbage Collectorul
cand sa isi faca treaba
Try-with-resources
● Feature al Java 7 care face management auto al resurselor => inchide resursele
imediat dupa executarea blocului try, catch
Blocuri statice
● Sunt executate cand clasa este incarcata in memorie de Class Loader =>
initializeaza variabilele statice ale clasei.
Interfete
● Mod de abstractizare in java prin care se stabileste un contract
● Nu putem instantia o interfata => nu are constructori si nici metode implementate
● Orice atribut e public, final si static
● Metodele sunt publice si abstracte
● Nu poate extinde o clasa
● Interfetele nu pot implementa alte interfete dar le pot extinde.
● Din Java 8 interfetele pot avea implementari default ale metodelor.
● Interfetele marker => interfete fara metode sau body => Serializable si Cloneable
Clase abstracte
● O clasa care contine implementarea default a unor metode.
● Poate avea metode abstracte si concrete
● Nu poate fi instantiata
Clasele wrapper
● Reprezentarea in obiecte a primitivelor
● Sunt imutabile si finale
● Autoboxing => primitiva in obiect, int -> Integer;
- se face automat de Java atunci cand se paseaza ca parametru un primitiv si metoda
asteapta un obiect
- cand adaugi un primitiv intr-o lista de obiecte
● Unboxing => obiect in primitiv; la fel ca la autoboxing dar invers
● Primitivele nu pot fi null dar clasele wrapper pot fi
Enum
● Tip care contine ca fielduri constante
● Poate implementa interfete
● Constructorii sunt privati, nu pot fi instantiate cu new
Anotatii
● Metadata despre program; putem crea o anotare noua cu public @interface
AnotareNoua;
● Ex. @Override, @Deprecated => anunta compilerul ca metoda este deprecata
Composition
● Se refera la relatia has-a; Person has a Job attribute
● Se foloseste composition in favoarea mostenirii:
Comparable si Comparator
● Comparable - interfata pentru sortarea colectiilor; are compareTo(T obj), returneaza
int(negativ, 0, pozitiv); Nu putem testa decat dupa un singur parametru
● Comparator - interfata; are compare(Object o1, Object o2), returneaza int
Clase Inner
● Clasa non-statica in alta clasa
● Clasele inner pot accesa membrii si metodele clasei outer
● Clasa inner fara nume => anonima
Super keyword
● Poate fi folosit pentru accesarea metodei clasei parinte
● Pentru invocarea constructorului din clasa parinte
This keyword
● Se refera la obiectul curent, se foloseste pentru distinctia de variabilele locale care
au acelasi nume; pentru invocarea altui constructor dintr-un alt constructor.
Break, continue
● Break - termina executarea unei bucle while, for, do-while; poate fi folosit in switch
pentru a iesi din case;
● Continue - trece peste iteratia curenta dintr-un while, for si do-while.
Serializare
● Convertirea unui obiect Java in Stream pentru a fi trimis mai departe. Se face prin
implementarea interfetei Serializable.
Pass by value vs Pass by reference
● Java este pass by value
● When an object is passed by value, this means that a copy of the object is
passed. Thus, even if changes are made to that object, it doesn’t affect the
original value. When an object is passed by reference, this means that the actual
object is not passed, rather a reference of the object is passed. Thus, any
changes made by the external method, are also reflected in all places.
String
● == verifica si daca obiectele sunt egale; folosim equals();
● Este thread safe, imutabil si final
● Cand facem concat, substrig se creaza un nou String => pentru asta se folosese
clasele StringBuffer si StringBuilder.
● StringBuffer este sincronizat => threadSafe
Collections Framework
● Contine Collection, Set, List si Map
● Java Collection Framework este un set de clase si interfete care contine structuri de
date.
● Iterator => interfata pentru a itera prin colectii. Se foloseste atunci cand vrem sa
iteram si sa stergem ceva dintr-o colectie.
● termenul ordonat înseamnă că ordinea elementelor este stabilita în funcţie de index.
List vs Set
● List - poate contine duplicate, este ordonata;
● Set - nu poate contine duplicate, neordonata,;
Map vs Set
● Map - chei unice cu orice valori;
● Set - doar valori unice;
Array vs ArrayList
● Array - marime statica, poate contine primitive
● ArrayList - marime dinamica, NU poate contine primitive
LinkedList vs ArrayList
● LinkedList - nesincronizate, insert sau add mai rapid
● ArrayList - nesincronizate, get(index) mai rapid
HashSet vs TreeSet
● HashSet - NU pastreaza elementele in ordinea introdusa, poate contine obiecte
null
● TreeSet - pastreaza elementele in ordinea introdusa, NU poate contine obiecte
null
HashMap vs HashTable
● HashMap => foloseste hashCode si equals pentru a pune si recupera elemente;
implementeaza interfata Map;
○ Permite kei si valori null si nu permite duplicate
○ Nu este sincronizat
● Hashtable => implementeaza Map;
○ Nu permite kei sau valori null si nu permite duplicate
○ Este sincronizat
Arrays
- they are a single block of memory(this is why we need to specify the size at creating)
- every element occupies the same amount of space in memory
- if we know the index of an element the time to retrieve the element will be the same, no
matter where is it in the array
- memory efficient when we know the index
ArrayList
- is backed by an Array
- not synchronized
- great for iteration
- add is slow if the array is not large enough
- insert/remove not at the end is slow because...well...shifting
- shifting is made by copying the array in the bg
- default capacity is 10
Vectors
- ArrayList thread-safe(synchronized). It was added before ArrayList
LinkedList
- doubly-linked list implementation of List and Deque
- not synchronized
- operation at head/tail => fast
Map
- is using a hash function to hash the key to an int value. The value is stored at the
hashed key value -> this is the index into the array
- Bucket sort: the values in bucket X must be greater than the values in bucket X-1 and
less that ... X+1
- Hashmap can have null values and a null key, not synchronized.
- LinkedHashMap -> has an list implementation, retains the order of the insertion, not
synchronized.
- HashTable -> you can't have null key or values, synchronized.
- keySet -> all keys in a map are a set
- values() -> all values in a map are a collection
- HashMap uses hashing, TreeMap uses ordering
- Create, modify or delete of objects in map => map.compute(key, (behaviour) (key,
value) -> value.doSomething())
- Map doesn't implement the Iterable interface => we need to specify what we want: the
keys, the values or the key value pair {k,v}
-> the keys = Set without order
-> the values = collection without order
-> the pair = Set (EntrySet)
Generalization is made with interfaces and implementations.
@Override
public boolean equals(Object object) {
if (this == object) {
return true;
}
if (!(object instanceof Class)) {
return false;
}
Class class = (Class) object;
return class.value == object.value;
}
Set
- NO duplicates
- not ordered & no index
- TreeSet => ordered, does not call equals, it uses compare
ArrayList DA DA NU DA DA NU
Vector DA DA NU DA DA DA
HashMap NU DA DA NU DA NU
HashTable NU DA DA NU NU DA
TreeMap DA DA DA NU NU NU
LinkedList DA NU NU DA DA NU
HashSet NU NU NU NU DA NU
TreeSet DA NU NU NU NU NU
Exceptii
● Throw - arunca o exceptie la runtime, se foloseste in interiorul metodei, se separa
prin pipe “|”
● Throws - semnaleaza ca metoda poate genera exceptia, se foloseste in semnatura
metodei, se separa prin virgula;
Cheched vs Unchecked
● Checked = compilare → trebuie sa fie tratate fie cu try catch fie throws; nu sunt
cauzate de program
■ ClassNotFoundException
■ IOException, FileNotFoundException,EOFException
■ SQLException, ParseException
■ NoSuchField/NoSuchMethod Exception
Exceptii custom
● Prin extinderea clasei Exception
Spring
● framework care te ajuta cu infrastructura aplicatiei; se foloseste ioc/di(monitor
exemplu)
● Modulele: Spring core, mvc, aop (aspect oriented programming), security, testing,
web services
● Spring container - instantiere, distrugere, creare bean-uri - life cycle; se foloseste app
context
● Manage-uieste doar bean-urile, nu si alte obiecte.
● Schema Spring WS
○ Clientul trimite un req servlet dispatcher-ului. Acesta il intercepteaza si il trimite unui
handler si primeste o mapare (locatia controller-ului) de la handler. Mai departe se
duce la locatia controller-ului care i-a fost sugerata. Controller-ul trimite un req catre
bd si primeste datele de acolo. Trimite un model catre SD, iar acesta trimite Model
Object catre View Resolver si acesta trimite inapoi view-ul catre SD. Mai departe se
trimite inapoi la client view-ul.
Bean
● Obiectele create de Spring Container;
○ se pot crea fie prin xml
○ Java Based Configuration (@Bean + @Configuration)
○ Adnotari
● Scope-uri - singleton, prototype si pentru MVC - session, request, global-session
○ Singleton - o singura instanta per App Context (e default)
○ Prototype - oricate instante per AC
○ Session - o instanta per HTTP session
○ Request - o instanta per HTTP request
○ Global-session - o instanta pe global HTTP session
1. Why Spring?
● It`s lightweight because it uses POJO model and highly modular
● Spring POJO model makes testing easy
● Makes life easy by allowing devs to focus on business logic while it takes care of the
low level "plumbing"
2. Spring Modules:
● Core container: Beans, Core, Context, SpEL
● AOP, Aspects, Messaging
● Data Access/Integration: JDBC, ORM(Hibernate), JMS, Transactions
● Web: WebSocket, Servlet, Web
● Test
3. IOC Container
● Find Beans
● Wire dependencies
● Manage lifecycle of the Beans
4. Application Context
● Bean Factory++
○ Spring AOP features
○ Internationalization capabilities
○ WebApplicationContext for web apps etc
6. Lifecycle of beans:
● Instantiere
● Populare campuri
● Setarea numelui beanului
● Setarea bean Factory
● Pre-initializare si initializare
● Post-initializare
● Distrugere - destroy() method
MISC
● CRUD
○ POST - creeaza o resursa; nu este idempotenta;
○ GET - citeste resursele; nu modifica starea serverului; este idempotenta - mai multe
cereri vor crea acelasi raspuns
○ PUT - actualizeaza sau poate si creea; idempotenta;
○ DELETE - sterge; idempotenta;
● Un serviciu Web este o aplicatie Web de tip client-server, în care un server furnizor
de servicii (numit si "Service Endpoint") este accesibil unor aplicatii client (care nu
sunt de tip browser) pe baza adresei URL a serviciului. Serviciul Web si clientii sãi
pot rula pe platforme diferite si pot fi scrise în limbaje diferite, deoarece se comunicã
prin protocoale standard HTTP, XML, SOAP, JSON, s.a.
○ Servicii de tip REST ( RESTful Web Services), în care cererile de la client se exprimã
prin comenzi HTTP (GET, PUT, POST,DELETE), iar rãspunsurile sunt primite ca
documente XML sau JSON;
○ Servicii de tip SOAP (Simple Object Access Protocol), în care cererile si rãspunsurile
au forma unor mesaje SOAP (documente XML cu un anumit format) transmise tot
peste HTTP. In astfel de servicii furnizorul expune si o descriere a interfetei API sub
forma unui document WSDL (Web Service Description Language), care este tot XML
si poate fi prelucrat de client. Un client trebuie sã cunoascã metodele oferite de cãtre
“Service Endpoint”, pe care le poate afla din descrierea WSDL.
The key parts of the singleton pattern are
1. A private static variable to store the single instance called the singleton. This variable
is usually final to keep developers from accidentally changing it.
2. A public static method for callers to get a reference to the instance.
3. A private constructor so no callers can instantiate the object directly.
Consumer -> functional interface that takes one argument and returns nothing =>
consumes the argument
- ex: s -> System.out.println(s)
Predicate -> functional interface that that takes one argument and returns a boolean
- ex: s -> s.startWith("a")
UnaryOperator (subinterface of Function) -> functional interface that takes one argument
and returns an object of the same type
- ex: s -> s.toUpperCase("a")
1. Checked Exceptions should be handled in the code using try-catch block or else
method should use throws keyword to let the caller know about the checked
exceptions that might be thrown from the method. Unchecked Exceptions are not
required to be handled in the program or to mention them in throws clause of the
method.
2. Exception is the super class of all checked exceptions whereas RuntimeException is
the super class of all unchecked exceptions. Note that RuntimeException is the child
class of Exception.
3. Checked exceptions are error scenarios that requires to be handled in the code, or
else you will get compile time error. For example, if you use FileReader to read a file,
it throws FileNotFoundException and we must catch it in the try-catch block or throw
it again to the caller method. Unchecked exceptions are mostly caused by poor
programming, for example NullPointerException when invoking a method on an
object reference without making sure that it’s not null. For example, I can write a
method to remove all the vowels from the string. It’s the caller responsibility to make
sure not to pass null string. I might change the method to handle these scenarios but
ideally the caller should take care of this.
What is difference between throw and throws keyword in
Java?
● throws keyword is used with method signature to declare the exceptions that the
method might throw whereas throw keyword is used to disrupt the flow of program
and handing over the exception object to runtime to handle it.
There are several benefits of String because it’s immutable and final.
● Default Methods
● Static Methods
What is a Default Method? Why do we need Default methods
in Java 8 Interfaces?
A Static Method is an Utility method or Helper method, which is associated to a class (or
interface). It is not associated to any object.
● We can keep Helper or Utility methods specific to an interface in the same interface
rather than in a separate Utility class.
● We do not need separate Utility Classes like Collections, Arrays etc to keep Utility
methods.
● Clear separation of Responsibilities. That is we do not need one Utility class to keep
all Utility methods of Collection API like Collections etc.
● Easy to extend the API.
● Easy to Maintain the API.
What is Hibernate Framework?
Hibernate provides reference implementation of Java Persistence API, that makes it a great
choice as ORM tool with benefits of loose coupling. We can use Hibernate
persistence API for CRUD operations. Hibernate framework provide option to map
plain old java objects to traditional database tables with the use of JPA annotations
as well as XML based configuration.
1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes care
of managing resources, so we can focus on business logic.
2. Hibernate framework provides support for XML as well as JPA annotations, that
makes our code implementation independent.
3. Hibernate provides a powerful query language (HQL) that is similar to SQL. However,
HQL is fully object-oriented and understands concepts like inheritance, polymorphism
and association.
4. Hibernate is an open source project from Red Hat Community and used worldwide.
This makes it a better choice than others because learning curve is small and there
are tons of online documentations and help is easily available in forums.
5. Hibernate is easy to integrate with other Java EE frameworks, it’s so popular that
Spring Framework provides built-in support for integrating hibernate with Spring
applications.
6. Hibernate supports lazy initialization using proxy objects and perform actual
database queries only when it’s required.
7. Hibernate cache helps us in getting better performance.
8. For database vendor specific feature, hibernate is suitable because we can also
execute native sql queries.
What is Lambda Expression?
Lambda Expression is an anonymous function which accepts a set of input parameters and
returns results.
Lambda Expression is a block of code without any name, with or without parameters and
with or without results. This block of code is executed on demand.
If an API call is synchronous, it means that code execution will block (or wait) for the
API call to return before continuing. This means that until a response is returned by the API,
your application will not execute any further, which could be perceived by the user as latency
or performance lag in your app. Making an API call synchronously can be beneficial,
however, if there if code in your app that will only execute properly once the API response is
received.
Asynchronous:
Asynchronous calls do not block (or wait) for the API call to return from the server.
Execution continues on in your program, and when the call returns from the server, a
"callback" function is executed.