You are on page 1of 18

PRIMITIVE

If you try and put a value larger than the maximum value in Java, or a value
smaller than the minimum value in Java, then you will get an Overflow in the case of
the maximum value or an Underflow in the case of the minimum.

A Byte occupies 8 bits.


A short can store a large range of numbers and occupies 16 bits.
An int occupies 32 bits.

A single float occupies 32 bits;


A double occupies 64 bits;

Operatorul ternar (elvis)

if in line
variabila = conditie ? prima varianta ? a doua varianta
JAVA OPERATOR PRECEDENCE TABLE

Precedence Operator Type Associativity


() Parentheses
Left to Right
15 [] Array subscript
· Member selection
++ Unary post-increment
14 Right to left
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
Logical AND
4 && Left to right

3 || Logical OR Left to right


2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Larger number means higher precedence.
Citirea de la tastura a unui vector

Copierea vectorilor

Copiere vector varianta I:


Copiere vector varianta II:

Reverse vector :
Sortarea vectorilor

sort - sorteaz ascendent un vector, folosind un algoritm de tip QuickSort


performant, de complexitate O(n log(n)).

java.util.Arrays.sort(c);

Exista trei tipuri de date din limbajul C care nu sunt suportate de limbajul Java.
Acestea sunt: pointer, struct ¸si union. Pointerii au fost eliminati din cauza ca erau o
sursa constanta de erori, locul lor fiind luat de tipul referinta, iar struct si union nu isi
mai au rostul atat timp cat tipurile compuse de date sunt formate in Java prin
intermediul claselor.

int x = 1;
System.out.println(++x);
// operatorul de incrementare prefixat 2

int y = 1;
System.out.println(y++);
// operatorul de incrementare postfixat 1

int a = 1;
System.out.println(--a);
// operatorul de incrementare prefixat 0

int b = 1;
System.out.println(b--);
// operatorul de decrementare postfixat 1
System.out.println(b);
MODIFICATORI DE ACCES

• public In orice alta clasa se pot crea instante ale clasei respective.

• protected Doar in subclase pot fi create obiecte de tipul clasei respective.

• private In nici o alta clasa nu se pot instantia obiecte ale acestei clase. O astfel
de clasa poate contine metode publice (numite ”factory methods”) care sa fie
responsabile cu crearea obiectelor, controland in felul acesta diverse aspecte legate de
instantierea clasei respective.

• implicit Doar in clasele din acelasi pachet se pot crea instante ale clasei
respective.
•transient Este folosit la serializarea obiectelor, pentru a specifica ce variabile
membre ale unui obiect nu participa la serializare. (vezi ”Serializarea obiectelor”)

•volatile Este folosit pentru a semnala compilatorului sa nu execute anumite


optimizari asupra membrilor unei clase. Este o facilitate avansata a limbajului Java.

OVERLOADING (SUPRAINCARCARE)

1) METODELE AU PARAMETRI DIFERITI


2) METODELE AU ACELASI NUME

public static int sum(int a, int b) {


return a + b;
}

public static int sum(int a, int b, int c) {


return a + b + c;
}

public static int sum(int a, int b, int c, int d) {


return a + b + c + d;
}
OVERRIDING (SUPRADEFINIREA)

1) METODELE AU ACEEASI PARAMETRI


2) METODELE AU ACELASI NUME
Method Override (Supradefinire) Method Overload (Supraincarcare)
Folosit pentru a suprascrie un Ofera functionalitate pentru a refolosi
comportament pe care clasa curenta metoda cu acelasi nume dar
l-a mostenit de la superclasa. parametri diferiti.
Intotdeauna apare in 2 clase care De obicei se afla intr-o singura clasa
contin o relatie copil-parinte sau dar poate fi folosita si in clasa copil.
IS-A/HAS-A
Obligatoriu are aceeasi parametri si Obligatoriu are parametri diferiti.
acelasi nume.
Obligatoriu intoarce acelasi tip sau o Poate avea tip returnat diferit.
covarianta (clasa copil).
NU poate avea un modificator de Poate avea modificatori de acces
acces mai mic dar poate avea un diferiti (private, protected, public).
modificator de acces mai mare.
Spectru mai ingust pentru exceptiile Poate arunca exceptii diferite.
aruncate.

