JAVA bevezets Devosa Ivn httpdevosa hu Szegedi Tudomnyegyetem
JAVA bevezetés Devosa Iván http//devosa. hu Szegedi Tudományegyetem v 111116
Java (programozási nyelv) n n n A Java egy objektumorientált programozási nyelv, amelyet a Sun Microsystems fejleszt a 90 -es évek elejétől kezdve napjainkig. A Java alkalmazásokat jellemzően bytecode formátumra alakítják, de közvetlenül natív gépikód is készíthető java forráskódból. A bytecode futtatása a java virtuális géppel történik, ami vagy interpretálja a bytecode-ot vagy natív gépikódot készít belőle és azt futtatja az adott operációs rendszeren. Létezik közvetlenül java bytecode-ot futtató hardware is, az úgynevezett Java processor. A java nyelv szintaxisát főleg a C és a C++ nyelvektől örökölte, viszont a java sokkal egyszerűbb objektummodellel rendelkezik, mint a C++. A Javascript szintaxisa és neve hasonló ugyan a Javahoz, de nincs közvetlen köze egymáshoz a két nyelvnek. Bár a nyelv neve kezdetben Oak (tölgyfa) volt, (James Gosling, a nyelv atyja nevezte így az irodája előtt növő tölgyfáról), de később kiderült, hogy ilyen elnevezésű nyelv már létezik, ezért végül Java néven vált ismertté. A Java szó a Sun Microsystems védjegye. Ennélfogva engedélye nélkül más nem használhatja más által kifejlesztett termékek megjelölésére még pl. Java-szerű 2 stb. összetételekben sem, mert ez a védjegyjogosult jogaiba
3
Általános tudnivalók n n n Négy fontos szempontot tartottak szem előtt, amikor a Javát kifejlesztették: objektum-orientáltság; függetlenség az operációs rendszertől, amelyen fut (többé-kevésbé); olyan kódokat és könyvtárakat tartalmazzon, amelyek elősegítik a hálózati programozást; távoli gépeken is képes legyen biztonságosan futni. 4
Objektum-orientáltság n A nyelv első tulajdonsága, az objektumorientáltság ("OO"), a programozási stílusra és a nyelv struktúrájára utal. Az OO fontos szempontja, hogy a szoftvert "dolgok" (objektumok) alapján csoportosítja, nem az elvégzett feladatok a fő szempont. Ennek alapja, hogy az előbbi sokkal kevesebbet változik, mint az utóbbi, így az objektumok (az adatokat tartalmazó entitások) jobb alapot biztosítanak egy szoftverrendszer megtervezéséhez. A cél az volt, hogy nagy fejlesztési projekteket könnyebben lehessen kezelni, így csökken az elhibázott projektek száma. 5
A Java szerepei n n n A Java szoftver három igen fontos szerepet tölt be: mint programozási nyelv; mint középszint; mint platform. A Java legfontosabb része a Java virtuális gép (Java Virtual Machine – JVM). A JVM mindenütt jelen van (szinte mindenféle berendezés, chip és szoftvercsomag tartalmazza), így a nyelv középszintként és platformként egyaránt működik. Ugyanakkor a nyelv "platformfüggetlen" is, mert a Java virtuális gépek interpretálják a szabványos Java gépi kódot. Ez azt jelenti, hogy egy PC-n megírt Java program minimális módosítás után ugyanúgy fog futni egy javás telefonon is. Innen jön az „írd meg egyszer, futtasd bárhol” kifejezés. Ez jelentős költségcsökkenést eredményez, mert a kódot csak egyszer kell megírni. 6
Platformfüggetlenség (hordozhatóság) n n n A második tulajdonság, a platformfüggetlenség azt jelenti, hogy a Javában íródott programok hasonlóan fognak futni különböző hardvereken. Ezt úgy lehet megvalósítani, hogy a Java fordítóprogram csak egy úgynevezett Java gépi kódra fordítja le a forráskódot, ami aztán futtatva lesz a virtuális gépben, amely lefordítja az illető hardver gépi kódjára. Továbbá, szabványos könyvtárcsomagok léteznek, amelyek elérhetővé teszik az illető hardver sajátságosságait (grafika, szálak és hálózat) egységes módon. Vannak olyan Java fordítóprogramok, amelyek natív gépi kódra fordítják le a forráskódot, ilyen például a GCJ, így valamelyest felgyorsítják a futtatást, de ugyanakkor a lefordított program elveszti hordozhatóságát. A Sun Microsystems licence ragaszkodik a különböző Java kivitelezések összeférhetőségéhez. Egyes cégek, mint például a Microsoft, mégis platformfüggő sajátságokat adtak a nyelvhez, amire a Sun keményen reagált: beperelte a Microsoftot (az amerikai bíróság 20 millió dollár kártérítésre és a sajátos tulajdonságok visszavonására kötelezte a céget). 7
n n n Válaszként a Microsoft kihagyta a Java rendszert a jövőbeli termékekből és Windows-változatokból. Ez azt jelenti, hogy az Internet Explorer web böngésző alapváltozataiból hiányzik a Java, így az olyan weboldalak, amelyek Javát használnak, nem fognak helyesen megjelenni. A Sun és más cégek ingyenesen letölthetővé tették a JVM rendszert azon Windows-változatok számára, amelyekből a virtuális gép hiányzik. A hordozhatóság megvalósítása technikailag nagyon bonyolult, a Java esetében is sok vita volt; az "írd meg egyszer, futtasd bárhol" szlogenből "írd meg egyszer, hibakeress mindenhol" lett. Ennek ellenére a Java sikeres lett a servletek és Enterprise Java Beans kiszolgáló oldali programozásokban. 8
Biztonságos távoli futtatás n A Java rendszer volt az első, amely lehetővé tette a távoli gépeken való futtatást. Egy kisalkalmazás futtatható volt a felhasználó gépén (letöltve a Java kódot egy HTTP kiszolgálóról). A kód egy biztonságos környezetben fut, amely nem teszi lehetővé a "rossz szándékú" kód futtatását; a kiadók kérhetnek olyan tanúsítványokat, amelyeket digitálisan aláírnak, tanúsítva, hogy a kisalkalmazás (applett) biztonságos, lehetővé téve ennek kilépését a biztonságos környezetből (ugyancsak a felhasználó felügyelete alatt, de a fájlrendszerhez ekkor sem férhet hozzá!). 9
Változatok n n n n 1. 0 (1996) – ez volt az első verziója a Java virtuális gépnek és az osztálykönyvtáraknak. 1. 1 (1997) – itt jelent meg először a belső osztály fogalom, ami lehetővé teszi több osztály egymásba ágyazását. 1. 2 (1998) – ez a verzió számottevő mérföldkö volt a nyelv evolúciójában. Hogy ezt kihangsúlyozza, a Sun hivatalosan Java 2 -nek nevezte el. 1. 3 (2000) – csak néhány kisebb változtatást végeztek el rajta. 1. 4 (2002) – ez ma a legelterjedtebb változat. 5 (2004) – belső számozás szerint 1. 5, kódneve Tiger, újdonsága pl. a továbbfejlesztett ciklusmegoldások, az adattípusok automatikus objektummá alakítása (autoboxing), a generic-ek. 6 (2006) – belső számozás szerint 1. 6. 0, kódneve Mustang. Decemberben jelent meg a végleges változat kiterjesztett nyomkövetési és felügyeleti megoldásokkal, szkriptnyelvek integrációjával, grafikusfelület-tervezést támogató kiegészítésekkel. 10 7 (2008? ) – kódneve Dolphin
11
12
13
14
A klasszikus „Helló Világ!” Javában public class Hello. Vilag { public static void main(String[] args) { System. out. println("Helló Világ!"); } } 15
Kommentezés n n n n n // komment (megjegyzés sor) /* * több soros megjegyzés */ /** * ezt a kommentet a Java. Doc használja a * dokumentáció generálásához */ 16
Változók, konstans n n n n Változók int i; //(csak deklarálom) int i =5; //deklarálom ÉS inicializálom Elnevezési szabály: $, _, betű lehet a kezdőkarakter, (szám nem!!!), szokás kisbetűvel kezdeni. Pl. int felhasznalo. Szuletesi. Eve; Konstans final int TOMBMERET = 5; (Kötelező: deklaráláskor inicializálni is!!!) Elnevezési szabály: $, _, betű lehet a kezdőkarakter, szokás csupa nagybetűvel írni. Pl. fent 17
Hatókör és összetett kifejezés n n n Az egyszerű utasítások pontosvesszővel záródnak (; ). Az összetett kifejezések hatókörét a kapcsos zárójel határozza meg: package b 01; public class Main { public static void main(String[] args) { System. out. println("The first sentence. "); System. out. println("The second sentence. "); } } 18
Tömb n n Definíció: „Azonos típusú adatok indexelt halmaza” (Vedd észre: Nem feltétel a rendezettség!) 19
Tömb n n n Létrehozás: pl. 5 db integer (egész) számot tartalmazó tömb: int[] t = new int[5]; Számozása 0 -tól indul, így a „t” nevű tömb 3 -ik elemére úgy hivatkozok, hogy pl. : t[2]=34; Az egydimenziós tömb neve: vektor Hossza: int hossz = t. length; 20
Egész számérték beolvasása n n n n public static void main(String[] args) throws java. io. IOException { int szamertek; System. out. println("Üdvözlöm! Kérem írjon be egy számot 0 -9 -ig. "); szamertek = System. in. read()-48; System. out. println("A beütött szám: " + szamertek); } 21
Karakter beolvasása n n n n public static void main(String[] args) throws java. io. IOException { char a; System. out. println("Üdvözlöm! Kérem írjon be egy betűt. "); a = (char) (System. in. read()); System. out. println("A beütött betű: " + a); } 22
Alapvető adattípusok Változó típusa Leírás byte 8 bites előjeles egész short 16 bites előjeles egész int 32 bites előjeles egész long 64 bites előjeles egész float 32 bites egyszeres lebegőpontosságú double 64 bites kétszeres lebegőpontosságú char 16 bites Unicode-karakter boolean logikai érték (igaz / hamis) 23
Karakterek n A Java a 16 bites Unicode kódolást (az UTF -16 -ot) használja. Ez tartalmazza a szabványos ASCII-karaktereket, de ugyanakkor tartalmazza más nyelvek karakterkészletét is (pl. : görög, cirill, kínai, arab stb. ). A Java programok mindezeket a karakterkészleteket képesek használni, habár a legtöbb szerkesztőprogram csak a hagyományos ASCII karakterkészletet támogatja. 24
Vezérlési szerkezetek n Ciklusok n Feltételes utasítások n Kivételkezelés 25
Ciklusok (loops, iterations) n n for (inicializálás ; belépési feltétel ; adalékos feltétel) ELŐLTESZTELŐ { utasítás(ok) } 26
for (példa) n n n Számoljunk el 1 -től 10 -ig, és írjuk ki for (int i=1; i<=10; i=i+1) { System. out. println(i); } Az „i” szokásos jelölés: i = index, iterátor 27
Inkrementáló és dekrementáló operátorok n n n n Az egyszerűbb írásmód és a gyorsabb működés miatt használatos operátorok: i=i+1; helyett i++; i=i-1; helyett i--; i=i+5; helyett i+=5; i=i-x; helyett i-=x; i=i*2; helyett i*=2; i=i/3; helyett i/=3; i=i%2; helyett i%=2; 28
Ciklusok (loops, iterations) for (elem : tömb) n { n utasítás(ok) n } PÉLDA (for-each) for (String s : new String[]{„Kati", „Pityu", „Gábor"}) { System. out. println(s); } n 29
Ciklusok (loops, iterations) n n while (logikai kifejezés) ELŐLTESZTELŐ { utasítás(ok) } 30
Ciklusok (loops, iterations) n n n do { utasítás(ok) } while (logikai kifejezés); HÁTULTESZTELŐ 31
Beolvasás Scanner osztállyal n n n n import java. util. *; //külső osztály hívás helye class Main { public static void main(String[ ] args) { Scanner olvas = new Scanner(System. in); int x = olvas. next. Int(); //szám beolvasása String s = olvas. next. Line(); //szöveg beolvasása 32
HF n Olvass be egy számot, és egy karaktert, majd írasd ki a karaktert annyiszor, amennyi a szám 33
n n n public static void main(String[] args) throws java. io. IOException { System. out. println(„Kiíratandó: "); int kar = System. in. read(); //karakter beolv. char c = (char) (kar); //konvertálés int>char System. in. read(); //Enter miatt kell System. out. println("Hányszor: "); int szam = System. in. read()-48; System. out. println("---Kiírás---"); for (int i = 1; i<=szam; i++) { System. out. println(c); } } //main vége 34
Feltétel nélküli ugróutasítások n A Java nem támogatja a goto utasítást, mivel ennek használata pongyola kódot eredményez. Nagyon ritkán mégis szükség van a goto-ra, a Java lehetővé tesz alternatív megoldásokat. A goto fenntartott szó és nem használható azonosítóként. 35
Korai kilépés a ciklusokból A Java nyelv két utasítást is ad a ciklusból való kilépéshez. A continue; utasítás befejezi a folyamatban levő ismételgetést és egy újabbat kezd (ugyanúgy viselkedik, mint a ciklus elejére ugró goto). Hasonlóan, a break; utasítás teljesen kilép a ciklusból, és több ismételgetést nem hajt végre. A hatás ugyanaz, mint egy goto utasítás a cikluson kívülre. 36
Többszintű ciklusból is ki lehet lépni n n kulso: while (true) { • belso: while (true) • { • break; // kilépés a legbelső ciklusból • break belso; // ugyancsak kilépés a legbelső ciklusból • break kulso; // kilépés a legkülső ciklusból • } n } 37
Korai kilépés az metódusokból A return; utasítás befejez egy eljárást. A return Érték; visszaad a hívó metódusnak egy értéket (Érték) is visszatéréskor. 38
Feltételes utasítások (conditional expressions) n n if (logikai kifejezés) { utasítás(ok) } 39
Feltételes utasítások (conditional expressions) n n n n if (logikai kifejezés) { utasítás(ok) } else { utasítás(ok) } 40
if (példa) n n Adott két számérték, ezek nagysága dönti el a program további futását, ha ‘a’ a nagyobb azt írjuk, ha ‘b’ akkor azt. int a=10; int b=15; if (a>b) { System. out. println(a); } else { } System. out. println(b); Ugyanez tömörebb megfogalmazásban int ered; ered=(a>b)? a: b; System. out. print(ered); 41
Döntési fa n n n n if i/ h if i/ h Vegyük észre: egymásba ágyazott döntéseknél függnek a megelőző döntések eredményétől, DE független döntések. (Pl. elmegyek ebédelni? Ha igen, menüt eszem, vagy egyénit? ) 42
Feltételes utasítások (conditional expressions) n n if (logikai kifejezés) { utasítás(ok) } • else if (logikai kifejezés) • { utasítás(ok) } else if (logikai kifejezés) n { utasítás(ok) } n • else { utasítás(ok) } 43
Logikai kifejezések p q && (AND) || (OR) ^ (XOR) I I H I H H I I H H H 44
if (komplex példa) n n n Csak akkor teljesüljön a feltétel, ha mindkét feltétel igaz. Pl. ha x értéke 21 és 50 közé esik (21<=x<=50) if((x>=21) && (x<=50)) Ha elegendő az egyik feltétel igazsága, de egynek mindenkép teljesülnie kell! Pl. ha egy szám osztható kettővel vagy hárommal (azaz osztási maradéka vagyis modulója nulla) if((x%2==0)||(x%3==0)) 45
Reláció operátorok n A feltételvizsgálat operátorai: • Egyenlő –e? pl. if (4 == x) • Nem egyenlő –e? pl. if (4 != x) • Kisebb –e? pl. if (4 < x) • Nagyobb –e? pl. if (4 > x) • Kisebb egyenlő –e? pl. if (4 <= x) • Nagyobb egyenlő –e? pl. if (4 >= x) 46
Feltételes utasítások n n n n switch (egész kifejezés) { case konstans egész kifejezés utasítás(ok) break; …. default: utasítás(ok) break; } 47
class Switch. Demo { public static void main(String[] args) { int month = 8; switch (month) { case 1: System. out. println("Jan"); break; case 2: System. out. println("Feb"); break; case 3: System. out. println("Már"); break; case 4: System. out. println(„Ápr"); break; case 5: System. out. println("Máj"); break; case 6: System. out. println("Jun"); break; case 7: System. out. println("Jul"); break; case 8: System. out. println("Aug"); break; case 9: System. out. println("Szep"); break; case 10: System. out. println("Oct"); break; case 11: System. out. println("Nov"); break; case 12: System. out. println("Dec"); break; default: System. out. println(„Érvénytelen hónap!!"); break; } } } 48
Véletlenszám generálás n n n A „Math” osztály „random” metódusával történik, mely alapesetben 0 és 1 intervallumon generál számokat, és visszatérési értéke double típusú Intervallum módosítása: pl. max=16 és min=10 között generáljon integer számokat: int x = (int) (Math. random()*(maxmin+1)+min); int x = (int) (Math. random()*(16 -10+1)+10); Az (int) (…. . ) az ún. típuskényszerítés! 49
Random példák n n n n n 10<=x<=20 int x = (int) (Math. random()*(20 -10+1)+10) 1<=x<=90 int x = (int) (Math. random()*(90 -1+1)+1) 85<=x<=120 int x = (int) (Math. random()*(120 -85+1)+85) Negatívok: -100<=x<=110 int x = (int) (Math. random()*(110 -(-100) +1)+(-100)) int x = (int) (Math. random()*(110+100) +1)-100) 50
Gyakorlat n n Feladat: Olvassuk be a 3 oldal értékét paraméterként (ha adottak), ha nem generáljunk 3 db számot, melyek rendre egy háromszög oldalai (a, b, c) Ellenőrizzük, hogy a generált számok kiadnak-e egy háromszöget? (a<b+c) és (b<a+c) és (c<a+b) Ha igen, számoljuk ki a háromszög kerületét (K=a+b+c) és Területét a Héron képlettel T=Math. sqrt(S*(S-a)*(S-b)*(S-c)) ahol S=K/2 51
Argumentumtömb (args) n n n n A tömb a program indításakor töltődik fel adatokkal (ha vannak!) Csak Stringek szerepelnek benne Pl. konzolon ”java progi 2 3” Public static void main(String[] args){ System. out. println(args. length); //int: 2 System. out. println(args[0]); //String: ” 2” System. out. println(args[1]); //String: ” 3” } 52
Típuskonverzió n n n Típuskényszerítéssel (int) (kényszerített típus) ellentétben nincs adatvesztés Minden típusnak van osztály megfelelője: char – Char; int – Integer; byte – Byte stb… Konvertáló metódus: . value. Of() Pl. String a=” 34”; int b = Integer. value. Of(a); 53
n n n n n public static void main(String[] args) { if (args. length >= 2) { int a = Integer. value. Of(args[0]); int b = Integer. value. Of(args[1]); System. out. println(a + b); } else { System. err. println("HIBA!"); } } } 54 n
Kivételkezelés n n n n try { utasítás(ok) } catch (kivételtípus) { utasítás(ok) } finally { utasítás(ok) } 55
Kivételkezelésre példa n n n n n Szeretnénk a hibás számformátum esetén, ha program nem lefagyna, hanem kezelné a kivételt (hibát), és szabályozottan állna le. String a=”k”; try { int k = a; //hiba azaz kivétel egy fajtája } catch (Number. Format. Exception e) { System. out. println(”Hibás számformátum”); System. exit(1); //kilépés hibakóddal, a normál kilépés kódja mindig 0 n } 56
Gyakorlat (try) n n Args tömbből olvastassunk be két számot, ha nem hibás a számformátum (pl. betű) akkor generáljunk két számot 25<=x<=70 között. Ez két oldalhosszt reprezentál. Ha a két szám hányadosa kisebb mint 1, akkor számítsuk ki egy négyzet kerületét, területét, ha nagyobb, akkor egy téglalap kerületét területét. 57
Kétdimenziós tömb n n n Emlékeztető: Definíció: „Azonos típusú adatok indexelt halmaza” (Vedd észre: Nem feltétel a rendezettség!) 58
Kétdimenziós tömb n n Létrehozás: pl. 5 soros 6 oszlopos integer (egész) számot tartalmazó tömb: int[][] t = new int[5] [6] ; Számozása 0 -tól indul, így a „t” nevű tömb 3 -ik sori 2 -ik oszlopi elemére úgy hivatkozok, hogy pl. : t[3][2]=34; A hossza: int hossz = t. length; 59
n n n n public class Break. With. Label. Demo { public static void main(String[] args) { int[][] array. Of. Ints = { { 32, 87, 3, 589 }, { 12, 1076, 2000, 8 }, { 622, 127, 77, 955 } }; int searchfor = 12; int i, j = 0; boolean found. It = false; search: //címke for ( ; i < array. Of. Ints. length; i++) { for (j = 0; j < array. Of. Ints[i]. length; j++) { if (array. Of. Ints[i][j] == searchfor) { found. It = true; break search; }}} if (found. It) { System. out. println("Found " + searchfor +" at " + i + ", " + j + '. '); } else { System. out. println(searchfor + "not in the array. "); }}} 60
String (Java-ban osztály!) n n n n n Unicode kódolású szöveget használ Sorszámozott: 0 -tól indul Tehát ha hossza n, akkor utolsó karaktere n-1 -ik! Létrehozás: String s = new String(„hello”); Vagy String s = „hello”; Vagy (karakterek tömbjéből) char[] ct = {‘c’, ’i’, ’c’, ’a’}; String s = new String(ct); 61
Stringműveletek n n Összefűzés: s 3=s 1+s 2 vagy s 5=s 4. concat(„ezt még”); Hossz lekérdezése int length() int hossz = s 1. length(); Adatot szöveggé konvertál String s = String. value. Of(adat) 62
Stringek összehasonlítása Csak ha azonos objektumra mutatnak használható az == művelet! Pl. String s 1, s 2=„ok”; igaz, de String s 1=„ok”; és String s 2=„ok” hamis!! n Ami szöveget hasonlít: n Boolean equals(Object obj) Pl. if (s 1. equals(s 2)) {… n Boolean equals. Ignore. Case(String str) Pl. if (s 1. equals. Ignore. Case (s 2)) {… //kis- és nagybetű ekkor nem számít n 63
String átalakítása, karakterlekérdezés Char char. At(int index) //char adott helyen Pl. char c = s 1. char. At(4); n String to. Upper. Case() //nagybetűssé konvertál Pl. String s 2 = s 2. to. Upper. Case(); n String to. Lower. Case() //kisbetűssé konvertál Pl. String s 2 = s 2. to. Lower. Case(); n 64
Stringbeszúrás String trim() //nyitó és záró szóközök nélkülivé konvertál n Pl. String s 6=” Demo szavak ”. trim(); n String replace (char régikar, char újkarakter); Pl. String s 3 = s 1. replace(‘a’, ’A’); n String substring(int kezdőérték) n String substring(int kezdőérték, int végérték) //részstring Pl. String s 4 = s 2. substring(6, 9); n 65
Struktúra helyetesítése n n n n n A C, C++, C# struktúrája (strukt) nem ismert a Java-ban. Helyette az osztállyal valósítunk meg a különböző adattípusok egységbe zárását. public class Adatok //sablon létrehozása { String neve; int kora; } … Adatok a 1 = new Adatok(); //példányosítás = objektum a 1. neve=”Kati”; System. out. println(a 1. neve); 66
A gyakorlati megvalósítás A Java programozásához is használhatunk programozási környezetet (Net. Beans, Eclipse), vagy egyszerű szövegszerkesztőt, melyből elkészült munkánkat pl. hello. java néven mentjük. n Majd: compiling „javac hello. java” n Végül: running „java hello” Itt az ideje megírni stringkezelő programunkat CMD és Unix alatt n 67
String metódusok JAVA (PPT)
- Slides: 68