Modernās Programmēšanas Tehnoloģijas (Advanced Programming Technologies) with JAVA

ninetimesdissemblingSoftware and s/w Development

Nov 10, 2012 (4 years and 8 months ago)

435 views

Modernās Programmēšanas Tehnoloģijas


(Advanced Programming Technologies
)

Edgars Celms,
Mārtiņš Opmanis

(askola@mii.lu.lv)

Latvijas Universitātes

Matemātikas un informātikas institūts

200
7,

Rīga, Latvija

Ievads valodā JAVA I



Java™ How to Program, Sixth Edition



Chapter 1. Introduction to Computers, the Internet and the World
Wide Web
.


Chapter 2. Introduction to Java Applications.


Valoda JAVA


Java


universāla
programmēšanas valoda
.


valoda,
kurā

var
uzrakstīt
dažāda “līmeņa” lietojumus


Java 2 Platform, Standard Edition (J2SE)


Java 2 Platform, Enterprise Edition (J2EE)


large
-
scale, distributed networking applications and Web
-
based applications


Java 2 Platform, Micro Edition (J2ME)


developing applications for small, memory
-
constrained
devices, such as cell phones, pagers and PDAs


Raksti vienreiz, izpildi visur (
WORA



Write Once, Run
Anywhere
).


Valoda Java tiek pastāvīgi papildināta ar jaunām
iespējām.

Valodas JAVA vēsture I


1991


Sun Microsystems (James Gosling)


Codename

Green



first time called “Oak”


Originally developed for intelligent consumer
-
electronic products
such as


set top box
es,
Microwave
s
, TV, etc.


1993


WWW exploded in popularity


Widely used with dynamic content (interactivity & animations)


Current


used for


Develop large scale enterprise applications


Enhance WWW server functionality


Provide applications for consumer devices


Cellular phone, Palm, Personal Game, etc.

Valodas JAVA vēsture II

(www.wikipedia.com)


JDK
1.0

(1996)


Initial release. 212 classes, 8 packages.


JDK
1.1

(1997)


Major additions, most notably the extensive
retooling of the event model, as well as the introduction of inner
classes. 504 classes, 23 packages.


J2SE 1.2

(December 4, 1998)


Codename
Playground
. Major
changes were made to the API (reflection was introduced, the Swing
graphical API was integrated into the core classes, Collections API,
etc) and to Sun's JVM (which was equipped with a JIT compiler).
These had little impact on the language itself, however: the only
change to the Java language was the addition of the keyword
strictfp
. This and subsequent releases were rebranded "Java 2",
but this had no effect on any software version numbers. 1520
classes, 59 packages.

Valodas JAVA vēsture III


J2SE 1.3

(May 8, 2000)


Codename
Kestrel
.



The most notable changes were: HotSpot JVM
, Remote Method
Invocation (
RMI
)

was changed to be based on CORBA
, RMI/IIOP,
Java Naming and Directory Interface (JNDI), Java Sound, etc



1842
classes,
76

packages.


J2SE 1.4

(February 13, 2002)


Codename
Merlin
. As of
2004, the most widely used version.


The most notable changes were: low
-
level I/O API, regular
expressions (modeled after Perl regular expressions), logging,
user preferences, XML
-
based persistence, DOM and SAX for
XML parsing, SSL, security and cryptography extensions (JCE,
JSSE, JAAS) were integrated into J2SE, image reading/writing,
drag
-
and
-
drop for Swing,
assert

keyword, etc


2991 classes, 135 packages.


Valodas JAVA vēsture IV


J2SE 5.0

(September 29, 2004)


Codename
Tiger
. (Originally
numbered 1.5, which is still used as the internal version number.)
Added a number of significant new language features:


Generics


Provides compile
-
time type safety for collections and
eliminates the need for most typecasts.


Autoboxing/unboxing


Automatic conversions between primitive types
(such as
int
) and wrapper types (such as
Integer
).


Metadata


also called Annotations, allows language constructs such as
classes and methods to be tagged with additional data, which can then
be processed by metadata
-
aware utilities


Enumerations


the
enum

keyword creates a typesafe, ordered list of
values (such as
Day.monday, Day.tuesday
, etc.). Previously this
could only be achieved by non
-
typesafe constant integers or manually
constructed classes (typesafe enum pattern).


Enhanced for loop


the for loop syntax is extended with special syntax
for iterating over each member of an array or Collection.


>3000 classes

Valodas JAVA vēsture V


Java SE 6