Metodele STATICE (de clasa) se apeleaza cu NumeClasa.metoda();

java.lang cel mai important pachet din Java


DESIGN PATTERNS

Pattern-ul Singleton este utilizat pentru a restricționa numărul de instanțieri ale


unei clase la un singur obiect, deci reprezintă o metodă de a folosi o singură instanță a
unui obiect în aplicație.

public class Student {


private static Student SINGLETON = null;
private Student() {}
public Student getInstance() {
if (SINGLETON == null) {
SINGLETON = new Student();
}
return SINGLETON;
}
}

Factory - Clasa care folosește aceste subclase nu trebuie să “știe” tipul lor concret
ci doar pe al părintelui.

public class Garage {


public Car makeMeACar(String choice) {
if (choice.equals("Audi")) {
return new Audi();
}
if (choice.equals("Dacia")) {
return new Dacia();
}
return null;
}
}
SIRURI DE CARACTERE

Modifier and Type Method and Description

charAt(int index)
char
Returns the char value at the specified index.

codePointAt(int index)
int Returns the character (Unicode code point) at the specified
index.

codePointBefore(int index)
int Returns the character (Unicode code point) before the
specified index.

codePointCount(int beginIndex, int endIndex)


int Returns the number of Unicode code points in the specified
text range of this String.

compareTo(String anotherString)
int
Compares two strings lexicographically.

compareToIgnoreCase(String str)
int Compares two strings lexicographically, ignoring case
differences.

concat(String str)
String
Concatenates the specified string to the end of this string.

contains(CharSequence s)
boolean Returns true if and only if this string contains the specified
sequence of char values.

contentEquals(CharSequence cs)
boolean
Compares this string to the specified CharSequence.

contentEquals(StringBuffer sb)
boolean
Compares this string to the specified StringBuffer.

copyValueOf(char[] data)
static String
Equivalent to valueOf(char[]).

copyValueOf(char[] data, int offset, int count)


static String
Equivalent to valueOf(char[], int, int).

endsWith(String suffix)
boolean
Tests if this string ends with the specified suffix.

equals(Object anObject)
boolean
Compares this string to the specified object.
equalsIgnoreCase(String anotherString)
boolean Compares this String to another String, ignoring case
considerations.

format(Locale l, String format, Object... args)


static String Returns a formatted string using the specified locale, format
string, and arguments.

format(String format, Object... args)


static String Returns a formatted string using the specified format string
and arguments.

getBytes()

byte[] Encodes this String into a sequence of bytes using the


platform's default charset, storing the result into a new byte
array.

getBytes(Charset charset)
byte[] Encodes this String into a sequence of bytes using the
given charset, storing the result into a new byte array.

getBytes(int srcBegin, int srcEnd, byte[] dst,


int dstBegin)
Deprecated.
void This method does not properly convert characters into
bytes. As of JDK 1.1, the preferred way to do this is via
the getBytes() method, which uses the platform's default
charset.

getBytes(String charsetName)
byte[] Encodes this String into a sequence of bytes using the
named charset, storing the result into a new byte array.

getChars(int srcBegin, int srcEnd, char[] dst,


int dstBegin)
void
Copies characters from this string into the destination
character array.

hashCode()
int
Returns a hash code for this string.

indexOf(int ch)
int Returns the index within this string of the first occurrence
of the specified character.

indexOf(int ch, int fromIndex)


Returns the index within this string of the first occurrence
int
of the specified character, starting the search at the
specified index.

