Você está na página 1de 77

Introduction to Java

Course Software in Electronics and Telecommunications English classes

Overview
Basic Elements concerning Java C++ to Java Transaction Java evolution Java applications and utilities IDEs in Java Eclipse Comparison between Java and C++ languages
2

Basic Elements Concerning Java


History 1.0 1.7, JavaOne annual conference to discuss Java technologies (22-26 September 2013, San Francisco) JDK 1.0-1.1 J2SE 1.2-1.5 JSE 6, 7 (update 40) JSE 8 (2013, summer, 2014/03/18 General Availability), JSE 9, Basic characteristics:
-pure objectual -platform independent
3

Platform independence

Java SE Characteristics
-Compiler/interpreter language (Java, C++) -JVM- Java Virtual Machine Other main Java products: -Java ME- Mobile platforms (Android) -Java Enterprise Edition -The Java Enterprise Edition (Java EE) is tailored for more complex applications to suit medium to large businesses. Typically they will be server based applications focusing on serving the needs 5 of lots of users at one time.

-JavaFX - The Rich Client Platform JavaFX is the next step in the evolution of Java as a rich client platform. It is designed to provide a lightweight, hardware-accelerated Java UI platform for enterprise business applications. With JavaFX, developers can preserve existing investments by reusing Java libraries in their applications. They can even access native system capabilities, or seamlessly connect to server-based middleware applications.
6

Aplicaie Java PLATFORMA JAVA Java API Java VM Java RE Platforma nativa software/hardware

Other Java Characteristics:


-multithreading -distributed -architecture neutral -pure objectual -portable -robust -secure
8

C++ to Java Transaction


-differences from C++:
-no multiple inheritance -no problems with space names, from packages to local block -no pointers -no independent methods -applications no main() method (applets, midlets,) -no templates till JDK 1.5 -exceptions treatment, try-catch() -garbage collection including for distributed applications

Java Developers Kit


-all tools to create, debug and execute programs -evolution from JDK 1.0 1.1.7, J2SE (JDK 1.2 1.4), with generics JDK 1.5 (Tiger), Java SE6 (Mustang), Java SE7, -IDE, Eclipse, NetBeans -source files, *.java -bytecode, *.class
10

Java SE 7 (July 28, 2011)


codename Dolphin, and as additions:
JVM support for dynamic languages, following the prototyping work currently done on the Multi Language Virtual Machine -Compressed 64-bit pointers -Small language changes (grouped under a project named Coin): -Strings in switch -Automatic resource management in try-statement -Improved type inference for generic instance creation -Simplified varargs method declaration -Binary integer literals -Allowing underscores in numeric literals -Catching multiple exception types and re-throwing exceptions with improved type checking
11

-Concurrency utilities -New file I/O library to enhance platform independence and add support for metadata and symbolic links. The new packages are java.nio.file and java.nio.file.attribute -Library-level support for Elliptic curve cryptography algorithms -An XRender pipeline for Java 2D, which improves handling of features specific to modern GPUs -New platform APIs for the graphics features -Enhanced library-level support for new network protocols, including SCTP and Sockets Direct Protocol -Upstream updates to XML and Unicode

12

Java SE 8
Java 8 was expected for October 2012 (now march 2014) and will include at a minimum the features that were planned for Java 7 but later deferred. Modularization of the JDK under Project Jigsaw Language-level support for lambda expressions (officially, lambda expressions; unofficially, closures) - anonymous methods - under Project Lambda used with inner classes. There was an ongoing debate in the Java community on whether to add support for lambda expressions. Sun later declared that lambda expressions would be included in Java 8 and asked for community input to refine the feature. Parts of project Coin that are not included in Java 7
13

Structure of Java Platform

14

Structure of JDK (bin, db, demo, include, ...)


15

Applications Types in Java


-stand alone -applets -appletcations -servlets, midlets, aglets, etc. -packages from API

16

Main Java 2 SDK packages


17

Java Utilities
-compiler: javac nume_fiier.java -interpreter: java nume_clasa_main -appletviewer nume_fiier.html -javadoc nume_fiier.java -javap nume_fiier.class (disassembler) -jdb (Java language debugger)

18

19

Main packages
-java.util - implicit -java.lang (Integer, Float,...) -java.awt -java.io -java.math -java.net -javax.swing -org.xml
20

Integrated Development Environments (IDEs) in Java


An IDE is an Integrated Development Environment Different IDEs meet different needs
BlueJ, DrJava are designed as teaching tools
Emphasis is on ease of use for beginners Little to learn, so students can concentrate on learning Java