(
December

11
, 200
6
)


Codename
Mustang
. As of this
version, Sun replaced the name "J2SE" with Java SE and dropped
the ".0" from the version number.


Web Services support in Java SE 6 (before it was partia
l
ly available only
in Java EE)

Valodas JAVA vēsture VII


Java SE 6
(December 11, 2006)


Scripting facilities in SE 6


Developer APIs to allow mixing of scripting code with your Java application


A collection of scripting engines at
scripting.dev.java.net

that you can
use with Java SE 6


The
Rhino JavaScript

engine in Java SE 6


Database Development

facilities


More Desktop APIs


Monitoring and Management
facilities

Valodas JAVA vēsture VIII


Java SE 6
(December 11, 2006)


Compiler Access


Pluggable Annotations






Java SE 7



Codename
Dolphin
. Project started up in August 2006,
with release estimated in 2008.


J2SE 5.0 platforma


Version 1.5.0 or 5.0


Both version numbers "1.5.0" and "5.0" are used to identify this release
of the Java 2 Platform Standard Edition. Version "5.0" is the product
version, while "1.5.0" is the developer version. The number "5.0" is used
to better reflect the level of maturity, stability, scalability and security of
the J2SE.


The number "5.0" was arrived at by dropping the leading "1." from
"1.5.0". Where you might have expected to see 1.5.0, it is now 5.0 (and
where it was 1.5, it is now 5).



J2SE 5.0 platforma

Java™ Platform, Standard Edition 6


Java™ SE 6, Platform Name and Version Numbers


At this release, the platform name has changed from
J2SE


to
Java


SE
. The
official name is
Java


Platform, Standard Edition 6
.


Both version numbers (1.6.0 and 6) are used to identify this release of the Java
Platform. Version 6 is the product version, while 1.6.0 is the developer version.
The number 6 is used to reflect the evolving level of maturity, stability, scalability
and security of Java SE.



Version 6 Used in Platform and Product Names









Due to significant popularity within the Java developer community, "JDK"
continues to be the acronym for the development kit, as does "JRE" for the
runtime environment. Notice that "JDK" stands for "Java SE Development Kit" (to
distinguish it from the Java EE Development Kit known as SDK). The name "Java
Development Kit" is no longer used, and has not been offically used since 1.1,
prior to the advent of Java EE and Java ME.


Java™ Platform, Standard Edition 6

JDK

JRE

Java SE

API

Javas klašu bibliotēka


Tiek saukta par
Java APIs

(
Application Programming Interfaces
)


Liela klašu kolekcija


Divas būtiskas lietas, kuras ir jāapgūst mācoties valodu Java


Valoda
Java


Javas klašu bibliotēkas lietošana

(
http://java.sun.com/javase/6/docs/api/
)


Vienu un to pašu var noprogrammēt daudzos dažādos veidos


padoms programmētājiem


rakstiet pēc iespējas vienkāršākas programmas (“KIS


keep it simple”)


izmantojiet standarta risinājumus

C++ un daudzu citu kompilējamu valodu
izpildes veids

Compiler For Windows PC

Your Program


If x = 5 then…

1011 0011

PC with Windows

Compiler For Mac

0011 1111

Mac

Source Code

Javas virtuālā mašīna (Java Virtual Machine)

Java Compiler

Your Program


If x = 5 then…

1011 0011

PC with Windows

ByteCode

Windows JVM

Mac JVM

0011 1111

Mac

Source Code

Tipiska Javas izstrādes vide

Edit

Edit & Store a file

-

Extension
. java

Compile

Creates bytecodes &

Stores a file

-

Extension
.class

Load

Class loader

-
put
.
c
lass

file

i
n memory

Verify

Verify bytecodes &

Validate for Java’s

security violations

Translate bytecodes into a machine language

Execute the program


-

display or store data values

Tipiska Javas
izstrādes vide


Bilde no



Java™ How to
Program, Sixth Edition
”.
H.

M.

Deitel
-


Deitel &
Associates, Inc., P.

J.

Deitel
-


Deitel & Associates, Inc.


Java SE 6 instalēšana


Java SE 6


http://java.sun.com/javase/downloads/index.jsp


Vajag lejuplādēt to kas ir atrodams pie (03.09.2007):









Turpat var lejuplādēt arī “
JDK 6 Update 2 with NetBeans 5.5.1
”, tad jums papildus būs pieejama arī IDE
programmēšanai Javā (
NetBeans 5.
5.1)