indexOf(String str)
int Returns the index within this string of the first occurrence
of the specified substring.
indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence
int of the specified substring, starting at the specified index.

intern()
String
Returns a canonical representation for the string object.

isEmpty()
boolean
Returns true if, and only if, length() is 0.

join(CharSequence delimiter, CharSequence... element


s)
static String Returns a new String composed of copies of
the CharSequence elements joined together with a copy of
the specified delimiter.

join(CharSequence delimiter, Iterable<?


extends CharSequence> elements)
static String Returns a new String composed of copies of
the CharSequence elements joined together with a copy of
the specified delimiter.

lastIndexOf(int ch)
int Returns the index within this string of the last occurrence of
the specified character.

lastIndexOf(int ch, int fromIndex)


Returns the index within this string of the last occurrence of
int
the specified character, searching backward starting at the
specified index.

lastIndexOf(String str)
int Returns the index within this string of the last occurrence of
the specified substring.

lastIndexOf(String str, int fromIndex)


Returns the index within this string of the last occurrence of
int
the specified substring, searching backward starting at the
specified index.

length()
int
Returns the length of this string.

matches(String regex)
boolean Tells whether or not this string matches the given regular
expression.

offsetByCodePoints(int index, int codePointOffset)


int Returns the index within this String that is offset from the
given index by codePointOffset code points.

regionMatches(boolean ignoreCase,
boolean int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
regionMatches(int toffset, String other,
boolean int ooffset, int len)
Tests if two string regions are equal.

replace(char oldChar, char newChar)


String Returns a string resulting from replacing all occurrences
of oldChar in this string with newChar.

replace(CharSequence target, CharSequence replacemen


t)
String Replaces each substring of this string that matches the
literal target sequence with the specified literal
replacement sequence.

replaceAll(String regex, String replacement)


String Replaces each substring of this string that matches the
given regular expression with the given replacement.

replaceFirst(String regex, String replacement)


String Replaces the first substring of this string that matches the
given regular expression with the given replacement.

split(String regex)
String[] Splits this string around matches of the given regular
expression.

split(String regex, int limit)


String[] Splits this string around matches of the given regular
expression.

startsWith(String prefix)
boolean
Tests if this string starts with the specified prefix.

startsWith(String prefix, int toffset)


boolean Tests if the substring of this string beginning at the
specified index starts with the specified prefix.

subSequence(int beginIndex, int endIndex)


CharSequence Returns a character sequence that is a subsequence of this
sequence.

substring(int beginIndex)
String
Returns a string that is a substring of this string.

substring(int beginIndex, int endIndex)


String
Returns a string that is a substring of this string.

toCharArray()
char[]
Converts this string to a new character array.

toLowerCase()
Converts all of the characters in this String to lower case
String
using the rules of the default locale.
toLowerCase(Locale locale)
Converts all of the characters in this String to lower case
String
using the rules of the given Locale.

toString()
String
This object (which is already a string!) is itself returned.

toUpperCase()
String Converts all of the characters in this String to upper case
using the rules of the default locale.

toUpperCase(Locale locale)
String Converts all of the characters in this String to upper case
using the rules of the given Locale.

trim()
String Returns a string whose value is this string, with any leading
and trailing whitespace removed.

valueOf(boolean b)
static String
Returns the string representation of the boolean argument.

valueOf(char c)
static String
Returns the string representation of the char argument.

valueOf(char[] data)
static String Returns the string representation of the char array
argument.

valueOf(char[] data, int offset, int count)


static String Returns the string representation of a specific subarray of
the char array argument.

valueOf(double d)
static String
Returns the string representation of the double argument.

valueOf(float f)
static String
Returns the string representation of the float argument.

valueOf(int i)
static String
Returns the string representation of the int argument.

valueOf(long l)
static String
Returns the string representation of the long argument.

valueOf(Object obj)
static String
Returns the string representation of the Object argument.
a) Uppercase doar prima litera dintr-un cuvant:

