Sie sind auf Seite 1von 85

Introduction to Java

Course
Software Engineering in Electronics and
Telecommunications English classes

1
Overview
Basic Elements concerning Java
C++ to Java Transaction
Java evolution
Java applications and utilities
IDEs in Java Eclipse/NetBeans
Comparison between Java and C++
languages
2
Basic Elements Concerning Java
History, JavaOne annual conference to
discuss Java technologies (22-26 September
2013, 28 September 2 October 2014, San
Francisco)
JDK 1.0-1.1
J2SE 1.2-1.5
JSE 6, 7
JSE 8 (announced 2013, appeared
2014/03/18), JSE 9,
Basic characteristics:
-pure objectual
-platform independent
3
Platform independence
4
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
of lots of users at one time.
5
-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
7
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
9
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,
Java SE6, Java SE7, Java SE8,
-IDE, Eclipse, NetBeans
-source files, *.java
-bytecode, *.class
10
Java SE 7 (July 28, 2011,
now update 67)
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 (appeared march 2014,
now update 20) 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. Oracle later
declared that lambda expressions would be included in Java 8
and asked for community input to refine the feature.
default and static methods on interfaces "allow a form of
multiple inheritance"
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_fisier.java
-interpreter: java nume_clasa_main
-appletviewer nume_fisier.html
-javadoc nume_fisier.java
-javap nume_fisier.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, Kawa are designed as teaching tools
Emphasis is on ease of use for beginners
Little to learn, so students can concentrate on learning Java
Eclipse, IntelliJ IDEA, 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. 2014 Eclipse version is named Luna with
support for Java SE8.
The following slides will describe Eclipse and are taken
from: www.eclipse.org/eclipse/presentation/eclipse-slides.ppt
21
22
Workbench Terminology
Tool bar
Perspective
and
Fast View
bar
Resource
Navigator
view
Stacked
views
Properties
view
Tasks
view
Outline
view
Bookmarks
view
Menu bar
Message
area
Editor
Status
area
Text
editor
23
Help Component
Help is presented in a standard web
browser
24
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
25
Java Perspective
Java-centric view of files in Java projects
Java elements meaningful for Java programmers
Java
project
package
class
field
method
Java
editor
26
Java Perspective
Browse type hierarchies
Up hierarchy to supertypes
Down hierarchy to subtypes
Type
hierarchy
Selected
types
members
27
Java Perspective
Search for Java elements
Declarations or references
Including libraries and other projects
Hits
flagged
in margin
of editor
All search
results
28
Java Editor
Hovering over identifier shows Javadoc
spec
29
Java Editor
Method completion in Java editor
List of plausible methods
Doc for method
30
Java Editor
On-the-fly spell check catches errors early
Preview
Click
to see
fixes
Problem
Quick
fixes
31
Java Editor
Code templates help with drudgery
Statement
template
Preview
32
Java Editor
Method stub insertion
for inherited methods
Method stub insertion for
anonymous inner types
Java editor creates stub methods
33
Java Editor
Variable name
suggestion
Argument hints and
proposed argument
names
JavaDoc
code assist
Java editor helps programmers write good Java code
34
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
35
Eclipse Java Debugger
Run or debug Java programs
Threads
and stack
frames
Editor with
breakpoint
marks
Console
I/O
Local variables
36
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)
NetBeans 8
-NetBeans IDE lets you quickly and easily develop Java
desktop, mobile, and web applications, as well as
HTML5 applications with HTML, JavaScript, and CSS.
-The IDE also provides a great set of tools for PHP and
C/C++ developers.
-It is free and open source and has a large community
of users and developers around the world.
Recent versions of NetBeans have included:
- first-class support for Java 8,
- best-in-class Maven support,
- full Java FX and Java EE 7 support
- and additional configurations to support technologies
like HTML 5 and JavaScript (including frameworks such
as AngularJS) as well as PHP, Groovy and C/C++.
37
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
38
-primitive data types: byte, short, int, long, char,
float, double and boolean (IEEE 754 standard for
dimensions)
-predefined constants: Double.POSITIVE_INFINITY
Double.NEGATIVE_INFINITY
Double.NAN
Double.MAX_VALUE
Double.MIN_VALUE
--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]);
String os = String.valueOf(5); String str = iObj.toString();
39
Operators: >>>right shift zero fill,
-instanceof, to verify if an object belongs to a
class
== will compare addresses for objects and
values for primitive data types (equals() method
to compare objects)
-No numerical to boolean conversions
Conversions:
-implicit, cost <10 no exception: widening (int -
> long), narrowing (int -> byte), truncation
(float -> int)
-explicit with cast operators
Comments: /* C */
//C++
/** Java */ with doc file generation
40
Useful JavaDoc Tags
@author
Specifies the author of the document
Must use javadoc author ... to generate in output
/** Description of some class ...
*
* @author <A HREF="mailto:hall@coreservlets.com">
* Marty Hall</A>
*/
@version
Version number of the document
Must use javadoc version ... to generate in output
@param
Documents a method argument
@return
Documents the return type of a method
41
Control statements:
-condition, always of boolean type
-switch( types) - types can be primitives,
enums, and (Java 7+ only) Strings
-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
42
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);
43
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
}
44
Example:
int[] numere = {1,2,3,4,5,6,7,8,9,10};
for (int element : numere) {
System.out.println("Elementul
curent: " + element);
}
45
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]);
}
}
46
//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
47
Java arrays
-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];
-init, declare and create an array: int iTab[] =new int[5];
-assign values: {e1, e2, }, by program, from other array
with arraycopy() static method from System class
-destroyed automatically by gc() method.
-length variable associated to array object:
int lengthTab=iTab.length;
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];//variable columns no.
48
Building Arrays:
One-Step Process
Examples:
int[] values = { 10, 100, 1000 };
String[] names = {"Joe", "Jane", "Juan"};
Point[] points = { new Point(0, 0),
new Point(1, 2),
new Point(3, 4) };
49
Building Arrays:
Two-Step Process
Step 1: allocate an array of references:
Type[] var = new Type[size];
E.g.:
int[] primes = new int[x]; // x is positive integer
String[] names = new String[someVariable]; // Positive int
again
Step 2: populate the array
primes[0] = 2; names[0] = "Joe";
primes[1] = 3; names[1] = "Jane";
primes[2] = 5; names[2] = "Juan";
primes[3] = 7; names[3] = "John";
etc. (or use a loop) etc. (or use a loop)
If you fail to populate an entry
Default value is 0 for numeric arrays
Default value is null for Object arrays
50
System class arraycopy()
static method
public static void arraycopy(Object src,
int srcPos,
Object dest,
int destPos,
int length)
51
Examples:
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;
52
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;