Java SE 6 instalācijas pamācība


http://java.sun.com/javase/6/webnotes/install/index.html


Skatīt arī “
Installing the J2SE Development Kit (JDK)
” no
“Java™ How to Program, Sixth Edition”


Paskatīties kāda Javas versija atrodas uz jūsu datora


To var izdarīt no komandrindas


java
-
version

Java SE 6 instalēšana

Programmēšanas valoda Java


Ļooooti daudz informācija par Javu ir atrodama tīmeklī


Java SE 6


http://java.sun.com/javase/downloads/index.jsp


Java SE 6



http://java.sun.com/javase/6/webnotes/install/index.html


Dažādi mācību līdzekļi (
tutorials
)


http://java.sun.com/docs/books/tutorial/index.html


Tutorials

var arī lejuplādēt


http://java.sun.com/docs/books/tutorial/information/download.html


Javas oficiālā dokumentācija


http://java.sun.com/javase/6/docs/



Dokumentāciju var arī lejuplādēt (apt. 52Mb)


http://java.sun.com/javase/downloads/index.jsp



Java SE 6 iekļauto rīku apraksts


http://java.sun.com/javase/6/docs/technotes/tools/index.html


Javas klašu bibliotēkas lietošana



http://java.sun.com/javase/6/docs/api/index.html


Ir pieejami arī Java SE 6 izejas teksti


...


Kursam nepieciešamā literatūra ir atrodama uz studentu ftp servera
“OOP” mapē.

Pirmā programma valodā JAVA



Java™ How to Program, Sixth Edition



Chapter 1. Introduction to Computers, the Internet and the World
Wide Web
.


Chapter 2. Introduction to Java Applications.



Pirmā programma valodā JAVA


Java
s

lietojumprogramma (
a
pplication
)


Datorprogramma, kura tiek izpildīta tad, kad jūs lietojat
java

komandu lai startētu javas virtuālo mašīnu (
Java Virtual Machine
(JVM)
)


Piemēra programma


Attēlo tekstu


Ilustrē dažas svarīgas Javas valodas īpašības

Valodas JAVA sintakses elementi


Komentāri

(
Comments
)


Single
-
line comments: // …


Multiple
-
line comments: /* … */


Javadoc comments: /** … */


Programmas bloki

(
Program Blocks
)



{ … statement; statement; … }


Atslēgvārdi

(
Keywords: reserved words for the Java
language
)


All lowercase letters


e.g.,
class, public, static, void, int, new
, …
[Appendix C]

Valodas JAVA sintakses elementi


Identifikatori

(
Identifiers: names of classes, methods,
variables, etc.
)


Sastāv no burtiem, cipariem
,
pasvītrojuma
(
_

)

un
dol
āra zīmes

(
$
)


Nevar sākties ar ciparu


Nesatur tukšumus



Lielie un mazie burti ir atšķirīgi (
Case sensitive
)


Piemēram,

ATM, atmNumber, atm_number, _val1,
$val2

Valodas JAVA komentāru piemēri



Single line and end

of

line comments


//

Test printing program


public class Welcome1

//

class declaration




Multiple
-
line comment


/*

This class is a fundamental programming
class with Java for beginners
*/




Javadoc comment


/**

This comment will be used by
javadoc utility program to document
the program in HTML format
*/


Vairāk par javadoc skat.:

http://java.sun.com.j2se/javadoc

Valodas JAVA atslēgvārdi

Laba programmēšanas prakse I

(
Good Programming Practice
)


Begin with a comment including the purpose of the program, the
author and the date and time the program was last modified.


Program change and version control


Use blank lines and space characters to enhance program
readability.


Also ignored by the compiler


Begin a class name’s identifier with a capital letter and start each
subsequent word in the identifier with a capital letter.


Valid
Identifiers


start with letter, $ , or _
-

Welcome1, $value,
_accountNo


Non
-
Valid

Identifier


start with numbers


e.g.
7button, 0121class


Java is case sensitive


edgarsCelms

and
EdgarsCelms

are different identifiers


Use proper upper and lower case letters

Laba programmēšanas prakse II

(
Good Programming Practice
)


Whenever opening a left brace, immediately put the matching right
brace


Prevent an error by missing braces


Indent the entire body of each class declaration one level of
indentation b/w the left braces


Set a convention for the indent size in the editor you are using


Tab key for indentation

Populārākās iesācēju kļūdas I

(
Common Programming Error
)


Class name and File name are mismatch