String originalString = "asd";


String modifiedString = originalString.substring(0, 1).toUpperCase();
modifiedString = modifiedString +
originalString.substring(1,originalString.length());

b) Transforma un int intr-un String:

int n = scanner.nextInt();
String s = Integer.toString(n);

java end-of-file
for (int i = 0; scanner.hasNext(); i++) {
System.out.println(i + " " + scanner.nextLine());
}

c) Transforma un String intr-un vector de cuvinte:

String str = "Ana are mere";


String[] arr = str.split(" ");
EXCEPTII

Exceptiile sunt de 2 feluri:


- Checked (Business) -> sunt tratate de catre programator
- Unchecked (Runtime)

NullPointerException accesarea membrilor unui obiect ce are valoarea null;


ClassCastException daca se incearca compararea unui obiect cu un obiect de
alt tip.
ArrayIndexOutOfBoundsException accesarea eronata a elementelor unui
vector.
NumberFormatException sirul primit ca parametru nu reprezinta un numar de
tipul respectiv.

private static int divide() {


int x, y;
try {
x = getInt();
y = getInt();
System.out.println("x is " + x + " ,y is " + y);
return x / y;
} catch (NoSuchElementException e) {
throw new ArithmeticException("no suitable input");
} catch (ArithmeticException e) {
throw new ArithmeticException("Attempt to divide by zero");
}
}

private static int getInt() {


Scanner s = new Scanner(System.in);
System.out.println("Please enter an integer ");
while (true) {
try {
return s.nextInt();
} catch (InputMismatchException e) {
// go round again. Read past the end of line in the input first
s.nextLine();
System.out.println("Please enter a number using only the digits 0 to
9");
}
}
}
COLECTII

ArrayList<String> list = new ArrayList<String>();


list.add("one");
list.add("two");
list.add("two");
list.add("three");
list.add("four");
list.add("five");
System.out.println(list);

output: [one, two, two, three, four, five]

LinkedList<String> list = new LinkedList<>();


list.add("one");
list.add("two");
list.add("two");
list.add("three");
list.add("four");
list.add("five");
System.out.println(list);

output: [one, two, two, three, four, five]

// neordonat nesortat
HashSet<String> list = new HashSet<>();
list.add("one");
list.add("five");
list.add("two");
list.add("four");
list.add("two");
list.add("three");
System.out.println(list);

output: [four, one, five, two, three]

// ordonat
LinkedHashSet<String> list = new LinkedHashSet<>();
list.add("one");
list.add("five");
list.add("two");
list.add("four");
list.add("two");
list.add("three");
System.out.println(list);

output: [one, five, two, four, three]


// sortat crescator
TreeSet<String> list = new TreeSet<>();
list.add("one");
list.add("five");
list.add("two");
list.add("four");
list.add("two");
list.add("three");
System.out.println(list);

output: [five, four, one, three, two]

// Neordonat Nesortat
HashMap<String, String> list = new HashMap<>();
list.put("key1", "one");
list.put("key3", "three");
list.put("key5", "five");
list.put("key2", "two");
list.put("key2", "two");
list.put("key4", "four");
System.out.println(list);

output: {key1=one, key2=two, key5=five, key3=three, key4=four}

// Ordonat
LinkedHashMap<String, String> list = new LinkedHashMap<>();
list.put("key1", "one");
list.put("key3", "three");
list.put("key5", "five");
list.put("key2", "two");
list.put("key2", "two");
list.put("key4", "four");
System.out.println(list);

output: {key1=one, key3=three, key5=five, key2=two, key4=four}

// sortat crescator

TreeMap<String, String> list = new TreeMap<>();


list.put("key1", "one");
list.put("key3", "three");
list.put("key5", "five");
list.put("key2", "two");
list.put("key2", "two");
list.put("key4", "four");
System.out.println(list);

output: {key1=one, key2=two, key3=three, key4=four, key5=five}

You might also like