53
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
54
Example:
char[] sursa = { 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h};
char[] destinatie = new char[3];
System.arraycopy(sursa, 2,
destinatie, 0, 3);
55
Java Strings
String, constant string
StringBuffer, variable strings
StringBuilder, optimized for multithreading
StringTokenizer, extract tokens
A Java string is an object and may be considered as an array of
characters represented in Unicode (7.0) with no \0 as end
character as in C/C++
A lot of specific methods for each class exist (see lab.) as:
contains(), startsWith(), endsWith(), indexOf(), substring(),
split(), replace(),replaceAll(), toUpperCase(), toLowerCase(),
equalsIgnoreCase(), trim(),isEmpty(), etc. (regular methods)
The dimension is determined with length() method
56
String s1 = new String(abc);//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.
57
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));
}
}

58
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());
}//while
}//main
}//class
59
Common String Error:
Comparing with ==
public static void main(String[] args) {
String match = "Test";
if (args.length == 0) {
System.out.println("No args");
} else if (args[0] == match) {
System.out.println("Match");
} else {
System.out.println("No match");
}
}
Prints "No match" for all inputs
Fix:
if (args[0].equals(match))
60
Java 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);
-unlimited precision libraries:BigInteger,
BigDecimal
Contain basic math operations like add(), pow(), mod(),
etc.
BigInteger also has isPrime()
-command line arguments: no application name
as first parameter
-varargs parameters: from JSE5
61
Basic Mathematical
Routines
Simple math routines use builtin operators
+, -, *, /, ^, %
Be careful with / on int and long variables (rounds off)
Static methods in the Math class
So you call Math.cos(...), Math.random(), etc.
Most operate on double precision floating point numbers
Simple operations: Math.pow(), etc.
pow (xy), sqrt (x), cbrt, exp (ex), log (loge), log10
Trigonometric functions: Math.sin(), etc.
sin, cos, tan, asin, acos, atan
Args are in radians, not degrees, (see toDegrees() and toRadians())
Rounding and comparison: Math.round(), etc.
round/rint, floor, ceiling, abs, min, max
Random numbers: Math.random()
random (Math.random() returns from 0 inclusive to 1 exclusive).
See Random class for more control over randomization.
62
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
63
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;
}
64
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.
65
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
66
Pointers
no pointers
references
no parameters transferred by pointers
no pointers to methods
un-instantiated variable of Object class to
define an array of references to methods
67
Classes and methods in C++
and Java
-In Java the general class form is:
[lista_modificatori] class idClasa [extends
idClasaBaza] [implements lista_ interface]
{
body
}
All methods use the run-time, not compile-time,
types (i.e. all Java methods are like C++ virtual
methods)
The types of all objects are known at run-time
All objects are allocated on the heap (always
safe to return objects from methods)
Single inheritance only (Java8 multiple with
interfaces)
68
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 (in Java8
exists as keyword)
69
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
}
}
70
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
}
}
71
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
}
}

72
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 statice din clasa
}
73
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);
}
}
74
Explicit this parameter
class MyClass{
int x;
void mutator(int x){
this.x = x; //ar fi fost non-sens
//expresia x = x;
}
}
75
class MyClass{
int x;
//primul constructor
MyClass(int valoare_noua){
x = valoare_noua;
}
//al doilea constructor
MyClass(){
this(0); //apelul primului constructor
}
}
76
Accessing instance vars in same class
Call methods from the same class directly
(no variable name and dot in front)
move();
double d = degreesToRadians();
For local methods, you can use a variable
name if you want, and Java automatically
defines one called this for that purpose.
77
Declaring Variables in
Methods
Format
When you declare a local variable inside of a
method, the normal declaration syntax looks like:
Type varName = value;
The value part can be:
A constant
Another variable
A method call
A constructor invocation (a special type of
function prefaced by new that builds an object)
Some special syntax that builds an object without
explicitly calling a constructor (e.g., strings)
78
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
79
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.
80
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();
81
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).
82
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();
83
Abstract classes
abstract class NumeClasa{
public abstract void metodaAbstracta();
public void metodaNormala(){
//implementarea metodei
}
}
84
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.
85

Das könnte Ihnen auch gefallen