In terms of spelling and capitalization


Not to end a file name with
.java

extension for a file containing a
class declaration


A syntax error if braces does not occur in matching pairs


Left brace { and match with right brace }


Omitting the semicolon at the end of a statement

main

metode


Starta (ieejas) punkts visām Javas lietojumprogrammām


Iekavas aiz
main

norāda, ka tā ir metode


Aplikācijai ir jābūt tieši vienai
main

metodei


static

metod
e



veic darbības, kuras nav atkarīgas no objekta
(klases instances) stāvokļa (tiek sauktas arī par klases metodēm)


void



beidzot darbu neatgriež nekādus datus


String args[]



argument
u saraksts

public static void main (String args[])

Programmas instrukcijas


Programmas instrukcijas liek datoram kaut ko darīt


System.out



sistēmas standarta izvades objekts


Attēlo simbolu virkni (sauktu arī par
string, message, string literal
)
komandu logā
(
prompt in Windows, shell or terminal window in Unix,
Linux, MacOS
)
.


System.out.println



Attēlo doto argumentu komandu logā un novieto kursoru nākamās rindas
sākumā


Semikols (
;
)


Katra programmas instrukcija beidzas ar semikolu


Tikai ; (bez programmas instrukcijas)
-
> nekāda darbība


Semikola neesamība instrukcijas beigās
-
> sintakses kļūda

System.out.println (“Welcome to Java Programming !”);

Kompilēšana un izpilde


Saglabājiet programmas tekstu datnē ar papalšinājumu
.java


Nomainiet aktīvo mapi uz to kur datne tika saglabāta


C:> cd C:
\
APT
\
examples


Kompilēšana


C:
\
APT
\
examples>javac Welcome1.java


Kompilācijas kļūdas ir jāizlabo pirms izpildes


Izpilde


C:
\
APT
\
examples>java Welcome1


Launches JVM


JVM loads
.class

file for class
Welcome1


.class

extension omitted from command


JVM calls method
main

Izpildes rezultāts

Daži komentāri par iespējamām kļūdām I


Compiler errors such as:


“bad command or filename”


“javac: command not found”



“'javac' is not recognized as an internal or external command, operable
program or batch file”


The system’s PATH environment variable may not set properly. Please
review the J2SE Development Kit installation instructions at
java.sun.com/j2se/5.0/install.html.

After correcting the PATH, you may need to reboot your computer for
these settings to take effect.

Daži komentāri par iespējamām kļūdām II


The compiler error message:


“Public class ClassName must be defined in a file called
ClassName.java”

F
ile name does not exactly match the name of the public class in the
file or the class name was incorrect when compiling the class.



When attempting to run a Java program, if you receive a message
such as:


“Exception in thread "main" java.lang.NoClassDefFoundError:
Welcome1”

Y
our CLASSPATH environment variable has not been set properly. On
some systems, you may need to reboot your computer after
c
onfiguring the CLASSPATH.


print

vs.
println



print

method does not move the cursor at the beginning of the
next line after performing the task


Not economical if you use multiple statements to do the same task,
which can be done with a single statement

Java Escape Sequences

Escape
sequence

Description

\
n

Newline. Position the screen cursor at the beginning of the next line.

\
t

Horizontal tab. Move the screen cursor to the next tab stop.

\
r

Carriage return. Position the screen cursor at the beginning of the
current line

do
not advance to the next line. Any characters output
after the carriage return overwrite the characters previously output
on that line.

\
\

Backslash. Used to print a backslash character.

\
"

Double quote. Used to print a double
-
quote character. For example
,

System.out.println(
"
\
"in quotes
\
""
);

displays

"in quotes"


Display multiple lines with a single statement

Escape Character:

-

a special meaning in a
sequence of characters

Welcome

to

Java

Programming

Formatizēta datu izvade ar
printf


System.out.printf


Formatizēta datu izvade (ļoti populāra lieta C valodā!!!)


Tika ieviesta tikai J2SE 5.0


Formatēšanas specifikators


sākas ar
%
, kam seko simbols (nosaka
izvadāmo tipu)


%s



pasakam, ka gribam izvadīt simbolu virkni


Izvadāmie argumenti tiek atdalīti ar komatiem

Welcome to

Java Programming

“Otrā” Javas lietojumprogramma


Javas lietojumprogramma divu skaitļu ievadīšanai un to
summas attēlošanai


Scanner

klases lietojums datu ievadei


printf

lietojums, lai attēlotu divu skaitļu summu


pakotņu (
package
) lietojums valodā Java

Divu veselu skaitļu saskaitīšana



Range of
int

-
2,147,483,648 to +2,147,483,647

Standard Input

System.out

class

-

A part of package
java.lang

(
java.lang

is the only package
in the Java API that does not
require an import declaration
)

Declare variables

Standard Input


(Command Window)

Populārākās iesācēju kļūdas II

(
Common Programming Error
)


All
import

declarations must appear before the first
class declaration in the file.


Placing an
import

declaration inside a class
declaration’s body or after a class declaration is a syntax
error.


Forgetting to include an
import

declaration for a class
used in your program typically results in a compilation
error containing a message such as
“cannot resolve
symbol.”



C
heck that you provided the proper
import

declarations.

Laba programmēšanas prakse III

(
Good Programming Practice
)


Declare each variable on a separate line with descriptive
comment


Choosing meaningful variable names helps a program to
be
self
-
documenting


Variable
-
name identifiers begin with a lowercase letter,
and every word in the name after the first word begins
with a capital letter


e.g.:
firstName

Aritmētiskie operatori valodā JAVA


Integer division truncates remainder


7 / 5 evaluates to 1


Remainder operator % returns the remainder


7 % 5 evaluates to 2

Java
operation

Arithmetic
operator

Algebraic
expression

Java
expression

Addition

+

f
+ 7

f + 7

Subtraction



p



c

p
-
c

Multiplication

*

B
m

b * m

Division

/

x
/
y

or



or

x

÷

y


x / y


Operatoru izpildes secība valodā JAVA


Some arithmetic operators act before others (i.e.,
multiplication before addition)


Use parenthesis for complex arithmetic expressions


Example: Find the average of three variables
a
,
b

and
c


Do not use:
a + b + c / 3


Use:
( a + b + c ) / 3

Operator(s)

Operation(s)

Order of evaluation
(precedence)

*

/

%

Multiplication

Division

Remainder

Evaluated first. If there are
several operators of this type,
they are evaluated from left to
right.

+

-

Addition

Subtraction

Evaluated next. If there are

several operators of this type,
they are evaluated from left to
right.


Vienādības (
equality
) un relāciju (
relational
)
operatori valodā JAVA


Nosacījums


Izteikmse kuras rezultāts ir vai nu patiess (
true
), vai nu aplams (
false
)


if
instrukcija (
statement
)


Piemērā būs vienkāršākais
if

variants (par pārējo vēlāk

)


Ja nosacījums
if

instrukcijā ir
true
,
tad
if
instrukcijas ķermenis (
body
) tiek
izpildīts


Nosacījumus

if

instrukcijās var veidot lietojot v
ien
ā
d
ī
bas
,

rel
ā
ciju
un loģiskos
(
conditional
) (par tiem arī vēlāk

)

operator
us


Standard algebraic

equality or relational
operator

Java equality

or relational
operator

Sample
Java
condition


Meaning of

Java condition

Equality operators






==

x == y

x
is equal to
y



!=

x != y

x
is not equal to
y

Relational operators






>

x
> y

x
is greater than
y



<

x < y

x
is less than
y



>=

x >= y

x
is greater than or equal to
y




<=

x <= y

x
is less than or equal to
y


Piemērs: salīdzināšana

Operatoru associativitāte valodā JAVA

Operators

Associativity

Type

* / %

left to right

multiplicative

+
-

left to right

additive

< <= > >=

left to right

relational

== !=

left to right

equality

=

right to left

assignment


Populārākās iesācēju kļūdas III

(
Common Programming Error
)


Forgetting parenthesis in an if
-
statement


Confusion b/w equality operator

(
==
) and assignment operator (
=
)


Contain spaces b/w their symbols


= =, ! = , > =

, etc.


Reversing the operators


=!, =>, =<


Put a semicolon right after the right parenthesis after an
if statement


i
f (int1 == int2) ;


No action if the statement is true


logical error

Laba programmēšanas prakse IV

(
Good Programming Practice
)


A lengthy statement can be spread over several lines. If
a single statement must be split across lines, choose
breaking points that make sense, such as after a comma
in a comma
-
separated list, or after an operator in a
lengthy expression. If a statement is split across two or
more lines, indent all subsequent lines until the end of
the statement.


Refer to the operator precedence chart (see the
complete chart in Appendix A) when writing expressions
containing many operators.


Operatoru prioritātes secība (pilns saraksts)

Jautājumi ?