programming in java java...
TRANSCRIPT
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java
Programming in Java
Java Fundamentals
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Five Common Programming Language Paradigms
� Imperative Languages(perhaps better know as "Procedural Languages"):
Pascal, FORTRAN, COBOL, C, Perl
� Functional Languages(sometimes called "Applicative Languages"):
LISP, Scheme, FP, ML
� Logic Languages(including the set of "Declarative Languages"):
Prolog
� Object-Oriented Languages:Simula, Smalltalk, Java, C++, Ada
� Special Purpose Languages(Problem-Oriented Languages):
Linda, parallel versions of FORTRAN, STRUDL, PANIC,
CIRCUIT, Mathematica, Excel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Tower of Babel
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
OOP-Development
Object-Oriented Programming
• 1967:Simula - O.J. Dahl Class and Instance
• 1972:Parnas Module - D. Parnas Information hiding
Smalltalk72 - Xerox PARC
• 1974:CLU - B. Liskov abstract data type – ADT
• 1981:Smalltalk80 - Xerox class library
• 1986:Objective-C - Cox,
C++ by Bjarne Stroustrup
• 1988:Eiffel - B. Meyer
• 1989:CLOS – Moon
• Today: Java, C++, C#
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Software Life Cycle
Software engineering life
cycle model for the
object oriented paradigm
Requirements Analysis and Specification
System Analysis and Design (Narrative, Class Diagrams)
Software Design(Tables, Nassi Shneiderman Charts)
Class Implementation
(Java) Application Implementation
(Java)
Unit Testing
System Testing
Maintenance
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Software Development - Waterfall Model
Upstream: What activities
Downstream: How AcitivitiesRequirements
Analysis
Specification
High Level Design
Low Level Design
Coding
Testing
Maintenance
The Standard Waterfall Model for System Development
Coding
Software Life Cycle
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Software Development - Waterfall Model
Upstream: What activities
Downstream: How AcitivitiesRequirements
Analysis
Specification
High Level Design
Low Level Design
Coding
Testing
Maintenance
The Iterative Waterfall Model for System Development
Coding
Software Life Cycle
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Software Development - V-Model
The V-Model (Standard of German Federal Armed Forces)
analyse
and
design
test
and
integrate
system
requirements
software
requirements
preliminary
design
detailed
design
code and
debug
system
integration
acceptance
test
software
integration
component
test
unit testKBSt
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Software Development – Spiral Model
1.Objectives,
Alternatives,
Constraints
2.Risk Analysis
& Aversion
3.Product
Development
4.Planning
& Management
Developed at TRW
by
Barry W. Boehm
(1988)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Ref.: Dr. Jody Paul
Typical Cycle of the Spiral
• Identification of
- objectives (of the portion of the product being elaborated)
- alternative means of implementing this portion of the product (design
A, design B, buy)
- constraints imposed on the application of the alternatives (cost,
schedule, copyright)
• Evaluate the alternatives relative to the objectives and constraints
- Identify areas of uncertainty that are significant sources of risk
- Evaluate the risks (e.g., by prototyping, simulation, benchmarking)
• The next step is determined by the relative remaining risks. Each level of
software specification and development is followed by a validation step.
• Each cycle is completed by the preparation of plans for the next cycle and
a review involving the primary people or organizations concerned with the
product. The review's major objective is to ensure that all concerned
parties are mutually committed to the approach for the next phase
Software Development – Spiral Model
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 1
(Poet) Lord Byron wrote:
Is your face like thy mother's, my fair child!
Ada! sole daughter of my house and heart?
The first computer programmer:
Augusta Ada Byron,
Countess of Lovelace
(Lady Lovelace)
(1815 - 1852)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 2
Charles Babbage
(1791 – 1871)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 3
Babbage's Difference Engine No. 1
(1832)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 4
Reconstructed Difference Engine
(built in 1991)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 5
Henry Babbage's
Analytical Engine Mill
(1910)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 6
Reconstructed Analytical Engine
(built in 1991)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 7
Babbage's Analytical Engine (1834-1871)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 8
Babbage's Analytical Engine (built in 1991)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 9
"Neutralising Cams for Number"
Part of the Analytical Engine,
drawn by Babbage.
Ref.: Computers and Computation, W.H. Freeman and Company, 1971
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 10
Lego Difference Engine
(built in 1991)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Computer History 11
Early program written for Charles Babbage's "Analytical Engine" by Lady
Lovelace.
She wrote the program, which was for computing the number series known
as Bernoulli numbers, to show what the engine could do.
Published in 1840 in Taylor's Scientific Memoirs.
Ref.: Computers and Computation, W.H. Freeman and Company, 1971
Lady Lovelace's Program
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming
Programming in Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming
Programming Languages and Compilers:
High-Level Languages
Low-Level Languages
Examples:
Fortran, Pascal, C, C++, Java
Assembly Language
Compiler
Interpreter
Machine Language
(Machine Code)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming
Program Development:
Programming Languages and Translation
Compiler:
• A program that translates a high-level language
program into a low-level program (machine
language) that can be executed on a computer
(CPU, microprocessor).
Interpreter:
• A program that translates program
statements into machine language one line at
a time as the program is running.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming
Elements of Java:
• Java Programming Language
• Java Virtual machine
• Java Application Programming Interface (API)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Environments
JavaSource(.java)
Compile-timeEnvironment
JavaCompiler
JavaBytecode(.class)
Run-Time Environment(Java Platform)
JavaInterpreter
Just-in-TimeCompiler
Run-Time System
Operating System
Hardware
Class LoaderByte Code Verifier
Java ClassesLibraries
VirtualJava Machine
VM
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Possible Java Implementations
Java VM
Browser
OS
Hardware
Java VM
OS
Hardware
Java VM
OS
Hardware
Java VM
Interf.
Hardware
Java OS
JavaChip
Java Base API
Java Base Classes
Java Standard Extension API
Java Standard Ext. Classes
Applets und Applications
Java onJavaChip
Java underJavaOS
Java ina Browser
Java on aDesktop OS
Java on asmall OS
Java
embedded
API
Interf. Interf.Interf.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
JDK Programming Environment
Java VM
Source
Program
Bytecode
Program Execution
javac <name>.java
java <name>
Compiler
Interpreter
<name>.java
<name>.class
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Byte-Code
Comparison: Java vs. C#
Both, C# and Java compile to an intermediate language:
Java ���� Java byte-code
abstract machine: Java Virtual Machine (JVM)
C# ���� Microsoft Intermediate Language (MSIL)
abstract machine:
Common Language Runtime (CLR)
In each case the intermediate language (IL) can be run - by
interpretation or just-in-time compilation - on an appropriate
'virtual machine'.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structures
Java File Structure
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java File Structure
jdk1.5.0
bin
java.exe
javac.exe
javap.exe
javah.exe
javadoc.exe
lib
tools.jar
dt.jar
jre
bin
java.exe
java.dll
awt.dll
client
jvm.dll
server
jvm.dll
rt.jar
charsets.jarext security applet
lib
Directories and Development FilesFiles and directories that are required to develop applications for
the Java platform (example: jdk1.5.0).
localedata.jar
fonts
Ref.:
http://java.sun.com/j2se/1.5.0/docs/tooldocs/windows/jdkfiles.html
executable files for the
development tools
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming
Java Basics
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Java Language
� simple
� object-oriented
� distributed
� robust
� secure
� architecture neutral
� portable
� interpreted
� high-performance
� multithreaded
� dynamic
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Language Comparison
HighHighLowLowLowMediumHighPerformance
�������Exceptions
�������Threads
�������Neutral
�������Portable
�������Dynamic
�������Interpreted
�������Secure
�������Robust
�������O-O
�������Simple
C++CShellsPerlTCLSmall
Talk
Java
Feature doesn’t exist�Feature somewhat exists�Feature exists�
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
The properties of the Java Language:
• Simple:one of the design goals of Java was simplicity. Simplicity and removal of
many features from ist C and C++ ancestors keep Java relatively small
and reduce the programmer's burden in producing reliable applications.
The Java design team examined many aspects of the "modern" C and
C++ languages to determine features that could be eliminated in the
context of modern object-oriented programming.
Another major design goal was that Java looks familiar to a majority of
programmers in the personal computer and workstation arenas, where a
large number of system and application programmers are familiar with C
and C++.
Thus, Java "looks like" C++.
But Java omits many rarely used, poorly understood, confusing features
of C++. These omitted features primarily consist of operator overloading
and multiple inheritance. But Java has method overloading.
An added feature of Java is "garbage collection", which simplifies the
task of Java programming but makes the systems more complicated.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
A good example of a common source of complexity in many C and C++
applications is storage management: the allocation and freeing of
memory.
By virtue of having automatic garbage collection the Java language not
only makes the programming task easier, but also dramatically cuts
down on bugs.
Another aspect of being simple is being small.
One of the goals of Java was to enable the construction of software that
can run stand-alone in small machines.
Java: Basic Interpreter and class support 40 kBytes
standard Libraries and thread support: 175 kBytes
(self-contained microkernel) ----------
Total: 215 kBytes
Summary: Simple, familiar, easy to learn, small.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
• Object-Oriented:In order to follow modern software development practices, Java is
object-oriented from the ground up.
As an object-oriented language, Java draws on the best concepts and
features of previous object-oriented languages, primarily Eiffel,
Smalltalk, Objective C, and C++.
Software-oriented design is very powerful because it facilitates the clean
definition of interfaces and makes it possible to provide reusable
"software ICs".
Simply stated, object-oriented design is a technique that focuses design
on data (= objects) and on the interfaces to it. To make an analogy with
carpentry, an "object-oriented" carpenter would be mostly concerned
with the chair he was building, and secondarily with the tools used to
make it; a "non-object-oriented" carpenter would think primarily of his
tools.
Object-oriented design is also the mechanism for defining how modules
"plug and play".
Java goes beyond C++ in both extending the object model and removing
the major complexities of C++. With the exception of its primitive data
types, everything in Java is an object, and even the primitive types can
be encapsulated within objects if the need arises. Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
Source: Sun Microsystems
To be truly "object-oriented", a programming language should support at
a minimum four characteristics:
- Encapsulation:
implements information hiding and modularity (abstraction).
- Polymorphism:
the same message sent to different objects results in behaviour that's
dependent on the nature of the object receiving the message.
- Inheritance:
new classes and behaviour are defined based on existing classes to
obtain code re-use and code organization.
- Dynamic binding:
objects could come from anywhere, possibly across the network. You
need to be able to send messages to objects without having to know
their specific type at the time you write your code.
Dynamic binding provides maximum flexibility while the program is
executing.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
• Distributed:Java supports network applications.
Java has an extensive library of routines for coping easily with TCP/IP
protocols like HTTP and FTP. Java applications can open and access
objects across the net via URLs with the same ease that programmers
are used to when accessing a local file system.
• Robust:Java is intended for writing programs that must be reliable in a variety of
ways.
Java puts a lot of emphasis on early checking for possible problems,
later dynamic (runtime) checking, and eliminating situations that are
error prone.
One of the advantages of a strongly typed language (like C++) is that it
allows extensive compile-time checking so bugs can be found early (but,
C++ inherits loopholes from C).
In Java declarations are required, implicit C-style declarations are not
supported.
The linker understands the type system and repeats many of the type
checks done by the compiler to guard against version mismatch
problems.Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
Source: Sun Microsystems
The single biggest difference between Java and C/C++ is that Java has a
pointer model that eliminates the possibility of overwriting memory and
corrupting data. Instead of pointer arithmetic, Java has true arrays. This
allows subscript checking to be performed. In addition, it is not possible
to turn an arbitrary integer into a pointer by casting.
Java does not make the QA (quality assurance) problem go away, it does
make is significantly easier.
Very dynamic languages like LISP, TCL and Smalltalk are often used for
prototyping. One of the reasons for their success is that they are very
robust: you don't have to worry about freeing or corrupting memory.
Programmers can be relativley fearless about dealing with memory
because they don't have to worry about it getting corrupted.
Java has this property.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
• Secure:Java is intended to be used in networked/distributed environments.
Therefore a lot of emphasis has been placed on security.
Java has security features designed into the language and run-time
system, that allow you to construct applications that can't be invaded
from outside (development of virus-free, tamper-free systems).
There is a strong interplay between "robust" and "secure". For example,
the changes to the semantics of pointers make it impossible for
applications to forge access to data structures or to access private data
in objects that they don't have access to.
• Architecture Neutral:Java was designed to support applications on networks. In general,
networks are composed of a variety of systems with a variety of CPU and
operating system architectures.
To enable a Java application to execute anywhere on the network, the
compiler generates so-called bytecodes – an architecture neutral
intermediate format designed to transport code efficiently to multiple
hardware and software platforms. The generated bytecode instructions
are designed to be both easy to interpret on any machine and easily
translated into native machine code on the fly.Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
• Portable:Architecture neutrality is just one part of a truly portable system. Java
takes portability a stage further by being strict in its definition of the
basic language.
Unlike C and C++ there are no "implementation dependent" aspects of
the specification. The sizes of the basic (primitive) data types are
specified, as is the behaviour of ist arithmetic operators that act on them.
For example, "int" always means a signed two's complement 32-bit
integer, and a "float" always means a 32-bit IEEE 754 floating point
number. Making these choices is feasible because essentially all CPUs
share these characteristics.
The libraries that are part of the system define portable interfaces. For
example, there is an abstract window class and implementations of it for
Windows, UNIX, Macintosh.
• Interpreted:The Java interpreter can execute Java bytecodes directly on any machine
to which the interpreter has been ported (VM). In an interpreted
environment such as the Java system, the link phase of a program is
very simple and incremental.
Result: Faster development cycles (rapid software prototyping) versus
the traditional compile, link, and test cycles. Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
Source: Sun Microsystems
• High Performance:Usually the performance of interpreted bytecodes is more than adequate.
In case that higher performance is required, the bytecodes can be
translated on the fly (at runtime, just in time) into machine code for the
particular CPU the application is running on.
For those accustomed to the normal design of a compiler and dynamic
loader, this is somewhat like putting the final machine code generator in
the dynamic loader.
The bytecode format was designed with generating machine codes in
mind, so the actual process of generating machine code is generally
simple.
The performance of bytecodes converted to machine code is almost
indistinguishable from native C or C++.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
Source: Sun Microsystems
• Multithreaded:Multithreading is a way of building applications with multiple threads.
Unfortunately, writing programs that deal with many things happening at
once can be much more difficult than writing in the conventional single-
threaded C and C++ style.
Java has a sophisticated set of synchronization primitives that are based
on the widely used monitor and condition variable paradigm that was
introduced by C.A.R. Hoare.
By integrating these concepts into the language they become much
easier to use and more robust.
Much of the style of this integration came from Xerox's Cedar/Mesa
system.
Other benefits of multithreading are better interactive responsiveness
and real-time behaviour. This is limited, however, by the underlying
platform; stand-alone Java runtime environments have good real-time
behaviour. Running on top of other systems line Unix, Windows, etc.
limits the real-time responsiveness to that of the underlying system.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Language
Source: Sun Microsystems
• Dynamic:In a number of ways, Java is a more dynamic language that C and C++. It
was designed to adapt to an evolving environment.
• While the Java compiler is strict in its compile-time static checking, the
language and run-time system are dynamic in their linking stages.
Classes are linked only as needed. New code modules can be linked in
on demand from a variety of sources, even from sources across the
network.
Java understands interfaces (concept borrowed from Objective C). An
interface, which is similar to a class, is simply a specification of a set of
methods that an object responds to.
It does not include any instance variables or implementations.
Interfaces can be multiply-inherited (unlike classes) and they can be
used in a more flexible way than the usual rigid class inheritance
structure.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming
Java Definitions and Syntax
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Syntax vs. Sematics
Syntax
refers to the ways symbols may be combined to create well-formed
sentences (or programs) in the language. Syntax defines the formal
relations between the constituents of a language (structure).
Semantics
reveals the meaning of syntactically valid strings in a language.
For programming languages, semantics describes the behavior that
a computer follows when executing a program in the language.
Pragmatics
alludes to those aspects of language that involve the users of the
language, namely psychological and sociological phenomena such
as utility, scope of application, and effects on the users. For
programming languages, pragmatics includes issues such as ease
of implementation, efficiency in application, and programming
methodology.
Formal Syntax and Semantics of Programming Languages
Kenneth Slonneger, University of Iowa
Barry L. Kurtz, Louisiana Tech University
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Operators
Java Operators:
An operator acts upon one, two or three operands.
Operands can be:
• A numeric value: integer, floating point or character
• Any primitve type variable: numeric and boolean
• Reference value to an object
• A literal: numeric value, boolean value, or string
• An array element
• "char" primitive (treated as an unsigned two byte integer)
Type of operators:
• Unary: acts on a single operand
• Binary: requires two operands
• Ternary: conditional operator (Java's only ternary operator)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Operators
assignmentRightvar x value=13
conditional operatorRightbool x all x all? :12
conditional ORLeftbool x bool||11
conditional ANDLeftbool x bool&&10
bitwise logical ORLeftbool x bool|8
bitwise logical ANDLeftbool x bool&7
reference identical, not ~LeftObject==, !=6
values equal, not equalLeftprimitive==, !=6
type checkLeftallinstanceof5
comparisonLeftnum x num<, <=, >, >=5
concatenationLeftString x String+3
Addition, SubtractionLeftnum x num+, -3
Multiplication, Division, ModuloLeftnum x num*, /, %2
signRightnumerical+, -1
in-/decrementRightnumerical++, --1
OperationAssoc.TypeOperatorPrec.
Associativitly: "Right to Left" of "Left to Right"
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Fundamental (Primitive) Data Types in Java
+/-1,79769313486231570E+308
+/-4,94065645841246544E-324
0.064double
+/-3,40282347E+38
+/-1,40239846E-45
0.032float
-9.223.372.036.854.775.808
+9.223.372.036.854.775.807
064long
-2.147-483.648
+2.147-483.647
032int
-32.768
+32.767
016short
-128
+127
08byte
\u0000
\uFFFF
016char
true
false
false1boolean
RangedefaultBitsData Type
signed
integer
floating point
IEEE 754-1985
Unicode
characters
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Floating-point Arithmetic in Java
exponentradixmantissasign ⋅⋅
Floating point IEEE 754-1985
Presentation for
32-bit floats and 64-bit doubles:
Floating-point numbers in the JVMexponent2⋅⋅mantissasign
sign mantissaexponent
1 bit 23 bits8 bits
1 bit 52 bits11 bits
float
double
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Expressions
Array{1,2,3}
current objectthis
Def. in superclasssuper
float47.11f, 47.11F
double47.11, 47.11d, 47.11D
long123l, 123L
int123
String"<string>"
char'<character>', '<ESC-Sequence>'
booleantrue, false
allnull
TypeLiterals
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Character Escape Sequences
Unicode character (d = 0-f/F)\udddd
Hexadecimal character (d = 0-f/F)\xdd
Octal character (d = 0-7)\ddd
Double quotation mark\”
Single quotation mark\’
Backslash\\
Formfeed\f
Carriage Return\r
Backspace\b
Tab\t
Newline\n
DescriptionEscape Sequence
Obs.: Java does not include\a (bell) and \v (vertical tab)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Program Structure – Control Flow
Empty Assignment: ;
Assignment: variable = expression;
Conditional Statements:if (<boolean>) {<statements>}
if (<boolean>) {<statements>} else
{<statements>}
Loops:
While:
while (<boolean>) {<statements>}
Do-While:
do {<statements>} while (<boolean>)
For:
for (<init>; <boolean>; <increment>)
{<statements>}
Edsger W. Dijkstra, Go To Statement Considered Harmful
http://www.acm.org/classics/oct95/
Java does not support a goto statement.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
OOP
Object-Oriented Programming (OOP):
Terminology
Object:A program construction that has data and actions
associated with it.
Method:Objects are performing actions that are called methods.
Class:A class declares the type of an object.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Syntax Diagrams
modifier class name body
superclass interface
Syntax diagram for class declaration
Syntax diagram for variable declaration
[ ] initializationmodifier
type name
Syntax diagram for method declaration
[ ]
modifier
methodtype name (
body
[ ]
parameters ) ;
name ( parameters )
Graphical equivalent to Backus-Naur Form (BNF)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Syntax Elements
Class Declaration:
modifier class name [extends SuperClass]
{ /** comment for documentation */
<declaration of variables> // comment
<declaration of methods> /* comment */
}
Variable Declaration:
modifier type (name [= value], ) ;
Method Declaration:
modifier type Name <parameter list>
{
<declaration of variables> (<command>);
}
Parameter List:
( ) | (type name ( , type name) )
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Operators
int A, B;
B = (A=4)/2;
Prefixed/Postfixed Increment/Decrement:
Operators: "++", "--"
Example:int A, B;
A = 1;
B = ++A; // Prefixed: A = 2, B = 2
A = 1;
B = A++; // Postfixed: A = 2, B = 1
Special Operators:
a op= b;
equivalent to:a = a op b;
Casting:byte A = 1;
byte B = 2;
A *= B; // allowed without casting!
// A = A * B is not allowed!
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Boolean (Logical) Operations
| →→→→ OR, & →→→→ AND, ^ →→→→ XOR
Example:int A, B;
if ((A > B) | btest(A)); // OR
{
...
}
Short-Circuit Evaluation:
|| →→→→ OR, && →→→→ AND, ^^ →→→→ XOR
Example:int A, B;
if ((A > B) || btest(A)); // short-circuit OR
{
...
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Ternary Operators
Syntax:
test ? trueresult : falseresult;
Example:
int smaller = x < y ? x : y;
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
A first example:
Hello World
Brian Kernighan, 1972:
Tutorial: Introduction to the Language B.
Program code:
main( ) {
extrn a, b, c;
putchar(a); putchar(b); putchar(c); putchar('!*n');
}
a 'hell';
b 'o, w';
c 'orld'; B-Tut
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
public class HelloWorld
{
public static void main (String[] args)
{
System.out.println("Hello World");
}
}
Source Code:
Source File: HelloWorld.java
Compilation: javac HelloWorld.java
Execution of the Bytecode: java HelloWorld
Path Definition: e.g. \java\bin\
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
Program Structure
Class Declaration:".java" file,
one class declared as public (defines filename).
Application:Set of classes; One public class contains method “main()”, which
will be called by the interpreter.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
HelloWorld-Application:Tradition going back to Kernighan and Ritchie
Compilation and Execution, Things to watch (basic syntax):
a) Semicolon after System.out.println("Hello World") - line
b) Bracket and braces
c) Case sensitivity (class ≠ Class)
Compiler creates: *.class – file (bytecode)
can be interpreted (VM – virtual machine)
Name fo the class-file comes from the
class HelloWorld – statement
and not from the source code filename.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
If there is more than one class in a file, then the Java compiler will
store each one in a separate .class-file.
Rules:
• Source code file should have the same name as the main class
in the file.
• Extension: *.java
• The initial class statement is very important:
can not only be called from command line but also from other
parts of the same or different program.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
The HelloWorld sample program declares a class named
HelloWorld.
Within the HelloWorld class a single method is declared called
main( ), the main method. The main method is where the program
execution begins.
public:
This method is declared public meaning that the method can be
called from anywhere.
static:
It is declared static meaning that all instances of this class share
this one method.
void:
The method is declared void meaning that is does not return a
value.
Finally any command line arguments are passed to the method in
an array of Strings called args. The HelloWorld program does not
use command line input.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
Execution:
The main( ) method is called and prints "Hello World" to the
standard output. This is accomplished by the System.out.println
method.
More precise:
The println() method is called out of the out object. The out object
is a class variable in the System class that performs output
operations on files.
System.out.println() can be treated just as one method.
Obs.:
println() appends a newline at the end of the output (no \n
necessary).
print() performs an output without newline.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
Braces and Block:
In Java a source code file is broken up into parts separated by
opening and closing braces: { }
Everything between { and } is a block and exists more or less
independently of everything outside of the braces.
Blocks are important both syntactically and logically. Without the
braces the code wouldn't compile.
���� delimiting classes and methods.
Blocks can be hierarchical.
���� HelloWorld: one outer block defines class,
inner method block defines "main".
Important: ���� Mark blocks by identation.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
Comments:
In Java there are three forms of comment:
// one line comment
/* */ multiline comment
/** */ Javadoc comment (Java only)
Javadoc:
Javadoc is a tool that parses the declarations and documentation
comments in a set of source files and produces a set of HTML
pages describing the classes, inner classes, interfaces,
constructors, methods, and fields.
Source: Sun Microsystems
HelloWorld - JavadocJavadoc
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"Hello World" - Java-Program
Data and variables:
Methods are only one part of a Java class.
The other part is data.
e.g. additional strings:
String name = "FH Kiel"
]
System.out.println(name)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Packages
Creating and Using Packages
To make types easier to find and use, to avoid naming
conflicts, and to control access, programmers bundle
groups of related types into packages.
Definition:
A package is a collection of related types providing access
protection and name space management. Note that types
refers to classes, interfaces, enums, and annotations.
The types that are part of the Java platform are members of
various packages that bundle classes by function:
fundamental classes are in java.lang, classes for reading and
writing (input and output) are in java.io, and so on.
http://java.sun.com/docs/books/tutorial/java/interpack/packages.html
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Struktogramme(Nassi-Shneiderman-Diagramme, DIN 66261)
Ben Shneiderman
Ike Nassi's Reading List:
http://www.nassi.com/reading-list.html
Ike Nassi
Executive Vice President
at SAP
Structure Elements
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements
Elementarblock/Strukturblock:
Reihung/Sequenz:
Struktogramme(Nassi-Shneiderman-Diagramme, DIN 66261)
f1
f1
f2
f3
fn
...
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements
f1 f2
f3
f2 f3
f1
allowed
not allowed
forming blocks:
f1
f2
f3
fn
...
Modul name
Modul description
Module block:
f1, f2, ..., fn = structural blocks
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - Conditionals
f1 f2
btrue false
Selektionsblöcke:
Alternative Anweisung (zweiseitige Auswahl):
b = Bedingung
f1, f2 = Strukturblöcke
f1 %
btrue false
Alternative Anweisung (einseitige Auswahl):
b = Bedingung
f1 = Strukturblock
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - Conditionals
if (condition)
{
statements
}
else
{
statements
}
f1 %
btrue false
optional
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements
fxfnf1 f2 ...
v =k1
k2
kn
else
v = Variable
f1,...,fn = Strukturblöcke
k1,...,kn = Konstanten
Fallunterscheidung (mit Fehlerausgang):
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - Switch
type var;
...
switch (var)
{
case val-1: ... ; break;
...
case val-n: ... ; break;
default: ...
}
“break” causes jump out of the switch-statement.
Without “break” the next statement will be executed.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - Loops
b = Ausführungsbedingung
f1 = Strukturblock
= Schleifenkörper
Iterationsblöcke:
Bedingungsschleife (abweisende Schleife,
kopfgesteuerte Schleife):
solange b = wahr
f1
Pre-condition test
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - Loops
b = Abbruchbedingung
f1 = Strukturblock
= Schleifenkörper
Iterationsblöcke:
Bedingungsschleife (nichtabweisende Schleife,
fußgesteuerte Schleife):
f1
bis b = wahr
Post-condition test
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - Loops
while (condition)
{
statements;
}
do
{
statements;
}
while (condition);
Pre-condition test
Post-condition test
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - Loops
sv = Schleifenvariable
aw = Anfangswert
ew = Endwert
sw = Schrittweite
(darf fehlen, wenn sw = +1)
f1 = Strukturblock
= Schleifenkörper
Iterationsblöcke:
Zählschleife (Sonderfall der Bedingungsschleife ):
sv = aw, ew [,sw]
f1
Iteration,
"for" statement (similar to "while" statement)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements - for statement
for
([initialisation];[condition];[update])
{
statements;
}
for (var in object)
{
statements;
}
Special loop: iteration through all properties of an object
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements
Aneinanderreihung von Strukturelementen
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Structure Elements
Schachtelung von Strukturelementen
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Loops
� While:
while (<boolean>) {<statements>}
� Do-While:
do {<statements>} while (<boolean>)
� For:
for (<init>; <boolean>; <increment>)
{<statements>}
Three types of loops
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Loops
for (j = 0; j < n; j++)
{
statements
}
Syntax of the For-Loop:
initialisation
(int j already declared)
condition
(n must already have a value)
iteration
(increment)
semicolons
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Loops
for (int j = 0; j < n; j++)
j is called the loop index variable.
Recommended Form:
Note:
the full definition (declaration and initialisation)
is here, this variable's scope is then limited to
the body of the loop.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Loops
public class Power2
{
public static void main(String[] args)
{
int power=1, nmax;
System.out.println("N\t^N");
nmax = Integer.parseInt(args[0]);
for (int n=1; n<=nmax; n++)
{
power*=2;
System.out.print(n);
System.out.println("\t" + power);
}
}
}
Example: Calculate powers of 2
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Loops
Test:
Calculate 2n for larger n
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java Loops
c:\JavaLecCode>java Powers2 20
N ^N
1 2
2 4
3 8
4 16
5 32
6 64
7 128
8 256
9 512
10 1024
11 2048
12 4096
13 8192
14 16384
15 32768
16 65536
17 131072
18 262144
19 524288
20 1048576
Result for n = 20:
N ^N
1 2
2 4
3 8
20 1048576
21 2097152
22 4194304
23 8388608
24 16777216
25 33554432
26 67108864
27 134217728
28 268435456
29 536870912
30 1073741824
31 -2147483648
32 0
33 0
34 0
35 0
36 0
Result for n = 36:
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Input
Resources
Further reading, see:
http://java.sun.com/javase/
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java 2 – V1.4
http://java.sun.com/j2se/1.4.2/docs/
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java 2 – V5
http://java.sun.com/j2se/1.5.0/docs/
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java 2 – V6
http://download.oracle.com/javase/6/docs/
Java Platform, Standard Edition 6 JDK
Product version number: 6
Developer version number: 1.6.0
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java 2 – V7
http://download.oracle.com/javase/7/docs/
Java Platform, Standard Edition 7 JDK
Product version number: 7
Developer version number: 1.7.0
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java 2 – Tools, APIs
Java 2 SDK
Tools and Utilitieshttp://java.sun.com/j2se/1.4.2/docs/tooldocs/tools.html
Java 2 Platform Standard Edition 5.0
API Specification http://download.oracle.com/javase/1.5.0/docs/api/
JavaTM 2 Platform, Standard Edition, v 1.4.2
API Specification http://java.sun.com/j2se/1.4.2/docs/api/
Java 2 Platform Standard Edition 6.0
API Specification http://download.oracle.com/javase/6/docs/api/
Java 2 Platform Standard Edition 7.0
API Specification http://download.oracle.com/javase/7/docs/api/
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Input
Command Line Input
CLI
Further reading, see:
Arrays
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Input / Output
Command Line Input:
main (String args[]) {...}
Array of Strings
Command args[0] args[1] … args[n-2] args[n-1]
Argument 1Argument 2 Argument n-1
Argument n
String Arguments
String
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Input
Command Line Arguments:
Command Line Input is possible via the args[ ] string array.
args is a special array that holds the command line arguments in
the order of input:
args[0], args[1], …
Example: command to print CLI-argument:
System.out.println(args[0]);
Problem:
Wrong number of arguments results in an error message:
Exception in thread "main":
IndexOutOfBoundsException.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Input
Conditional Statements: if …, if … else
���� Boolean Operators <, >, <=, >=, ==
Check for non-zero number of arguments:
if (args.length > 0)
{
System.out.println (args[0])
}
or:if (args.length > 0)
{
System.out.println (args[0])
}
else
{
System.out.println ("No Input")
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Command Line Input
class helloCLI
/** HelloWorld with Command Line Input */
{
public static void main(String args[])
{
int i;
System.out.print("Hello ");
for (i=0; i < args.length; i = i+1)
{
System.out.print(args[i]);
System.out.print(" ");
}
System.out.println(); // new line
}
}
Variable number of input values (use of loops):
Tradition from Fortran; Loop variables: i, j, k, ]
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Input / Output
Problem: Numerical input values
The input string-elements args[i] have to be converted, before they
can be used in arithmetic operations, etc.
Array of Strings (has to be converted):
Integer.parseInt (args[...]);
Standard Output:
System.out.print(...); // no <CR>,<LF>
System.out.println(...); // with <CR>,<LF>
Obs.:Output with “print” will be buffered;
at least one “println” is necessary to terminate a sequence of output operations.
Additional info: see Wrapper classes
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Numerical Command Line Input
class helloCLIn
/** HelloWorld with numerical Command Line Input */
{
public static void main(String args[])
{
int i, sum=0;
System.out.print("Hello ");
for (i=0; i < args.length; i = i+1)
{
sum += Integer.parseInt(args[i]);
}
System.out.println("Result: " +sum);
}
}
Numerical input values: Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Strings
String Concatenation:
String concatenation operator: +
In case that either operand of the binary + operator is a reference to
a String class (or StringBuffer class), the operator is interpreted as
the string concatenation operator instead of the arithmetic addition
operator.
The string concatenation operator produces a new string object
that contains the concatenation of its operands.
If one of the operands is a reference to a string object and the other
is not, the nonstring operator is converted to a string object.
In order to implement string concatenation Java uses StringBuffer
objects:
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Strings
String Concatenation:
In order to implement string concatenation Java uses StringBuffer
objects:
Example:
Program Code:
String s, s1, s2
s = s1 + s2
Java code for string concatenation:
s = new Stringbuffer().append(s1).append(s2).toString()
Javanew Operator
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming Paradigms
Programming Paradigms
Paradigma: Example or Model
[lat. paradigma, gr. paradeigma]
Thomas Kuhn , 1970:
"The Structure of Scientific Revolutions".
Robert Floyd, 1979:
"The Paradigms of Programming".
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming Paradigms
Alan C. Kay, 1993:
"The Early History of Smalltalk".
����Reader
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
The Early History of Smalltalk
1. Everything is an object.
2. Computation is performed by objects communicating with each
other, requesting that other objects perform actions. Objects
communicate by sending and receiving messages. A message is
a request for action bundled with whatever arguments may be
necessary to complete the task.
3. Each object has its own memory, which consists of other
objects.
4. Every object is an instance of a class. A class simply represents
a grouping of similar objects, such as integers or lists.
5. The class is the repository for behaviour associated with an
object. That is, all objects that are instances of the same class
can perform the same actions.
6. Classes are organized into a singly rooted tree structure, called
the inheritance hierarchy. Memory and behaviour associated
with instances of a class are automatically available to any class
associated with a descendant in this tree structure.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
All computer programs consist of two elements: code and data. A program can be conceptually organized around its code or around its data.
There are two models that govern how a program is constructed:
Process-oriented Model.
Object-oriented Model.
Process-oriented model:characterizes a program as a series of linear steps (code). It can be thought of as code acting on data.
Object-oriented model:organizes a program around its data (objects) and a set of well-defined interfaces to the data. It can be thought of as data controlling access to code.
Programming Paradigms
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Mechanisms that help implement the
object-oriented model:
– Encapsulation
– Inheritance
– Polymorphism
Object-Oriented Programming
– Data Abstraction
– Persistence
– Delegation
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• Encapsulation binds together code and data.
• Basis of encapsulation is the class.
• Code and data that constitute the class are called
members of the class.
• Data defined by the class is referred to as member
variable or instance variable.
• The code that operates on that data is referred to
as member methods or just methods. In Java
programs, the methods define how the member
variable can be used.
Encapsulation
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
class Rect {float w, h;
float Area() {return w*h;
}
}
public class Example1{public static void main(String args[]){
Rect p = new Rect();p.w = 10.2f;p.h = 12.4f;
System.out.println("Area is " + p.Area());}
}
Encapsulation – Class Example
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"new" Operator
Creating Objects – The "new" operator
A class provides the blueprint for objects; the object is created from
the class. The following statement creates an object and assigns it to
a variable:
Rect p = new Rect();
This statement creates an object of the Rect() class. It has three
parts (discussed in detail later):
• Declaration:
The code "Rect p" declares a variable that associates a
variable name with an object type.
• Instantiation:
The "new" keyword is the Java operator that creates the object.
• Initialization:
The "new" operator is followed by a call to a constructor, which
initializes the new object.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Programming
Objects and Messages
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Class-Definition:
Template (blueprint, prototype) of an object.
Object-Definition:
Software unit of variables (data) and related
methods.
Variable Declarations
Methods
Class
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Class
Definitions:
Object:
Software unit of variables (data) and related methods.
Class:
Software construct that defines the instance variables and
methods of an object.
A class in itself is not an object. It is the template (blueprint,
prototype) that defines how an object will look and behave when
the object is created or instanciated from the specification
declared by the class.
class instanciation ���� concrete object
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Messages:
Software objects interact and communicate with
each other using messages.
Object A
Object B
Message
Class / Messages
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Class
Messages:
Software objects interact and communicate with each other using
messages.
When object B wants object A to perform one of A's methods,
object B sends a message to object A.
Sometimes the receiving object needs more information, so that it
knows exactly what to do. This information is passed along with
the message as parameters.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Composition of a message:
1. The object to which the message is addressed;
2. The name of the method to perform;
3. Any parameter needed by the method.
Syntax:object.method(parameters)
Object A
Object B
Parameters
Message with Parameters
Class / Messages
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Inheritance
Definitions:
Inheritance - Subclassing:
New and enhanced objects can be defined in terms of existing
objects by a mechanism called
SubclassingIn object-oriented terms this means creating a subclass of an
existing class, which is called the superclass.
���� Hierarchy of Classes
Each subclass inherits state (in form of variable declarations) from
the superclass.
However, subclasses are not limited to the state and behaviours
provided to them by their superclass. Subclasses can add
variables and methods to the one they inherit from the superclass.
Subclasses can also override inherited methods and provide
specialized implementations for those methods.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Inheritance
This procedure is not limited to just one layer of inheritance. The
inheritance tree, or class hierarchy, can be as deep as needed.
Methods and variables are inherited down through the levels.
In general, the further down in the hierarchy a class appears, the
more specialized its behaviour.
Special superclasses: abstract classes,
���� define "generic" behaviours.
Passing Information into a Method:The set of arguments to any method is a comma-delimited list of
variable declarations where each variable declaration is a
type/name pair:
type name
In the methods body the argument name is used to refer to the
argument's value.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
class Rect {float w, h;
float Area() {return w*h;
}
}
class Box extends Rect {float d;
float volume() {return w*h*d;}
}
Inheritance is the process by which one object
acquires the properties of another object
Inheritance
continued
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
public class Example2{
static public void main(String args[]){
Box Box1 = new Box();
Box1.w = 10.2f;
Box1.h = 12.4f;
Box1.d = 3.5f;
System.out.println("Area is " + Box1.Area());
System.out.println("Volume is " + Box1.volume());
}
}
Inheritance
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Object
Vehicle Building
BikeCar OfficeHouse
TruckVan
Inheritance
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
OOD
Object-Oriented Design Concepts
Abstract Data Type – ADT
• A structure that contains data and the actions that can be
performed on the data.
• Class:
an implementation of an ADT.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Unified Modeling Language:
The OMG (Object Management Group) specification states:
"The Unified Modeling Language (UML) is a graphical language for
visualizing, specifying, constructing, and documenting the artifacts
of a software-intensive system.
The UML offers a standard way to write a system's blueprints,
including conceptual things such as business processes and
system functions as well as concrete things such as programming
language statements, database schemas, and reusable software
components."
The Object Management Group (OMG)
http://www.omg.org/
UML
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
UML:standard language for modeling software systems:
• Bridge between the requirement specification and the
implementation.
• Way to specify and document the design of a software
system.
• Independent of the programing language.
• Suited to object-oriented program design and
development.
UML
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
UML
Object-Oriented Technologies
(Object Oriented Analysis and Design - OOAD)
• 1986: OOD by Grady Booch
• 1988: Shlare/Mellor,
• 1991: Coad/Yordon, OMT by James Rumbaugh
• 1992: OOSE by Ivar Jacobson
• 1993-1994: Design Patterns by GoF
• 1997: CBSE by Szyperski
UML
• 2004: UML 2 & MDA
Grady Booch
James Rumbaugh
Ivar Jacobson
OOD: Object-Oriented Design
OMT: Object Modeling Technique
OOSE: Object-Oriented Software Engineering
CBSE: Component-based Software Engineering
UML: Unified Modeling Language
MDA: Model-driven architecture
GoF, or Gang of Four:Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides:
Design Patterns: Elements of Reusable Object-Oriented Software
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
UML Models
A UML model consists of:
• A diagram:graphical representation, general overview of the model, shows
the principal elements and their relation.
• A specification:the details of each element – should have sufficient information
to develop the program code.
UML diagrams:
• Class diagram:
set of classes, interfaces, collaborations
• Object diagram:
set of objects and their relationship
• Use case diagram:
use cases and actors
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
UML Models
Class diagram:
name
operations
attributes
responsibilities
(optional text)
Car
drive()
accelerate()
brake()
park()
type
size
class icon is devided into three compartment
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
UML Models
Relationships:
A dependency:semantic relationship between two things (the change of one
effects the semantics of the other one).
An association:structural relationship describing a set of links (connections
between objects).0...1 *
parents child
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
UML Models
Relationships:
A generalization:specialization/generalization relationship, objects of the
specialized element (child) can be substituted for objects of the
generalized element (parent)
A realization:semantic relationship between classifiers.
parentschild
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Vehicle
Car
Superclass
Subclass
Inheritance Diagram (UML)
Generalization:
generalization
Obs.:
Short form presentation of classes:
only name is shown, attributes and operations are avoided
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• Polymorphism (“many forms”) is a feature that allows
one interface to be used for a general class of actions.
• Concept of polymorphism is expressed by "one
interface, multiple methods".
• Compiler selects the specific action (method) as it
applies to each situation.
• Result: reduction of complexity.
Polymorphism
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Polymorphism
continued
class A {
int i,j;
int sum1() {
return i+j;
}
}
class B extends A {
int k;
int sum2() {
return i+j+k;
}
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Polymorphism
public class Example3{
static public void main(String args[]){
B q = new B();
q.i = 2;
q.j = 4;
q.k = 3;
System.out.println("Sum: " +q.sum1());
System.out.println("Sum: " +q.sum2());
}
}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• Polymorphism, encapsulation, and inheritance combine
to produce a programming environment that supports
the development of far more robust and scaleable
programs than does the process-oriented model.
• A well-designed hierarchy of classes is the basis for
reusing the code in which we have invested time and
effort developing and testing.
• Encapsulation allows to migrate implementations over
time without breaking the code that depends on the
public interface of the class.
• Polymorphism allows to create clean, sensible,
readable and resilient code.
Polymorphism, encapsulation, inheritance
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• Creating a class means creating a new data type. This
type can be used to declare objects of that type.
• Obtaining objects of a class is a two-step process:
1. Declaring a variable of the class type. This variable does
not define an object, it is simply a variable that can refer to
an object.
2. Create an actual, physical copy of the object and assign it
to that variable.
This is done using the "new"-operator, which dynamically
allocates run time memory for an object and returns a
reference to it. This reference is the address in memory of
the object allocated by "new". This reference is then
stored in the variable.
Declaring Objects
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Vehicle
Bike Car
Truck
is subclass of
BMWToyota
Mountain
Bike
is instance (object) of
Declaring Objects
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Creating Instances, Objects
1. Create a class:
class TestClass
{
...
}
2. Declare a reference or pointer variable:
TestClass mytest;
3. Create an object (=instance); make the reference
variable point to it using the operator “new”
mytest = new TestClass();
� Steps 2. and 3. can be combined:
TestClass mytest = new TestClass();
(Instances = Objects)
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Declaring Objects – Example 1
Two-step process:
Rect rect1 = new Rect();
This statement combines the two steps just described:
Rect rect1; // declare reference to object
rect1 = new Rect(); // allocates a Rect object
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Declaring Objects – Example 2
Data within an object can consist of primitive types:
class TestClass
{
int x, y;
double a, b;
}
Creating an object of ”class TestClass”
TestClass mytest = new TestClass();
Reading / Modifying the data belonging to the new object
(instance):
mytest.a = 1.1;
score = mytest.x;
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Parameters allow a method to be generalized. A parameterized
method can operate on a variety of data and can be used in
different situations.
Adding a method that takes Parameters
continued
class Rect {double width;double length;
double area() {return width * length;
}
void setDim(double w, double l) {width = w;length = l;
}}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Adding a method that takes Parameters
class Example4 {public static void main(String args[]) {
Rect rect1 = new Rect();Rect rect2 = new Rect();
double A1, A2;
rect1.setDim(10,20);rect2.setDim(5,8);
A1 = rect1.area();A2 = rect2.area();
System.out.println("Area of rect1 is: " +A1);System.out.println("Area of rect2 is: " +A2);}
} Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• Java allows objects to initialize themselves when they
are created. This automatic initialization is performed
through the use of a constructor.
• A constructor has the same name as the class in which
it resides and is syntactically similar to a method.
• The constructor is automatically called immediately after
the object is created.
• Constructors have no return type (not even void).
• A parameterized constructor accepts arguments when
called.
Constructors
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Constructors - Example
continued
class Rect {
double width;
double length;
Rect(double w, double l) {
width = w;
length = l;
}
double area() {
return width * length;
}
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Constructors - Example
Java
class Example5 {
public static void main(String args[]) {
Rect rect1 = new Rect(10,20);
Rect rect2 = new Rect(5,8);
System.out.println("Area of rect1 is: " + rect1.area());
System.out.println("Area of rect2 is: " + rect2.area());
}
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Constructors – Example 2
class Body
{
public long idNum;
public String name = "<unnamed>";
private static long nextID = 0;
Body() // constructor declaration
{
idNum = nextID++;
}
}
Properties of constructors:
• Always have the same name as the class,
• Don’t have a return type
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Constructors – Example 2
class Person{
String name;int age;
Person (String n, int a) // Constructor{
name = n;age = a;System.out.println("\nCopyright (C) 2006");System.out.println(name + a);
}
public static void main (String args[]){
Person p;p = new Person("Julie: ", 20);p = new Person("John: ", 25);
}}
Output: Copyright (C) 2006Julie: 20
Copyright (C) 2006John: 25Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Arguments
Definitions:
Argument Types:
In Java an argument of any valid data type can be passed into a
method.
���� primitive data types,
���� reference data types (objects, arrays).
Unlike some other languages, you cannot pass methods into Java
methods. But you can pass an object into a method and then
invoke the object's methods.
Argument Names:
A method argument can have the same name as one of the class's
member variables. If this is the case, then the argument is said to
hide the member variable.
Arguments that hide member variables are often used in
constructors to initialize a class.
Example: Circle class and constructorSource: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
this:
• Sometimes a method will need to refer to the object that invoked
it. To allow this, Java defines the "this" - keyword. "this" can be
used inside any method to refer to the current object.
• "this" can be used anywhere a reference to an object of the
current class type is permitted.
Example 1:
Rect(double w, double l){
this.width = w;
this.length = l;
}
The "this" - Keyword
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
class Circle
{
int x,y,radius;
Circle (int x, int y, int radius)
{
...
}
}
Argument Names - Hiding Member Variables
The argument names hide the member variables!
member/Instance
variables
formal parameters
Constructor
Example: Circle class and constructor
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
class Circle
{
int x,y,radius;
Circle (int x, int y, int radius)
{
this.x = x;
this.y = y;
this.radius = radius;
}
}
"this" - the current object
To access the member variables, they must be
referenced through "this".
formal parameters
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Arguments
The Circle class has three member variables:
x, v, radius.
In addition, the constructor for the Circle class accepts three
arguments each of which shares its name with the member
variable for which the argument provides an initial value.
The argument names hide the member variables. So using x, y and
radius within the body of the constructor refers to the argument,
not to the member variable.
To access the member variable, it must be referenced through
this – the current object.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• In Java it is possible to define two or more methods
within the same class that share the same name, as long
as their parameter declarations are different.
• In this case the methods are said to be overloaded, and
the process is referred to as method overloading.
• Method overloading is one of the way that Java
implements polymorphism.
• When an overloaded method is invoked, Java uses the
type and/or number of arguments as its guide to
determine which version of the overloaded method to
actually call.
Overloading Methods
Signature
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Overloading Methods
continued
class OvDemo {
void test() {
System.out.println("No parameter!");
}
void test(int i) {
System.out.println("i is " + i);
}
void test(int i, int j) {
System.out.println("i is: "+i+"\nj is: " + j);
}
double test(double i) {
System.out.println("double is: " + i);
return i*i;
}
}
test() methods have
different "signatures"
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Overloading Methods
class Example6 {
public static void main(String args[]) {
OvDemo x = new OvDemo();
x.test();
x.test(20);
x.test(20, 30);
System.out.println
("Result of double test:" + x.test(15.45));
}
}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• In addition to overloading normal methods, constructor
methods can also be overloaded.
For example, Rect class requires two arguments, and it
will cause error to call it without them.
• But, what if we want to be able to call Rect() with only
one argument or without any argument at all?
• The solution to this question is simply overloading the
Rect constructor so that it handles the situations just
described.
Overloading Constructors
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Overloading Constructors
continued
class Rect {
double width;double length;
Rect(double w, double l) {width = w;length = l;
}
Rect(double w) {width = length = w;
}Rect() {
width = length = 0;}
double area() {return width * length;
}}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Overloading Constructors
class Example7 {
public static void main(String args[]) {
Rect rect1 = new Rect(10,20);
Rect rect2 = new Rect(5);
Rect rect3 = new Rect();
System.out.println
("Area of rect1 is: " + rect1.area());
System.out.println
("Area of rect2 is: " + rect2.area());
System.out.println
("Area of rect3 is: " + rect3.area());
}
} Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• In a class hierarchy, when a method in a subclass has
the same name and type signature as a method in its
superclass, then the method in the subclass is said to
override the method in the superclass.
• When an overridden method is called from within a
subclass, it will always refer to the version of that
method defined by the subclass.
• The version of the method defined by the superclass will
be hidden.
Method Overriding
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• Method overriding forms the basis for one of the Java's
most powerful concepts: dynamic method dispatch.
• Dynamic method dispatch is the mechanism by which a
call to an overridden function is resolved at run time,
rather than compile time. Dynamic method dispatch is
important because this is how Java implements run-time
polymorphism.
• Polymorphism is essential for object-oriented
programming because it allows a general class to
specify methods that will be common to all of its
derivatives, while allowing subclasses to define the
specific implementation of some or all of those methods.
Method Overriding
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
• Overridden methods are another way that Java
implements the "one interface, multiple methods" aspect
of polymorphism.
• Part of the key to successfully applying polymorphism is
understanding that the superclasses and subclasses
form a hierarchy which moves from lesser to greater
specialization.
• Through the dual mechanism of inheritance and run-
time polymorphism, it is possible to define one
consistent interface that is used by several different, yet
related types of objects.
Method Overriding
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Class Class
Class Class
Class
Method
Object Object
Method Overriding
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Class Class
Class
Method
Object Object
Class
Method
Method Overriding
Method Overriding
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
There are two ways that a computer language can pass an
argument to a subroutine.
1. Call-by-value:This method copies the value of an argument into the formal
parameter of the subroutine. Therefore, changes made to the
parameter of the subroutine have no effect on the argument
used to call it.
2. Call-by-reference:In this method, a reference to an argument (not the value of
the argument) is passed to the parameter. Inside the
subroutine, this reference is used to access the actual
argument specified in the call. This means that changes
made to the parameter will effect the argument used to call
the subroutine.
Argument Passing
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Java uses Call-by-value.
• When a simple type is passed to a method, it is passed by
value. Thus, what happens to the parameter that receives
the argument has no effect outside the method.
• When objects are passed to a method the reference
(address) is passed as a value. The reference to the object is
available inside the method, so that changes can be passed
to this object.
Argument Passing
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Argument Passing - Call by value
class Pen{
int rValue, gValue, bValue;...void getRGB(int red, int green, int blue){... red, green, blue = -1
red = rValue;green = gValue;blue = bValue;
}}
calling sequence:
...int r = -1, g = -1, b = -1;pen.getRGB(r,g,b);System.out.println(r+g+b);...
?
?
?
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Argument Passing - Call by reference
class RGBColor{
public int red, green, blue;}
class Pen{
int rValue, gValue, bValue;void getRGB (RGBColor aColor){aColor.red = rValue;aColor.green = gValue;aColor.blue = bValue;}
}
calling sequence:
...RGBColor penColor = new RGBColor();pen.getRGB (penColor);System.out.println(penColor.red +
penColor.green + penColor.blue);...
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Argument Passing - Call by value
class Test {
void cal(int i, int j) {i *= 5;j /= 10;
}}
class ExampleCallValue {public static void main(String args[]) {Test ob = new Test();
int i = 10, j = 20;System.out.println("Original i and j: "+i+" "+j);
ob.cal(i,j);System.out.println
("Changed i and j: " + i + " " + j);}} Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Argument Passing - Call by reference (value)
class Test {
int a, b;
Test (int i, int j) {a = i;b = j;
}
void cal(Test o) {o.a *= 5;o.b /= 10;
}}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Argument Passing - Call by reference (value)
class ExampleCallRef {
public static void main(String args[]) {
Test ob = new Test(10, 20);System.out.println("Original ob.a and
ob.b:"+ob.a+" "+ob.b);
ob.cal(ob);System.out.println("Changed ob.a and ob.b:
"+ob.a+" "+ob.b);
}}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Modifiers and Protection
Modifiers and Protection for Classes, Variables, and Methods
nonoyesyesFrom a subclass outside the same package
noyesyesyesFrom a subclass in the same package
nononoyesFrom any class outside the same package
noyesyesyesFrom any class in the same package
yesyesyesyesFrom the same class
privatepackageprotectedpublicVisibility/Protection
Obs.: The older form “private protected” is not available any more (for JDK ≥≥≥≥ 1.02)
XXpackage
XXXXpublic
XXXprotected
Xprivate
worldpackagesubclassclassSpecifier
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Modifiers
variable is not thread safe (not used since 1.0.2)variablevolatile
locks object for other threadsmethodsynchronized
no return valuemethodvoid
or method-variablevariable
one instantiation only for class-variablemethodstatic
platform dependent code, no bodymethodnative
constantvariable
no overridingmethod
no subclassclassfinal
no bodymethod
no instantiation (abstract class)classabstract
DescriptionAppl.Modifier
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Accessors
Accessors: getter and setter methods
Get method (getter): A method that returns (gets) the value of an
instance variable, A method which returns the state of an object.
Set method: A method that programs (sets) the value of an
instance variable, A method which programs the state of an object.
Class Test type getVar()
{ {
private int x; return x;
private int y; }
}
void setVar(type y)
{
this.y = y;
}
Getter method
Setter method
Problem:
commonly used, not good programming style
(data abstraction in OOP)!
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Bjarne Stroustrup in der
Computer-Schausammlung der FH Kiel
Accessors
Problem:
getter and setter methods
http://www.artima.com/intv/goldilocks2.html
Bjarne Stroustrup:
"I particularly dislike classes
with a lot of get and set
functions. That is often an
indication that it shouldn't have
been a class in the first place.
It's just a data structure. And if it
really is a data structure, make it
a data structure."
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Type Casting (Converting)
Casting (Converting) converts the value of an object or primitive type into
another type.
There is no automatic coercion (casting) in Java!
Primitive ↔↔↔↔ Primitive
Object ↔↔↔↔ Object
Primitive ↔↔↔↔ Object
Rules:� The type "boolean" cannot be casted.
� No type can be casted to boolean.
� All numerical types can be casted to any other numerical type.
� A reference type can be casted into another reference type when they
are related by inheritance.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Casting (Converting)
Type-casting
There are two types of casting:
Implicit casting and explicit casting.
Implicit casting means simply assigning one entity to
another without any guidance to the compiler.
Example:int a = 1000;
long b = a; //Implicit casting
Problem:int a = 1000;
long b = a; //Implicit casting
a = b;
throws exception: explicit cast required
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Casting (Converting)
Explicit casting of primitive (fundamental) types means very
specifically informing the compiler about the transformation
that is expected.
Syntax Diagram:
Example: (int) (x / y)
Precedence of casting is higher than that of
arithmetic!
Example:int a = 1000;
long b = a; //Implicit casting
a = (int) b; //Explicit casting
( type )
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Casting (Converting)
Widening Casting
byte
charshort
int
long
float
double
Widening
conversion
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Casting (Converting)
Casting Objects (Reference Types):
Downward casting in the class hierarchy is automatic!
Upward casting:Syntax: (Classname) object
Example:Car auto;
Vehicle veh;
auto = new Car();
veh = (Vehicle) auto;
Vehicle
Car
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Casting (Converting)
Converting Primitive Types to Objects and vice versa:
Automatic casting between primitive types and objects is not
possible!
However:
The java.lang package includes special classes (so called
“Wrapper Classes”) that correspond to each primitive data type:
Integer ↔↔↔↔ int
Float ↔↔↔↔ float...
Example:int →→→→ Integer: // Conversion
Integer intObject = new Integer(10);
Integer →→→→ int: // Method
int vInt = intObject.intValue(); // Returns 10
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Wrapper Classes
Booleanboolean
Characterchar
Doubledouble
Floatfloat
Longlong
Integerint
Bytebyte
Shortshort
Wrapper ClassPrimitive Type
Constructs a newly allocated object that represents
the primitve value indicated by the String parameter.
WrapperType (String s)
e.g. Integer(String s)
Constructs a newly allocated object that represents
the specified primitive type value.
WrapperType (type value)
e.g. Integer(int value)
At least two constructors exist for all wrapper classes:
Observe
change of name
Ref.: Sun JavaTM 2 SDK, Standard Edition Documentation
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Wrapper Classes
Returns the value of this Integer as an int.intValue()
Returns an Integer object holding the value of the
specified String.valueOf(String s)
Parses the string argument as a signed decimal integer.parseInt(String s)
Several methods exist for all wrapper classes
Example: Integer
Ref.: Sun JavaTM 2 SDK, Standard Edition Documentation
Since JDK 1.2 all parseType-methods exist (except for
Boolean):
parseShort, parseInt, parseLong, parseDouble, parseFloat
Returns boolean true if and only if the system
property named by the argument exists and is
equal to the string "true".
getBoolean(String name)
Example: Boolean
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Super
• There might be situations when we will want to create a
superclass that keeps the details of its implementation to itself
(keeps its data members private).
In this case, there would be no way for a subclass to directly
access or initialize these variables on its own.
• Since encapsulation is a primary attribute of OOP, Java
provides a solution to this problem. Whenever a subclass
needs to refer to its immediate superclass, it can do so by use
of the keyword "super".
• "super" has two general forms:
- The first calls the superclass's constructor.
- The second is used to access a member of the superclass
that has been hidden by a member of a subclass.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"super" - call Superclass Constructors
A subclass can call a constructor method defined by its
superclass by use of the following form of "super":
super(parameter_list);
where parameter_list specifies any parameters needed
by the constructor in the superclass.
super must always be the first statement executed inside a
subclass's constructor.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
"super" - Second Use
The second form of super acts somewhat like this, except
that it always refers to the superclass of the subclass in
which it is used. This usage has the following general form:
super.member
where member can be either a method or an instance
variable. This form of super is most applicable to situations
in which member names of a subclass hide members by the
same name in the superclass.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Abstract Methods and Classes
An abstract method is defined by its signature only, it has no
body. The details for the method, i.e. the body, are supplied by
sub-classes.
To declare a method the keyword "abstract" is used.
Example:
abstract public void function(int test);
An abstract method can be considered a template or blueprint for
a method whose details are contained in the sub-classes.
The abstract methods are overriden by the full method definitions
contained in the sub-classes.
Abtract Methods:
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Abstract Methods and Classes
An abstract class is identified by the keyword abstract. It does not
have to contain an abstract method, however, a class that does
contain at least one abstract method is considered to be an
abstract class and must therefore be declared abstract.
Syntax:abstract class ClassName {
< Field Declarations >
< Method Declarations >
}
An abstract class can contain methods that are not abstract.
The abstract class itself cannot be used for instantiation. To do
this a sub-class has to be defined first.
Similar to abstract methods, the abstract classes are used to
represent concepts or entities.
Abtract Classes:
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Interfaces
Multiple inheritance
class A
Not allowed in Java
class B
class C class D class E
class FProblem:
Diamond inheritance:
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Interfaces
Problem in Java:
� No multiple inheritance
Solution:
� Interfaces:Collection of abstract methods and constants only.
Interfaces do not declare any concrete methods.
Implementation inheritance:A class can only extend one other class.
interface inheritance:Interfaces provide a form of multiple inheritance, because
multiple interfaces can be implemented.
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Interfaces
Interface Declaration:
interface InterfaceName [extends InterfaceNameList]
{
... interface body
// abstract methods and constants
}
default modifier:
Methods: abstract, public
Variables: static, final, public
use "public" when overriding
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Interfaces
Syntax diagram for interface declaration:
modifier
interface name body
extends name
Inheritance of Interfaces:
[public] class ClassName
[extends SuperClass]
implements InterfaceNameList;
{
... body
// implementation of interfaces
}
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Interfaces
interface Size {
int length = 1;
int width = 10;
int length();
int width();
}
class Area implements Size {
public int length() {
System.out.println("Length = "+Size.length);
return Size.length;
}
public int width() {
System.out.println("Width = "+Size.width);
return Size.width;
}
}
continued
abstract methods
final
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Interfaces
public class AreaTest {
public static void main(String[] args) {
Area Area2 = new Area();
System.out.println("Area = "+Area2.length()*Area2.width());
}
}
Java
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Classes
Special Classes
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Math
Class Math
public final class Math
extends Object
The class Math contains methods for performing basic
numeric operations such as the elementary exponential,
logarithm, square root, and trigonometric functions.
Source: Sun Microsystems
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Source: Sun Microsystems
Computes the remainder operation on two arguments as prescribed by
the IEEE 754 standard.
IEEEremainder(double f
1, double f2)
Returns the largest (closest to positive infinity) double value that is not
greater than the argument and is equal to a mathematical integer.
floor(double a)
Returns Euler's number e raised to the power of a double value. exp(double a)
Returns the trigonometric cosine of an angle. cos(double a)
Returns the smallest (closest to negative infinity) double value that is not
less than the argument and is equal to a mathematical integer.
ceil(double a)
Converts rectangular coordinates (x, y) to polar (r, theta).atan2(double y,
double x)
Returns the arc tangent of an angle, in the range of -pi/2 through pi/2. atan(double a)
Returns the arc sine of an angle, in the range of -pi/2 through pi/2.asin(double a)
Returns the arc cosine of an angle, in the range of 0.0 through pi. acos(double a)
Returns the absolute value of a long value.abs(long a)
Returns the absolute value of an int value.abs(int a)
Returns the absolute value of a float value. abs(float a)
Returns the absolute value of a double value.abs(double a)
Math
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Source: Sun Microsystems
Returns the closest int to the argument. round(float a)
Returns the closest long to the argument.round(double a)
Returns the double value that is closest in value to the argument and is
equal to a mathematical integer.
rint(double a)
Returns a double value with a positive sign, greater than or equal to 0.0
and less than 1.0.
random()
Returns the value of the first argument raised to the power of the second
argument.
pow(double a, double b)
Returns the smaller of two long values. min(long a, long b)
Returns the smaller of two int values. min(int a, int b)
Returns the smaller of two float values. min(float a, float b)
Returns the smaller of two double values. min(double a, double b)
Returns the greater of two long values. max(long a, long b)
Returns the greater of two int values. max(int a, int b)
Returns the greater of two float values.max(float a, float b)
Returns the greater of two double values.max(double a, double b)
Returns the natural logarithm (base e) of a double value. log(double a)
Math
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Source: Sun Microsystems
Converts an angle measured in degrees to an approximately
equivalent angle measured in radians.
toRadians(double angdeg)
Converts an angle measured in radians to an approximately
equivalent angle measured in degrees.
toDegrees(double angrad)
Returns the trigonometric tangent of an angle.tan(double a)
Returns the correctly rounded positive square root of a double value. sqrt(double a)
Returns the trigonometric sine of an angle. sin(double a)
Math
The double value that is closer than any other to pi, the ratio of the circumference of a circle to
its diameter.
PI
The double value that is closer than any other to e, the base of the natural logarithms. E
Field Summary
http://java.sun.com/j2se/1.4.2/docs/api/index.html
Fachbereich Informatik und Elektrotechnik
Programming in Java, Helmut Dispert
Math
class MathTest
{
public static void main(String args[])
{
double x,y,z;
x=Math.sin(Math.PI);
y=Math.sin(Math.PI/2.);
System.out.println("Result: \n" +x + "\n"+y);
x=2;
y=4;
z=Math.pow(x,y);
System.out.println("\n\nResult: \n" +z);
x=10000;
z=Math.sqrt(x);
System.out.println("\n\nResult: \n" +z);
}
} Java