Eclipse, JBuilder, NetBeans are designed as professional-level work tools


Emphasis is on supporting professional programmers More to learn, but well worth it in the long run

We will use Eclipse, but other professional IDEs are similar. 2013 Eclipse version is named Kepler. The following slides are taken from
www.eclipse.org/eclipse/presentation/eclipse-slides.ppt
21

Workbench Terminology
Menu bar Tool bar Perspective and Fast View bar Text editor

Outline view

Resource Navigator view Bookmarks view

Properties view Message area

22

Stacked views

Tasks view

Editor Status area

Help Component
Help is presented in a standard web browser

23

Java Development Tools


JDT = Java development tools State of the art Java development environment Built a top Eclipse Platform
Implemented as Eclipse plug-ins Using Eclipse Platform APIs and extension points

Included in Eclipse Project releases


Available as separately installable feature Part of Eclipse SDK drops

24

Java Perspective
Java-centric view of files in Java projects
Java elements meaningful for Java programmers

Java project package class field method Java editor


25

Java Perspective
Browse type hierarchies
Up hierarchy to supertypes Down hierarchy to subtypes

Type hierarchy

Selected types members


26

Java Perspective
Search for Java elements
Declarations or references Including libraries and other projects

Hits flagged in margin of editor


All search results

27

Java Editor
Hovering over identifier shows Javadoc spec

28

Java Editor

Method completion in Java editor


Doc for method

List of plausible methods

29

Java Editor
On-the-fly spell check catches errors early

Click to see fixes Problem Quick fixes


30

Preview

Java Editor
Code templates help with drudgery

Statement template

Preview

31

Java Editor

Java editor creates stub methods

Method stub insertion for anonymous inner types

Method stub insertion for inherited methods

32

Java Editor

Java editor helps programmers write good Java code


Variable name suggestion
JavaDoc code assist

Argument hints and proposed argument names

33

Eclipse Java Compiler


Eclipse Java compiler
JCK-compliant Java compiler (selectable) Helpful error messages Generates runnable code even in presence of errors Fully-automatic incremental recompilation High performance Scales to large projects

Multiple other uses besides the obvious


Syntax and spell checking Analyze structure inside Java source file Name resolution Content assist Refactoring Searches
34

Eclipse Java Debugger


Run or debug Java programs
Local variables

Threads and stack frames Editor with breakpoint marks Console I/O
35

Eclipse Java Debugger


Run Java programs
In separate target JVM (user selectable) Console provides stdout, stdin, stderr Scrapbook pages for executing Java code snippets

Debug Java programs


Full source code debugging Any JPDA-compliant JVM

Debugger features include


Method and exception breakpoints Conditional breakpoints Watchpoints Step over, into, return; run to line Inspect and modify fields and local variables Evaluate snippets in context of method Hot swap (if target JVM supports)

36

Comparison between Java and C++ languages


Basic elements (supplementary details):
-key words- feeling and expressivity of the language: data, loops, conditional, exceptions, access modifiers, others -variable: declaration, assign, init, cast, visibility -identifiers: recommendation rules -constants: public, static and final -characters: are of UNICODE type (\uxxxx) -expressions: combinations of operands and operators 37

-primitive data types: byte, short, int,

long, char, float, double and boolean

-predefined constants: POSITIVE_INFINITY,


NEGATIVE_INFINITY, NaN (Not a Number) -IEEE 754 standard for dimensions
-wrrapers classes:

Byte, Short, Integer, Long, Character, Float, Double and Boolean


autobox : Integer iObj=10;

or classical, Integer iObj=new Integer(10); auto-unbox: int i = iObj; or classical, int i= iObj.intValue(); Other methods from wrrapers and String class: int i = Integer.parseInt(args[0]); 38 String os = String.valueOf(5); String str = iObj.toString();

Operators: >>> shift right zero fill,


-instanceof == will compare addresses for objects and values for primitive data types -No numerical to boolean conversions

Conversions:
-implicit, cost <10 no exception: widenning (int -> long), narrowing (int -> byte), truncation (float -> int) -explicit with cast operators Comments: /* C */ //C++ /** Java */ 39

Control statements:
-condition, always of boolean type -break, continue with labels -no goto(), but reserved -try, catch, throw, throws, finnaly for exceptions -for...each, for loops from JSE5:
for(type itr_var:collection) block_statement Example: int nums[] = {1,2,3,4,5}; int sum = 0; for(int i=0;i<5;i++)sum+=nums[i];//classic for(int x: nums)sum+=x;//for_each
40

Break with label


Example: int contor=0; for( ; ; ){ contor++; if(contor%3==0) break eticheta1; if(contor%2==0) break eticheta2; } eticheta1: System.out.println(Eticheta 1); eticheta2: System.out.println(Eticheta 2);
41

For-each instruction
for(tip_variabila nume_variabila:

nume_variabila_de_tip_sir){ //instructiuni } and for(tip_variabila nume_variabila: nume_variabila_de_tip_colectie){ //instructiuni }

42

Example: int[] numere = {1,2,3,4,5,6,7,8,9,10}; for (int element : numere) { System.out.println("Elementul

curent: " + element); }

43

import java.util.Iterator; import java.util.Vector; class Test { public static void main(String[] arguments) { String[] codes = { "alpha", "lambda",

"gamma", "delta", "zeta" }; Vector list = new Vector(); for (int i = 0; i < codes.length; i++) { if (!list.contains(codes[i])) { list.add(codes[i]); } }

44

//varianta clasica de abordare for (Iterator ite = list.iterator(); ite.hasNext();) { String output = (String) ite.next(); System.out.println(output); } //varianta for-each for (Object s : list) { //String output = (String) ite.next(); System.out.println((String)s); } }//main }//class
45

-primitive and object arrays -one-dimensional, multi-dimensional - each row may have a variable number of elements -declaration as a reference value: int iTab[]; int []iTab; -create with new: iTab=new int[5]; -declare and create an array: int iTab[] =new int[5]; -assign values: {e1, e2, }, by program, from other array with arraycopy() method from System class -destroyed automatically by gc() method. -length variable associated to array object:
int lengthTab=iTab.length;

Java arrays

Multi-dimensional arrays:
int twoD[][]=new int[4][5]; or int twoD[][]=new int[4][]; twoD[0]=new int[5]; twoD[3]= new int[7];
46

System class arraycopy()


public static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length)

47

Example: int[] sir = {100, 101, 102, 103, 104,

105, 106, 107}; int nr_elemente = sir.length;


int matrice[][] = new int[3][3]; for(int i=0; i<3; i++) for(int j=0; j<3; j++) matrice[i][j] = 0;
48

class Test{ public static void main(String[] args){ int mat[][] = new int[2][]; //liniile au numar diferit de elemente mat[0] = new int[8]; mat[1] = new int[2]; mat[0][0] = 100; mat[0][1] = 101; mat[0][2] = 102; mat[0][3] = 103; mat[0][4] = 104; mat[0][5] = 105;
49

mat[0][6] = 106; mat[0][7] = 107; mat[1][0] = 1; mat[1][1] = 2; //afisarea matricei for(int i=0; i<2; i++){ System.out.println("\nlinia "+i+"\n"); for(int j=0; j<mat[i].length; j++){ System.out.print(mat[i][j]+" "); } }//for } //main } //class
50

Example: char[] sursa = { 'a', 'b', 'c', 'd', 'e', 'f',

'g', 'h};

char[] destinatie = new char[3]; System.arraycopy(sursa, 2, destinatie, 0, 3);

51

Java Strings
String, constant string StringBuffer, variable strings StringBuilder, optimized for multithreading StringTokenizer, extract tokens
A Java string may be considered as an array of characters represented in Unicode (6.x) with no \0 as end character as in C/C++ A lot of specific methods for each class exist (see lab.) The dimension is determined with length() method
52

String s1 = new String(abc); String s2 = s1 + def; //sirul def

este convertit automat in String String s3 = s1 + 5; //se concateneaza sirul initial cu sirul de caractere 5 System.out.println(s1 + s2 + 100.23f); //etc.
53

public class Test{

public static void main(String[] args) { System.out.println("Test StringBuffer!"); StringBuffer sb = new StringBuffer(0); //inserarea la prima poziie System.out.println(sb.insert(0, inceput")); //determinarea lungimii int len = sb.length(); //inserarea la sfarsit System.out.println(sb.insert(len, "sfarsit")); //inserarea la o pozitie intermediara a unei instante anonime de tip Integer System.out.println(sb.insert(7, new Integer(777))); //inserarea la sfarsit a unei variabile de tipul elementar int System.out.println(sb.append(888)); } }

54

class Test{ public static void main(String[] args) { //declararea si initializarea unei var. de tip StringBuffer StringTokenizer st = new StringTokenizer("abc;def;ghi", ";"); //parcurgerea tutuor poriunilor irului iniial de caractere while(st.hasMoreElements()){ System.out.println("Elementul curent:

"+st.nextToken()); } } }

55

Methods
-utility methods:
import java.lang.Math.*; Math.pow(...); import static java.lang.Math.*; pow(...); import static java.lang.System.* out.println(test);// not System.out.println(test);

command line arguments:


name as first parameter

no application

varargs parameters:

from JSE5
56

Command line arguments


public class ArgsTest { public static void main(String args[]) { System.out.print(args[0]: + args[0]); System.out.print(args[1]: + args[1]); } > java ArgsTest Hello World
57

Methods with a variable number of parameters


Sintaxa: [specificatori_de_acces] tip_returnat numeMetoda

(tip_parametru ... nume_variabila){ //implementare metoda }

Example: public int numarare(int... valori) { int rez = valori.length; return rez; }
58

Variable argument methods are very similar to a method with an array of integers (primitives, objects, arrays) as a parameter. In a program, you must know the number of elements in an array to be able to create an array. If the number of elements changed, you would have to make a different array for each different length. Using a variable argument method allows for use of the method without ever having to initialize an array. It also allows for multiple uses with a variable number of elements.
59

class VarArgs{ static void vaTest(intv){ System.out.println(No. of args=+ v.length + Contents:); for(int x:v) System.out.print(x+ ); System.out.println();}//vaTest public static void main(String args[]){ vaTest(10);//1 arg vaTest(1,2,3);//3 args vaTest();//no arg }//main }//class
60

Pointers
no pointers references no parameters transferred by pointers no pointers to methods un-instantiated variables of Object class to define arrays of references to methods

61

Classes in C++ and Java


-In Java the general class form is: [lista_modificatori] class idClasa [extends

idClasaBaza] [implements lista_ interface] { corp_clasa }

62

Main differences:
-no scope operator, :: -no multiple variable with the same access specifier -extends for class inheritance -implements, for interface inheritance -super to access constructors or other methods from base class (Example) -protected access specifier modified in a package (private protected any protected member is able to be accessed in the package, without inheritance) -default, accessed by any class in the package if no keyword is specified

63

Direct access to members


class MyClass{ private int i; //metoda accesor public void afiseaza(){ System.out.println(Valoarea lui i este +i); } //metoda mutator public void seteaza(int valoare_noua){ i = valoare_noua; //accesarea unei variabile din clasa afiseaza(); //accesarea unei metode din clasa } }
64

Indirect access to members using a class


class MyClass{ private int i; //metoda accesor public void afiseaza(){ System.out.println(Valoarea lui i este +i); } //metoda mutator public void seteaza(int valoare_noua){ i = valoare_noua; //accesarea unei variabile din clasa } }

65

class Test{ public static void main(String[] args){ MyClass ob1 = new MyClass(); // instantierea clasei MyClass ob1.seteaza(7); // apelul metodei din clasa ob1.afiseaza(); // apelul metodei din clasa } }

66

Access for static members


class MyClass{ public static int i; //metoda mutator statica public static void seteaza(int valoare_noua){ i = valoare_noua; //accesarea unei variabile din clasa }

67

class Test{ public static void main(String[] args){ MyClass.seteaza(7); // apelul metodei statice din clasa

//accesarea variabilei statice din clasa System.out.println(Valoarea lui i este +MyClass.i); }


}

68

Explicit this parameter


class MyClass{ int x; void mutator(int x){ this.x = x; //ar fi fost non-sens

//expresia x = x;

} }
69

class MyClass{ int x; //primul constructor MyClass(int valoare_noua){ x = valoare_noua; } //al doilea constructor MyClass(){ this(0); //apelul primului constructor } }
70

Nested/Inner classes
Define a class, NestedClass, within an other class OuterClass, where NestedClass does not exist independently of OuterClass. class OuterClass { ...
class NestedClass { ... //InnerClass }//N

} //O
71

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.
72

class OuterClass { ... static class StaticNestedClass { ... } class InnerClass { ... } }

Static nested classes do not have access to other members of the enclosing class.
OuterClass.StaticNestedClass staticNestedObject = new

OuterClass.StaticNestedClass();

73

A nested class (non static) is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. As a member of the OuterClass, a nested class can be declared private, public, protected, or package private (private protected).
74

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:
OuterClass outerObject = new OuterClass(); OuterClass.InnerClass innerObject = outerObject.new

InnerClass();

75

Abstract classes
abstract class NumeClasa{ public abstract void metodaAbstracta(); public void metodaNormala(){ //implementarea metodei } }

76

In a class the finalize() method will be called before the garbage collection, as a destructor. instanceof operator is used to verify if an object belongs to a class or not A class with final acces specifer will not be inherited. Involves early binding. May be used for constants and methods.
77

Você também pode gostar