Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Java design patterns:
- 3 druhy:
- Where Creational patterns mostly describe a moment of time (the instant of creation), and Structural patterns describe a more or less static structure, Behavioral patterns describe a process or a flow
- Creational - riešia problémy s vytváraním objektov v systéme a postup vyberu/vytvorenia triedn nového objektu a zabezpečujú ich správny počet. Dejú sa zväčša za behu programu.
- Abstract Factory - rozhranie pre vytváranie inštancie viacerých rodín objektov
- - podobné ako Factory ale všetko je encapsulated a všetko je abstraktne, iba konečný produkt/objekt vie o sebe
- - Client/Main, AbstractFactory (interface s createProductA/B metodami), ConcreteFactory1/2 implementuje AbstractFactory
- - AbstractProductA/B (interfaci s metódami pre produkty) a ProduktA1/2 & Produkt B1/2 implementujú AbstractProductA/B
- Builder - oddeluje tvorbu objektov aby sme proces tvorby bol použitelný aj inými inštanciami
- - ked chceme vybuildit object z viacerych inych objektov a schovat tvorba objektov z ktorych je vysledny objekt vystavany
- - Client/Main, Directory (construct(), metoda ktora dava product dokopy pomocou createProduct()), Builder (interface ktory má createProduct() na vystavania objektu)
- - ConcreteBuilder1/2/... (implementuje Builder, vytvara novy product v constructore - private Product product = new Product();, a vracia dany Product cez getter)
- - Product (classa ktora obsahuje gettery a settery pre nastavovanie parametrov daneho produktu)
- Factory Method - rozhranie pre vytváranie objektov a necháva potomkov rozhodnúť aký objekt bude vytvorený
- - keď potrebuje aby metóda vytvorila viacero class, ktoré majú rovnakú superclassu počas behu a nevieme koľko nám ich bude treba
- - dovoľuje vytvoriť objekty bez toho aby sme špecifikovali presný objekt (špecifikujeme iba Stringom napr.)
- - Creator (interface s metodov pre getProduct()), ConcreteCreator (implemetuje Creator interface a obsahuje getter pre getnutie produktu)
- - Product1/2/... (obsahuje metódy daného produktu) a ConcreteProduct1/2/... (ktory je dany produkt ktory sme chceli vytvorit)
- Prototype - nové objekty sú vytvárané kopírovaním/klonovaním prototypu (prvého objektu) ak ich potrebujeme počas runtime-u
- - Prototype (interface, ktory implementuje library Cloneable a dalsie metody ktore chceme)
- - ConcretePrototype1/2/... (implemetuje Prototype interface aj s clone metodov)
- @Override
- public PrototypeImp clone() throws CloneNotSupportedException{
- return (PrototypeImp) super.clone();
- }
- - Client/Main
- PrototypeImp prototype = new PrototypeImp(1000);
- ...
- PrototypeImp prototype1 = prototype.clone();
- Singleton - trieda v ktorej iba jedna inštancia objektu môže existovať (keď nechceme viac ako jednu inštanciu)
- public class Singleton{
- private static Singleton instance = null;
- private int data;
- private Singleton(){
- data = 0;
- }
- public static getInstance(){
- if(instance == null){
- instance = new Singleton();
- }
- return instance;
- }
- public int getData(){
- return data;
- }
- public void setData(int data){
- this.data = data;
- }
- }
- public class Main{
- public static void main(String[] args){
- Singleton singleton = Singleton.getInstance();
- System.out.println(singleton.getData);
- singleton.setData(10);
- System.out.println(singleton.getData);
- }
- }
- ////////////////////////////////////////////////////
- Structural - zameriavajú sa na usporiadavanie jednotlivých tried/komponentov v systéme, identifikujú vzťahi medzi entitami a definuje ich vzťahy. Sprehľadnujú systém a štruktualizujú kód.
- Adapter - zabezpečuje spoluprácu dvoch nekompatibelných rozhraní
- - Client/Main (vytvárame oba objekty a adapter a adapteru dame 2 nekompatibilný objekt)
- - Target (interface ktorý je implementovaný iným objektom/clasov)
- - Adapter (classa ktorá implementuje Target interface s jeho metódami a ukladáme doňho referenciu na Adaptee a v implementovaných metódach voláme jeho metódy)
- EnemyRobot theRobot;
- public EnemyRobotAdapter(EnemyRobot newRobot){
- theRobot = newRobot;
- }
- @Override
- public void fireWeapon() {
- theRobot.smashWithHands();
- }
- - Adaptee (classa objektu ktorý sme vytvorili aby používal rovnaké metódy aj keď vykonáva svoje vlastné veci)
- Composite - vytvára stromový systém objektov
- - Component (interface v ktorom sú operácie/metódy, ktorý je implementovaný Leafom aj Compositom)
- - Composite (obsahuje ArrayList do ktorého vkladáme jednotlivé Leafs)
- - Leaf (objekt ktorý má nejaké parametre/metódy a je vkladaný do Compositu)
- Decorator - dovoľuje modifikáciu objektov počas behu
- - flexibilnejší než dedičnosť, pretože umôžňuje funkcionality pre subclassy ako keby dedily ale počas behu
- - Component (interface ktorý obsahuje základné operácie/metódy - napr. getDescription)
- - ConcreteComponent (základná classa, ktorá implementuje Component a ktorá sa dekoruje)
- - Decorator (abstract class, ktorá implementuje Component a do ktorej posiela objekt ktorý chceme dekorovať)
- - ConcreteDecorator (classa v ktorom sa superuje objekt ktorý jej bol poslaný do Decorator kde je uložený do premennej
- a v ktorej je daný objekt dekorovaný - getDescription - return pizza.getDescription() + " <>")
- Facade - jednotné rozhranie, ktoré reprezentuje celý subsystém
- - Client/Main (vytvára Facade class a spustí metódu ktorá chceme a Facade metóda spraví všetky veci ktoré sú potrebné - Computer facade = new Computer(); -> facade.startComputer();)
- - Facade (obsahuje constructor v ktorom vytvárame ComplicatedClasses ktoré robia svoje vlastne operácie - Computer(){ cpu = new CPU(); hdd = ...} & startPC(){ cpu.run(); hdd.turn(); ...})
- - ComplicatedClasses1/2/... (classy ktoré vykonávajú svoje vlastné operácie aby sme vykonali čo chceme spraviť z Clienta/Mainu
- Proxy - vytvára objekt, ktorý je reprezentáciou iného objektu aby bolo možné kontrolovať alebo pristúpiť ku dátam iného objektu
- - limituje prístup inej classe
- - ATM (bankomat) je pekný príklad využitia Proxy - limitujeme prístup ku citlivým informáciam a metódam ako zmena množstva peňazí atď.)
- - Client/Main (vytvárame Subject objekty do ktorých vkladáme new SubjectProxy("<data>");)
- - Subject (interface v ktorom sú metódy ku ktorým chcem mať prístup, aby sme nemali prístup ku všetkým dátam ConcreteSubject-u)
- - SubjectProxy (implementuje Subject a má vytvorený Subject ConcreteSubject premennú)
- - ConcreteSubject (implementuje Subject a obsahuje všetky info, keďže ide o reálne zariadenie a nie o proxy)
- Bridge - oddeluje interface objektu od jeho implementácie
- Flyweight - používa sa keď máme príliš veľa malý objektov, ktoré sú si podobné
- ////////////////////////////////////////////////////
- Behavioral - riešia chovanie systému, akú objekti interaktujú. Sú založené na triedach alebo objektoch. U tried sa využíva dedičnosť a u objektov spolubráza medzi nimi a skupinami objektov.
- Chain of Responsibility - dovoľuje posúvanie requestov medzi objektami v reťazi/chain-e pokiaľ to daný objekt nedokáže vyriešiť
- - napr. keď si žiadame isté povolenie tak po chain-of-command budeme hľadať kto nám ho môže dať
- - Client/Main (vytvorí Handler handler = new ConcreteHandler1(); handler.handleRequest(<data>);)
- - Handler (interface ktorý obsahuje handleRequest(); metódu)
- - ConcreteHandler1/2/... (implementujú Handler interface a handleRequest() metódu v ktorej je IF,
- ak dokáže spracovať tak vykonajú operáciu ak nie tak vytvoria nový handler = newConcreteHandlerX() a dajú hadler.handleRequest(<data>))
- Observer - spôsob ako oznamujeme viacerým classám nejakú zmenu
- - observable/subject/object (uplementuje interface s add, remove a notif/update) si udržuje ArrayList s observermi, ktorým v prípade zmeny zavolá nejakú z ich metód (for-kuje (loop) a update() kazdy)
- State - mení chovanie objektu keď sa zmení jeho stav
- - Client/Main
- public class StatePatternDemo {
- public static void main(String[] args) {
- Context context = new Context();
- StartState startState = new StartState();
- startState.doAction(context);
- System.out.println(context.getState().toString());
- StopState stopState = new StopState();
- stopState.doAction(context);
- System.out.println(context.getState().toString());
- }
- }
- - State (interface)
- public interface State {
- public void doAction(Context context);
- }
- - Context
- public class Context {
- private State state;
- public Context(){
- state = null;
- }
- public void setState(State state){
- this.state = state;
- }
- public State getState(){
- return state;
- }
- }
- - ConcreteState1/2/...
- public class StartState implements State {
- public void doAction(Context context) {
- System.out.println("Player is in start state");
- context.setState(this);
- }
- public String toString(){
- return "Start State";
- }
- }
- Command - zapúdri request ako objekt (umožňuje parametrizovať daný objekt atď.) aby bol zavolaní neskôr
- - napr. vloženie orderov na kúpenie/predanie akcií/tovaru do listu a broker následne executne order a vykonajú sa
- - Client/Main (vytvára request/objekt (Stock s menom) - jablká, vytvára nové ConcreteOrders a vytvára Invoker-a, ktorému sa dané ConcreteOrders predané a on ich potom executne po jednom z listu a premaže list)
- - CommandBase (interface obsahujúci metódy ako execute)
- - ConcreteOrder1/2/... (implementuje CommandBase a ukladá si referenciu na daná objekt (Stock))
- - Invoker (si ukladá requesty ktoré su mu poslané do "private List<Order> list = new ArrayList<Order>();" a keď mu je povedané nech ich executne tak ich po jednom z listu vykoná a premaže)
- Iterator - dovoľuje pristupovať ku špecifickému elementu(om) v skupine elementov (objektom)
- - Array, ArrayList, Hashtable Objects...
- - Client/Main
- public static void main(String[] args) {
- ConcreteAggregate zoznam = new ConcreteAggregate();
- zoznam.pridajOsobu(new Osoba("Jozef"));
- zoznam.pridajOsobu(new Osoba("Peter"));
- zoznam.pridajOsobu(new Osoba("Stefan"));
- Iterator iterator=zoznam.createIterator();
- System.out.println(iterator.first().getMeno());
- System.out.println(iterator.next().getMeno());
- System.out.println(iterator.next().getMeno());
- }
- - Object/Person
- public class Osoba {
- private String name;
- public Osoba(String name,String priezvisko,int plat){
- this.name = name;
- }
- public String getMeno(){
- return this.name;
- }
- }
- - Container/Aggregate
- public interface Aggregate {
- public Iterator createIterator();
- }
- - ConcreteContainer/ConreteAggregate
- public class ConcreteAggregate implements Aggregate {
- private List<Osoba> zoznam = new ArrayList<>();
- public ConcreteAggregate(){
- }
- @Override
- public Iterator createIterator() {
- return new ConcreteIterator(this);
- }
- public List<Osoba> getZoznam(){
- return this.zoznam;
- }
- public void pridajOsobu(Osoba osoba){
- zoznam.add(osoba);
- }
- }
- - Iterator
- public interface Iterator {
- public Osoba first();
- public Osoba next();
- public Osoba currentItem();
- }
- - ConcreteIterator
- public class ConcreteIterator implements Iterator{
- private ConcreteAggregate aggregate;
- private int current = 0;
- public ConcreteIterator(ConcreteAggregate aggregate){
- this.aggregate = aggregate;
- }
- @Override
- public Osoba first() {
- //chyba osetrenie keby bol prazdny
- return aggregate.getZoznam().get(0);
- }
- @Override
- public Osoba next() {
- //chyba osetrenie keby bol prazdny a keby nemal dalsieho
- return aggregate.getZoznam().get(++current);
- }
- @Override
- public Osoba currentItem() {
- //chyba osetrenie keby bol prazdny
- return aggregate.getZoznam().get(current);
- }
- }
- Strategy - encapsuluje nejaký algoritmi vo vnútri classy aby sa dalo medzi nimi prepínať
- - Animal class má Dog a Bird classy, Animal bude implementovať Flys interface, kde budú metódy (stratégie/algos) ItFlys(), CantFly()
- - ked potrebuje dynamicky vyuzivat rozne chovania/behaviours pre objekty/kód
- - IStrategy (interface)
- public interface IStrategy {
- public int doOperation(int num1, int num2);
- }
- - Context
- public class Context {
- private Strategy strategy;
- public Context(Strategy strategy){
- this.strategy = strategy;
- }
- public int executeStrategy(int num1, int num2){
- return strategy.doOperation(num1, num2);
- }
- }
- - ConcreteStrategy1/2/... (OperatioAdd/Substract/Multiply) (implementuje Strategy)
- public class OperationAdd/Substract/Multiply implements Strategy{
- @Override
- public int doOperation(int num1, int num2) {
- return num1 +/-/* num2;
- }
- }
- - Client/Main
- public class StrategyPatternDemo {
- public static void main(String[] args) {
- Context context = new Context(new OperationAdd());
- System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
- context = new Context(new OperationSubstract());
- System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
- context = new Context(new OperationMultiply());
- System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
- }
- }
- Visitor - definuje operáciu, ktorá sa má vykonať nad objektami bez zmeny triedy
- - dovoľuje pridať metódy do class (aj rôznych typov) bez zmeny týchto class
- - Visitor (interface)
- interface Visitor {
- // Created to automatically use the right
- // code based on the Object sent
- // Method Overloading
- public double visit(Liquor liquorItem);
- public double visit(Tobacco tobaccoItem);
- public double visit(Necessity necessityItem);
- }
- - TaxVisitor (implementuje Visitor)
- class TaxVisitor implements Visitor {
- // This formats the item prices to 2 decimal places
- DecimalFormat df = new DecimalFormat("#.##");
- // This is created so that each item is sent to the
- // right version of visit() which is required by the
- // Visitor interface and defined below
- public TaxVisitor() {
- }
- // Calculates total price based on this being taxed
- // as a liquor item
- public double visit(Liquor liquorItem) {
- System.out.println("Liquor Item: Price with Tax");
- return Double.parseDouble(df.format((liquorItem.getPrice() * .18) + liquorItem.getPrice()));
- }
- // Calculates total price based on this being taxed
- // as a tobacco item
- public double visit(Tobacco tobaccoItem) {
- System.out.println("Tobacco Item: Price with Tax");
- return Double.parseDouble(df.format((tobaccoItem.getPrice() * .32) + tobaccoItem.getPrice()));
- }
- // Calculates total price based on this being taxed
- // as a necessity item
- public double visit(Necessity necessityItem) {
- System.out.println("Necessity Item: Price with Tax");
- return Double.parseDouble(df.format(necessityItem.getPrice()));
- }
- }
- - Visitable (interface)
- interface Visitable {
- // Allows the Visitor to pass the object so
- // the right operations occur on the right
- // type of object.
- // accept() is passed the same visitor object
- // but then the method visit() is called using
- // the visitor object. The right version of visit()
- // is called because of method overloading
- public double accept(Visitor visitor);
- }
- - Liquor/Necessity/Tobacco
- class Necessity implements Visitable {
- private double price;
- Necessity(double item) {
- price = item;
- }
- public double accept(Visitor visitor) {
- return visitor.visit(this);
- }
- public double getPrice() {
- return price;
- }
- }
- - TaxHolidayVisitor (ConcreteVisitor class)
- class TaxHolidayVisitor implements Visitor {
- // This formats the item prices to 2 decimal places
- DecimalFormat df = new DecimalFormat("#.##");
- // This is created so that each item is sent to the
- // right version of visit() which is required by the
- // Visitor interface and defined below
- public TaxHolidayVisitor() {
- }
- // Calculates total price based on this being taxed
- // as a liquor item
- public double visit(Liquor liquorItem) {
- System.out.println("Liquor Item: Price with Tax");
- return Double.parseDouble(df.format((liquorItem.getPrice() * .10) + liquorItem.getPrice()));
- }
- // Calculates total price based on this being taxed
- // as a tobacco item
- public double visit(Tobacco tobaccoItem) {
- System.out.println("Tobacco Item: Price with Tax");
- return Double.parseDouble(df.format((tobaccoItem.getPrice() * .30) + tobaccoItem.getPrice()));
- }
- // Calculates total price based on this being taxed
- // as a necessity item
- public double visit(Necessity necessityItem) {
- System.out.println("Necessity Item: Price with Tax");
- return Double.parseDouble(df.format(necessityItem.getPrice()));
- }
- }
- - Client/Main/VisitorTest
- public class VisitorTest {
- public static void main(String[] args) {
- TaxVisitor taxCalc = new TaxVisitor();
- TaxHolidayVisitor taxHolidayCalc = new TaxHolidayVisitor();
- Necessity milk = new Necessity(3.47);
- Liquor vodka = new Liquor(11.99);
- Tobacco cigars = new Tobacco(19.99);
- System.out.println(milk.accept(taxCalc) + "\n");
- System.out.println(vodka.accept(taxCalc) + "\n");
- System.out.println(cigars.accept(taxCalc) + "\n");
- System.out.println("TAX HOLIDAY PRICES\n");
- System.out.println(milk.accept(taxHolidayCalc) + "\n");
- System.out.println(vodka.accept(taxHolidayCalc) + "\n");
- System.out.println(cigars.accept(taxHolidayCalc) + "\n");
- }
- }
- Template Method - definuje kostru algoritmu tak aby potomkovia si kostru mohli upraviť a následne použiť vo forme v akej potrebujú
- Interpreter - includuje jazykové elementy do programu
- Mediator - zaisťuje komunikáciu medzi dvoma komponentami bez toho aby boli v priamej interakcií
- Memento - zachytí a dokáže obnoviť vnútorný stav objektu
- Java theory:
- Java balíky:
- Java ME (Micro Edition) – mobilné telefóny a malé zariadenia
- Java SE (Standard Edition) – typická inštalácia Javy pre domáce počítače
- Java EE (Enterprise Edition) – používaná v enterprise sektore
- Java Card – inteligentné čipové karty (ako napr. SIM karta do mobilného telefónu)
- Jacarta
- Java 10
- //zmena
- Overloading - two or more methods in the same class with the same name but different arguments
- void foo(int a)
- void foo(int a, float b)
- Overriding - two methods with the same arguments, but different implementations.
- One of them would exist in the parent class, while another will be in the derived, or child class.
- The @Override annotation, while not required, can be helpful to enforce proper overriding of a method at compile time.
- class Parent {
- void foo(double d) {
- // do something
- }
- }
- class Child extends Parent {
- @Override
- void foo(double d){
- // this method is overridden.
- }
- }
- Prístup ku objektom/elementom/metódam: private < package private (no modifier) < protect < public
- Modifier Class Package Subclass World
- public Y Y Y Y
- protected Y Y Y N
- package private Y Y N N
- private Y N N N
- /////////////////////////
- For for objects in Java:
- private List<Graphic> graphicList = new ArrayList<>();
- for(Graphic gr: graphicList) //foreach
- {
- gr.print();
- }
- /////////////////////////
- Encapsulation in Java is a mechanism of wrapping up the data and code together as a single unit.
- It also means to hide your data in order to make it safe from any modification.
- We can achieve encapsulation in Java by:
- Declaring the variables of a class as private.
- Providing public setter and getter methods to modify and view the variables values.
- //////////////////////////
- Polymorphism:
- Overloading (static) and overriding (dynamic polymorphism) are types of polymorphism where a method is acting differently based on the situation/data/object.
- //////////////////////////
- Constructor - can be invoked only one time per object creation by using the "new" keyword. You cannot invoke constructor multiple times, because constructor are not designed to do so.
- Method - can be invoked as many times as you want (Even never) and the compiler knows it.
- //////////////////////////
- KEYWORD extends is for extending a class. Preberáš všetky metódy z danej classy ale nemusíš ich použiť a môžeš ich prepísať.
- KEYWORD implements is for implementing an interface. Interface obsahuje iba názvy/volania/typy metód ktoré musia byť implementované do classy ktorá ich implementuje.
- A class can only extend ONE other class. A class can implement SEVERAL interfaces.
- Interface: Each mobile must provide Calling and SMS facility so we can create Interface that has methods Calling, SMS, etc...
- So if any class Implements MobileInterface then it has to write implementation part of all method writtenMobileInterface.
- In our example its Calling ans SMS. Check following source code for better understanding.
- IMPLEMENT
- public interface MobileInterface {
- /* Each mobile must have calling facility */
- public void call();
- /* Each mobile must have sms facility */
- public void sms();
- }
- Abstract Class: Now What other you can think of that mobile, it may have Mp3 Player, GPS, Camera, etc...
- but its not compulsory for mobile to have all this feature so we can create an Abstract class that has methods like Mp3Player, GPS, Camera, etc...
- Its not compulsory to implement all methods of SmartPhoneAbstractClass Abstract class.
- EXTEND
- public abstract class SmartPhoneAbstractClass {
- /* Its not compulsory to have MP3 Player in each mobile */
- public void mp3Player(){
- System.out.println("Can have implementation");
- }
- /* Its not compulsory to have GPS in each mobile */
- public void GPS(){
- System.out.println("Can have implementation");
- }
- }
- //////////////////////////
- Keyword STATIC:
- Static basically means that the values would be stored in the class memory.
- So if a class has a static variable, no matter how many instances of it you create, they all would have the same value for the variable.
- In other words, they all refer to the same copy. Static variables and methods can be accessed directly through the class.
- Though accessing them through instances wouldn't break compilation, your IDE will complain asking you to access them in a static way.
- Static methods can access only static variables in the class.
- “static” in Object Oriented languages means that the member is not tied to a particular instance.
- A static method cannot reference the “this” object, and cannot reference any other non-static members.
- A static field has only one value, which is shared across the entire application.
- Static classes are interesting. In Java, a nested class that is declared static is
- just an ordinary class that happens to be declared inside another class.
- If it’s public you can instantiate it and use it just like any other class.
- The interesting part is that a non-static nested class (sometimes called an “inner” class) is contained within
- an instance of the outer class, and can reference instance members of the containing object. Among other things, this means you
- cannot even create an instance of the inner class without qualifying it with an instance of the outer class.
- Keyword FINAL:
- Value of variables (ints, doubles etc.) cannot change.
- In very simple terms it means the values once assigned cannot be modified.
- In the case of final variables, they should either be assigned at declaration or in the constructor. In the case of final classes, it means that they cannot be subclassed.
- final int x = 5;
- Reference types: For references to objects, final ensures that the reference will never change, meaning that it will always refer to the same object.
- It makes no guarantees whatsoever about the values inside the object being referred to staying the same.
- final List<Whatever> foo;
- As such, final List<Whatever> foo; ensures that foo always refers to the same list, but the contents of said list may change over time.
- ////////////////////////////////////////////////////
- import java.util.ArrayList;
- import java.util.List;
- class Test {
- private final List foo;
- public Test() {
- foo = new ArrayList();
- foo.add("foo"); // Modification-1
- }
- public void setFoo(List foo) {
- //this.foo = foo; Results in compile time error.
- }
- }
- //////////////////////////
- private final List foo;
- "foo" is an instance variable. When we create Test class object then the instance variable foo, will be copied inside the object of Test class.
- If we assign foo inside a method, the compiler knows that a method can be called multiple times, which means the value will have to be changed multiple times,
- which is not allowed for a final variable.
- So the compiler decides constructor is good choice!
- You can assign a value to a final variable only one time.
- //////////////////////////
- private static final List foo = new ArrayList(); //must be static
- foo is now a static variable. When we create an instance of Test class, foo will not be copied to the object because foo is static.
- Now foo is not an independent property of each object. This is a property of Test class.
- But foo can be seen by multiple objects and if every object which is created by using the new keyword which will ultimately invoke the Test constructor
- which changes the value at the time of multiple object creation (Remember static foo is not copied in every object, but is shared between multiple objects.)
- //////////////////////////
- Try, Catch, Throw, Finally:
- Try: Java try block is used to enclose the code that might throw an exception. It must be used within the method. Java try block must be followed by either catch or finally block.
- Catch: Java catch block is used to handle the Exception. It must be used after the try block only. You can use multiple catch block with a single try.
- Finally: The finally block is executed after execution exits the try block and any associated catch clauses regardless of whether an exception was thrown or caught.
- Exception: Chybová správa/classa ktorá obsahuje dané chyby a vyhodí chybu ak nastane počas behu kódu.
- public static String test(){
- try {
- System.out.println("try");
- throw new Exception();
- } catch(Exception e) {
- System.out.println("catch");
- return "return";
- } finally {
- System.out.println("finally");
- return "return in finally";
- }
- }
- //////////////////////////
- Literals:
- Literals in Java are a sequence of characters (digits, letters, and other characters) that represent constant values to be stored in variables.
- Integer literals: 100 (base 10), 0144 (octal), 0x64 (hexa)
- Floating-point literals: 4.23, -0.00001
- Character literals: 'u0041' (capital A), \n (new line)
- String literals: "hello world"
- Boolean literals: true, false
- Null literal: null
- //////////////////////////
- JRE:
- JRE is an implementation of the JVM which actually executes Java programs.
- It includes the JVM, core libraries and other additional components to run applications and applets written in Java.
- Java Runtime Environment is a must install on machine in order to execute pre compiled Java Programs.
- JRE is smaller than the JDK so it needs less disk space and it is so because JRE does not contain Java compiler and other software tools needed to develop Java programs.
- JDK:
- The Java Development Kit (JDK) is a software development environment used for developing Java applications and applets.
- It includes the Java Runtime Environment (JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator (javadoc) and other tools needed in Java development.
- JVM (Java Virtual Machine):
- JVM is an abstract machine. A java program execution uses a combination of compilation and interpretation.
- Programs written in Java are compiled into machine language, but it is a machine language for a computer that is, virtual and doesn't really exist.
- This so-called "virtual" computer is known as the Java virtual machine (JVM). The machine language for the Java virtual machine is called Java bytecode.
- Java Virtual Machine is a program that runs pre compiled Java programs, which mean JVM executes .class files (byte-code) and produces output.
- The JVM is written for each platform supported by Java included in the Java Runtime Environment (JRE). The Oracle JVM is written in the C programming language.
- //////////////////////////
- Data types:
- Primitive:
- boolean - true/false
- char - single 16-bit Unicode character ('\u0000' or 0 - '\uffff' 65,535)
- byte - 8-bit signed integer (-128 - 127)
- short - 16-bit signed integer (-32768 - 32767)
- int - 32-bit signed integer (-2,147,483,648 - 2,147,483,647)
- long - 64-bit signed integer (-9,223,372,036,854,775,808 - 9,223,372,036,854,775,807)
- float - single-precision 32-bit IEEE 754 floating point (used to save memory)
- double - double-precision 64-bit IEEE 754 floating point (generally used for decimal values)
- Non-Primitive:
- String:
- By string literal : Java String literal is created by using double quotes.
- For Example: String s = “Welcome”;
- By new keyword : Java String is created by using a keyword “new”.
- For example: String s = new String(“Welcome”);
- It creates two objects (in String pool and in heap) and one reference variable where the variable ‘s’ will refer to the object in the heap.
- Array - Java Array is an object that holds a fixed number of values of a single data type.
- - can hold primitive, non-primitive or references
- - can be 2D or 3D
- Reference:
- A reference variable can be used to refer any object of the declared type or any compatible type.
- Animal animal = new Animal("giraffe");
- //////////////////////////
- Enum:
- An enum is a group of named constants. It can be used for defining user defined data types.
- package com.ashok.enums;
- enum Month {
- JANUARY, FEBRUARY, MARCH, APRIL, MAY, JUNE,
- JULY, AUGUST, SEPTEMBER, OCTOBER, NOVEMBER, DECEMBER;
- }
- public class MyEnum {
- public static void main(String[] args) {
- Month mon = Month.JANUARY;
- System.out.println(mon);
- }
- }
- //////////////////////////
- Hashtable:
- Hashtable<String, Integer> numbers = new Hashtable<String, Integer>();
- numbers.put("one", 1);
- numbers.put("two", 2);
- numbers.put("three", 3);
- Ku danej hodnote v Hastable sa pristupuje pomocou "key", čo je prvý dátovy typ (String).
- //////////////////////////
- Garbage Collector:
- The process by which Java programs perform automatic memory management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM for short.
- When Java programs run on the JVM, objects are created on the heap, which is a portion of memory dedicated to the program.
- Eventually, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.
- //////////////////////////
- Java Collections:
- The Java collections framework (JCF) is a set of classes and interfaces that implement commonly reusable collection data structures.
- At times you might be required to search, sort, insert, manipulate or delete big chunks of data. You can do all that with the help of Java Collections Framework.
- Collections in java is a framework that provides an architecture to store and manipulate the group of objects.
- All the operations that you perform on a data such as searching, sorting, insertion, manipulation, deletion etc. can be performed by Java Collections.
- Java Collection simply means a single unit of objects.
- Java Collection framework provides many interfaces (Set, List, Queue, Deque etc.) and classes (ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet etc).
- ArrayList - has dynamic length (with each added object, the lenght increases)
- - can't story primitive values (only objects)
- - can only be 1D
- LinkedList - Linked List is a sequence of links which contains items. Each link contains a connection to another link. (Linkedlist object = new Linkedlist();)
- - Singly Linked List (reference to the next link) and Doubly Linked List (reference to the next and to the previous link)
- //////////////////////////
- Package:
- Package is an encapsulation mechanism to group related classes and interfaces into a single module. The main purpose of packages are:
- To resolve naming conflicts
- To provide security to the classes and interfaces. So that outside person can't access directly.
- It improves modularity of the application.
- Class:
- A template/blueprint that describes the behavior/state that the object. Class is a logical entity. Class doesn't allocated memory when it is created.
- Object:
- Object is an instance of a class, a physical entity. It can be created many times as required.
- Object allocates memory when it is created.
- Nested classes:
- Nested classes are divided into two categories: static and non-static.
- Nested classes that are declared static are simply called static nested classes.
- Non-static nested classes are called inner classes. (has access to outer class members/variables)
- There are three reasons you might create a nested class:
- organization: sometimes it seems most sensible to sort a class into the namespace of another class, especially when it won't be used in any other context
- access: nested classes have special access to the variables/fields of their containing classes (precisely which variables/fields depends on the kind of nested class, whether inner or static).
- convenience: having to create a new file for every new type is bothersome, again, especially when the type will only be used in one context
- //////////////////////////
- Autoboxing:
- Auto Boxing is used to convert primitive data types to their wrapper class objects. Wrapper class provide a wide range of function to be performed on the primitive types.
- int a = 56;
- Integer i = a; // Auto Boxing
- Wrapper class:
- Each of Java's 8 primitive type (byte,short,int,float,char,double,boolean,long) hava a seperate Wrapper class Associated with them.
- These Wrapper class have predefined methods for preforming useful operations on primitive data types.
- String s = "45";
- int a = Integer.parseInt(s); // sets the value of a to 45.
- Unboxing:
- Unboxing is opposite of Auto Boxing where we convert the wrapper class object back to its primitive type.
- This is done automatically by JVM so that we can use a the wrapper classes for certain operation and then convert them back to primitive types as primitives result int faster processing.
- Integer s = 45;
- int a = s; auto UnBoxing;
- In case of Collections which work with objects only auto unboxing is used.
- ArrayList<Integer> al = new ArrayList<Integer>();
- al.add(45);
- int a = al.get(0); // returns the object of Integer. Automatically Unboxed.
- //////////////////////////
- Java Spring:
- In short, Spring framework helps you build web applications.
- It takes care of dependency injection, handles transactions, implements an MVC framework and provides foundation for the other Spring frameworks (including Spring Boot)
- MVC stands for Model View Controller.
- Developers use an MVC architecture for the same reason web designers use HTML (the model) and CSS (the view) instead of mixing structure, data,
- and layout together — the separation of presentation and data reduces complexity and allows developers to — for instance — build new front-end interfaces without having to change the core logic.
- //////////////////////////
- *method* *parameter*
- public setWeight(int newWeight){
- }
- *argument*
- x.setWeight(80);
- //////////////////////////
- public static void main(String args[])
- public - It means that you can call this method from outside of the class you are currently in.
- This is necessary because this method is being called by the Java runtime system which is not located in your current class.
- static - When the JVM makes call to the main method there is no object existing for the class being called therefore it has to have static method to allow invocation from class.
- void - Java is platform independent language and if it will return some value then the value may mean different things to different platforms.
- Also there are other ways to exit the program on a multithreaded system. Detailed explaination.
- main - It's just the name of method. This name is fixed and as it's called by the JVM as entry point for an application.
- String[] args - These are the arguments of type String that your Java application accepts when you run it.
- //////////////////////////
- File streams:
- I/O Streams: These are sequences of bytes that you can read from (InputStream and its subclasses) or write to (OutputStream and its subclasses).
- Java 8 streams: Basically a generalization of lists: they are sequences of objects; the difference is in how you use them.
- //////////////////////////
- Java JDBC:
- Java JDBC je Java API (Application Programming Interface) ktoré slúži na pripojenie a interakciu Java kódov s relačnými databázami (SQL, MySQL, PostgreSQL...). JABC používa JDBC motorist na rozhovor s databázami.
- JDBC (Java Database Connectivity)-to-ODBC (Open Database Connectivity) dovoľuje premostiť komunikáciu do akéhokoľvek ODBC zdroju dát vo Java Virtual Machin (JVM).
- Java JPA/Hibernate & ORM:
- ORM - Object-Relational Mapping
- JPA - Java Persistence Api
- Hibernate - ORM Framework that uses JPA
- JPA vyuziva ORM, ze si pouzijes presne Hibernate alebo eclipselink alebo openJPA a ti namapuje sql objekty na java objekty
- ale je zalozene na JDBC
- Java FX/JFX:
- A GUI toolkit for Java/Java Framework, bundled as part of the regular JVM and JDK. It replaces Swing (predchodca).
- It utilizes a XML architecture to map UI elements to the code.
- Databases:
- SQL - Structured Query Language
- DBMS - Database management system (data are stored as files)
- RDBMS - Relational database management system (data are stored as tables)
- PL/SQL - procedurálne rozšírenie Oracle SQL databázového systému. Umožňuje písať imperatívny kód, ktorý je vykonávaný systémom riadenia bázy dát (SRDB).
- Oracle SQL, MySQL, PostgreSQL - najznámenšie databázové systémy líšiace sa syntaxov, featurami atď. (Oracle SQL je platené)
- Primary key - v jednej tabuľke, slúži na indexovanie dát v tabuľke (môže byť iba jeden, nemôže byť NULL)
- Foreiging key - hodnota v tabuľke ktorá je primárnym kľúčom v inej tabuľke (môže ich byť viacero v tabuľke, môže byť NULL)
- Relationships:
- One-to-One (1:1) - každý riadok v jednej tabulke je linknutý ku presne jednúmu riadku v druhej tabuľke
- One-to-Many (1:m) - jedna tabulka s primarnym klucom a v druhej cudzi kluc na primarny z prvej tabulke
- Many-to-Many (m:n) - tu sa používa spojovacia tabuľka (obe tabuľky sú ku spojovacej tabuľke vo vzťahu 1:m)
- // creates a database
- CREATE DATABASE db1;
- // drops the database
- DROP DATABASE db1;
- // sets default database for queries
- USE db1;
- // creates a table
- CREATE TABLE Account
- (
- ID INT NOT NULL,
- Name VARCHAR2(16) NOT NULL,
- Password VARCHAR2(32) NOT NULL,
- Email VARCHAR2(32) NOT NULL,
- Account_Created DATE NOT NULL,
- PRIMARY KEY (ID)
- );
- // alters the table
- ALTER TABLE Account
- ADD <column_name> <datatype (INT)>;
- // drops the table
- DROP TABLE db1;
- // shows info about a table
- DESCRIBE <table>;
- // creates a select
- SELECT ID, Name, Email, TRUNC(Subscription_Ends) - TRUNC(sysdate) as Days_Remaining
- FROM ACCOUNT
- WHERE (TRUNC(Subscripti on_Ends) - TRUNC(sysdate)) <= 14;
- // inserts data into the table
- INSERT INTO Profession (ID, Name)
- VALUES (1, 'Alchemist');
- // inserts data into the table without specifying order of collumns
- INSERT INTO person SET first_name = 'John', last_name = 'Doe';
- // updates specific data in the table at given position
- UPDATE table_name SET column1 = value1, column2 = value2 WHERE id=100;
- // deletes data from table where...
- DELETE FROM Customers
- WHERE CustomerName='Alfreds Futterkiste';
- // replaces string/values on specific place (works exactly like INSERT only deletes the old value and inserts the new one even if they are exactly the same)
- REPLACE INTO t1 VALUES (...)
- // truncates the table
- TRUNCATE TABLE table_name;
- // rollbacks all changes
- ROLLBACK;
- // comits all changes
- COMMIT;
- // creates a view
- CREATE VIEW avg_values_races AS SELECT Race, TRUNC(AVG(HP)) as Average_HP, TRUNC(AVG(MP)) as Average_MP, TRUNC(AVG("EXP")) as Average_EXP
- FROM CHARACTER
- GROUP BY Race
- ORDER BY Race
- WITH READ ONLY;
- // lists the number of customers in each country, sorted high to low:
- SELECT COUNT(CustomerID), Country
- FROM Customers
- GROUP BY Country
- ORDER BY COUNT(CustomerID) DESC;
- // inner join - selects records that have matching values in both tables.
- SELECT Orders.OrderID, Customers.CustomerName
- FROM Orders
- INNER JOIN Customers ON Orders.CustomerID = Customers.CustomerID;
- // natural join - selects data from both tables (they have to have same name for collumns, same data type and you can't use ON clause on natural join)
- SELECT *
- FROM table1
- NATURAL JOIN table2;
- // intersect - vráti riadky ktoré sú v oboch tabuľkách (musia byť rovnakého typu a mena)
- SELECT Name, BirthDate FROM Employee
- INTERSECT
- SELECT Name, BirthDate FROM Customer
- // IN - dovoľuje špecifikovať viacero WHERE
- SELECT * FROM Customers
- WHERE Country IN ('Germany', 'France', 'UK');
- // EXISTS - The EXISTS operator is used to test for the existence of any record in a subquery and returns true if the subquery returns one or more records.
- SELECT SupplierName
- FROM Suppliers
- WHERE EXISTS (SELECT ProductName FROM Products WHERE SupplierId = Suppliers.supplierId AND Price < 20);
- GROUP BY - zgrupuje výsledok selectu s rovnakými atributmi v danom stĺpci
- ORDER BY - zoradí dáta podľa daného stĺpca
- INNER JOIN - selects records that have matching values in both tables
- NATURAL JOIN - selects data from both tables (they have to have same name for collumns, same data type and you can't use ON clause on natural join)
- (FULL) OUTER JOIN - elect vráti dáta ktoré matchujú v oboch tabuľkách a všetky dáta z oboch tabuliek
- LEFT/RIGHT JOIN - select vráti dáta ktoré matchujú v oboch tabuľkách a všetky dáta z ľavej/pravej tabuľky
- INTERSECT - vráti riadky ktoré sú v oboch tabuľkách (musia byť rovnakého typu a mena)
- IN - dovoľuje špecifikovať viacero WHERE
- EXISTS - operator is used to test for the existence of any record in a subquery and returns true if the subquery returns one or more records.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement