You are on page 1of 59

ASE Lecture 1

Advanced Software Engineering


Prof. Dr. Tobias Meisen
Dipl.-Inform. Christian Kohlschein

Institute of Information Management in Mechanical


Engineering (IMA)
RWTH Aachen University
Fall 2015

www.ima-zlw-ifu.rwth-aachen.de

The Road Ahead Lecture 1


Organization and Motivation
Whats Java?

Structure of a Java Program


Variables
Control Flow Statements
Arrays and Strings

21.10.2015

Advanced Software Engineering

Organization
Your lecturers

Prof. Dr. Tobias Meisen

Dipl.-Inform. Christian Kohlschein

Professor of Mechanical Engineering


Chair for Information Management

Computer Scientist and Researcher


Chair for Information Management

Contact
ase@ima.rwth-aachen.de
0241 80 911 77
Office hours: By appointment
https://www3.elearning.rwth-aachen.de/ws15/15ws-05458/
21.10.2015

Advanced Software Engineering

Organization
Synopsis
Todays mechanical engineering relies heavily on advanced software tools. Both
industry and research expect you not only to use these tools but to design, develop
and deploy them as well. During this course we teach you how.

Timeline for Lectures and Exercises

Java 101

Object
Oriented SE

Project
Management
in SE

Applications

Exam

Lec./Ex. 1 - 3

Lec./Ex. 4 - 6

Lec./Ex. 7 - 9

Lec./Ex. 10 - 12

09.03.2016

No Lec./Ex. on: 18./19.11.15, 27./28.01.16 and 10./11.02.16

21.10.2015

Advanced Software Engineering

Motivation
Advanced Software Tools are everywhere in Engineering!
From Computer Aided Design (CAD) to Robotics

21.10.2015

Advanced Software Engineering

Motivation
Advanced Software Tools are everywhere in Engineering!
or Virtual Production Intelligence (at our Institute)

21.10.2015

Advanced Software Engineering

Motivation
Advanced Software Tools are everywhere in Engineering!
to self-optimizing Production Systems!

21.10.2015

Advanced Software Engineering

Whats Java?
Brief History
Java invented June 1991 by James Gosling at Sun (2010 acquired by Oracle)

Five Design Goals:


Simple, Object Oriented, and Familiar
Robust and Secure
Architecture Neutral and Portable
High Performance
Interpreted, Threaded, and Dynamic
Current Version: Java 8
21.10.2015

Advanced Software Engineering

Whats Java?
Its widely spread

TIOBE 2015 (Popularity Index)

21.10.2015

Industry use (to name a few)

Advanced Software Engineering

Whats Java?
A great deal of tools, libraries and frameworks

21.10.2015

Advanced Software Engineering

Whats Java?
Motto: Write Once, Run Anywhere

Design Time

Compile
Time

Java Byte
Code

OS X & Unix

Text files

101010101

Android

.java

.class

OS-Specific
JRE

Java Source

Java
Compiler

Windows

Run Time
21.10.2015

Advanced Software Engineering

10

Whats Java?
Terminology
JVM: Java Virtual Machine. Executes Java byte code.
JRE: Java Runtime Environment. Contains the JVM + set of libraries
JDK: Java Development Kit. Contains the JRE + Development tools (e.g. javac)

JVM Features

21.10.2015

Automatic Garbage Collector


JIT Compiler
Byte Code Verifier
Supports other languages:

Advanced Software Engineering

11

Whats Java?
What are the basic requirements for writing a Java program?
A computer with a Java supported OS (e.g. Windows or OS X)
A text editor, e.g. notepad++ (but well use
IDE during this course)
The Java JDK: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

Five steps to run a Java program

Create a Java source file, i.e. write some code.


Save it to a .java file (e.g. HelloWorld.java)
Compile the Code (using javac, e.g. javac HelloWorld.java).
The compilation yields a class file (e.g. HelloWorld.class)
Run the program (e.g. java HelloWorld)

21.10.2015

Advanced Software Engineering

12

Whats Java?
Writing, Compiling and Executing
1

1: Write
2: Compile
3: Yields a .class file
4: Execute
21.10.2015

Advanced Software Engineering

13

Structure of a Java Program


Structure of a Java Source File
Class Definition

Methods

Statements

public class Foo {

public class Foo {

public class Foo {

void bar() {

void bar() {
statement1;
statement2;

statement3;
}
}
21.10.2015

}
Advanced Software Engineering

}
}
14

Structure of a Java Program


Structure of a Java Source File
Class
Definition

public class HelloWorld {


public static void main (String[] args) {

Method
Statement

System.out.println("Hello, World!");
}
}

21.10.2015

Advanced Software Engineering

15

Structure of a Java Program


Structure of a Java Source file. A closer look at the class.
Keyword
class

Opening
Curly Brace

public class HelloWorld {

public
access

21.10.2015

The name
of the class

Closing
Curly Brace

Advanced Software Engineering

16

Structure of a Java Program


Structure of a Java Source File. A closer look at the method.

keyword
static

arguments of
the method

return type

public static void main (String[] args) {


Closing
Curly Brace

public
access

the name of
the method

Opening
Curly Brace

We will mainly stick to the main method in Lecture 1!

21.10.2015

Advanced Software Engineering

17

Structure of a Java Program


Structure of a Java Source File. A closer look at the statement.

print to standard
output

What to print in
apostophes

System.out.println("Hello, World!");
Statement
must end in a
semicolon!

21.10.2015

Advanced Software Engineering

18

Structure of a Java Program


What are comments?
Document the code and keep it readable
Single line comment: // myComment
Multiple line comment: /* myMultiLineComment */

Examples
public class HelloWorld { // Its my first class!
public static void main (String[] args) {
/* I want to
print on the command line */
System.out.println("Hello, World!");
}
}
21.10.2015

Advanced Software Engineering

19

Variables
What are variables?
A container, a box or a cup. It contains something.
They come in different kinds
They got a name

Examples

short numberOfEngines = 5;
double temperature = 23.7;
boolean engineStarted = true;
char c = 'e';
int depth = -343535;

21.10.2015

Advanced Software Engineering

20

Variables
Two ways of constructing variables
First declare, than initialize: int length;length = 5;
Or by defining them in one single statement: int length = 5;

Examples

short numberOfEngines = 5;
double temperature = 23.7;
boolean engineStarted = true;
char c = 'e';
int depth = -343535;

21.10.2015

Advanced Software Engineering

21

Variables
Four Primitive Data Types in Java
boolean, char, integer and floating point
They got a default value
They only hold one value
Data Type

Example

Keyword

Logical value

true, false

boolean

Single character

a, b,

char

Whole number

1, -3, 87,

byte, short, int, long

Real number

-2.6, 9.4,

float, double

For details (e.g. max or min values) see:


https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html
21.10.2015

Advanced Software Engineering

22

Variables
Rules I
Variables must have a type, e.g. double!
Variables must have a name, e.g. temperature!
double temperature;

type

name

Rules II and Good Practice


No keywords are allowed as names, e.g. class or while are prohibited!
https://en.wikipedia.org/wiki/List_of_Java_keywords
Names must start with a letter, underscore (_) or a dollar sign ($)
No special characters, e.g. .
Choose meaningful names, e.g. currentVelocity (as opposed to cV);
21.10.2015

Advanced Software Engineering

23

Variables
Three Kinds of Variables in Java
public class Cylinder {

instance variables

public double cylinderCap = 0;

class/static
variables

public static char vendor = 'A';


public double computeCylinderCapacity(int r, int h) {

double rSquare = r*r;


return rSquare * Math.PI * h;
}

local variables

21.10.2015

Advanced Software Engineering

24

Variables
Defining Constants Variables
Are all-round in Mathematics, physics, engineering ...
Are declared with the keyword final
Convention for naming of constants: UPPERCASE, e.g. PI or E

Examples (the bad and the good)


double circumf = 2 * 3.1415 * r;
double area = r * r * 3.1415;

final double PI = 3.1415;


double circumf = 2 * PI * r;
double area = r * r * PI;

Typing errors
Changing code in different places
Bad Readability

Good readability
DRY principle (dont repeat
yourself)

21.10.2015

Advanced Software Engineering

25

Variables
Operators and Variables

Allocation (=)
Arithmetic (+, -, *, /, %)
Comparison (==, !=, <, >)
Unary (++, --)
Logical (! (not), &&, ||)

Allocation and Arithmetic Operator Examples


int number; number = 5;
int x = 5;
int y = 7;
int sum = x + y;
int diff = 40 y;
double div = 30 / 4.3;
21.10.2015

Advanced Software Engineering

26

Variables
Operators and Variables

Allocation (=)
Arithmetic (+, -, *, /, %)
Comparison (==, !=, <, >)
Unary (++, --)
Logical (! (not), &, |)

Comparison, Unary and Logical Operator Examples


boolean isSmaller;
int one = 1; int two = 2;
isSmaller = one < two;
int i = 3;
int j = i++;
boolean result = !true | false;
21.10.2015

Advanced Software Engineering

27

Variables
Operators Priorities
How does Java evaluate an complex expression? E.g.:
int a = 5;
int b = 7;
int c = 2
a = a b + c % (a * c++); // (a is 4)
With an internal priority table! Excerpt from:
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/operators.html
Priority

Operator

Unary, e.g. ++

Additive, e.g. +

11

Logical OR e.g. |

13

Allocation, e.g. =

If two operators have same priority, Java parses the expression left to right.
21.10.2015

Advanced Software Engineering

28

Variables
Type Casts
It can be necessary to convert one type of data into an other one
There are two types of casts
Implicit type casts. Target type is computed automatically via context.
Upgrading.
Explicit type casts. Target type has to be explicitly defined. Downgrading.
Target type has to be defined in ( and ) brackets

Examples
int i = 70;
double radius = i; // radius contains 70.0
double d = 70.3456;
int num = (int)d; // num contains 70

21.10.2015

Advanced Software Engineering

29

Variables
Implicit type cast only one way

int variable

double variable

double variable
21.10.2015

int Variable
Advanced Software Engineering

30

Variables
Type cast overview

byte

short

int

long

float

char
implicit type cast
explicit type cast

double

boolean
21.10.2015

Advanced Software Engineering

String

31

Variables
Output
How does Java output information on the screen?
Without linefeed: System.out.print (<output>)
With: linefeed: System.out.print (<output>)

Examples
System.out.print("Hello, World");
System.out.print ("!"); // Output: Hello, World!
System.out.println ("Hello, World");

21.10.2015

Advanced Software Engineering

32

Control Flow Statements


Control flow
Statements are generally executed from top to bottom
Control flow statements break up the flow
Enable that particular blocks of code are executed conditionally

Control flow statements in Java

There are three types of control flow statements in Java


Decision-making statements (if-then, if-then-else, switch)
Looping statements (for, while, do-while)
Branching statements (break, continue, return)

21.10.2015

Advanced Software Engineering

33

Control Flow Statements


if-then(-else) statement (simple)

Certain section of code is only executed if test evaluates to true


If test section evaluates to false, else block is executed
Nesting possible
Else block is optional

Structure of a simple if-then-(-else) statement


if (<condition>){
statement(s)
}
else {
statements(s)
}

21.10.2015

Advanced Software Engineering

34

Control Flow Statements


A simple if-then(-else) example
public void break() {
if (carIsMoving) {
speed = 0;
}
else {
System.out.println("Car has already stopped!");
}
}
If the car is moving then set its speed to zero. Otherwise print a message to the
command line which says that the car has already stopped.

21.10.2015

Advanced Software Engineering

35

Control Flow Statements


A complex if-then(-else) statement
Its possible to test more then one condition using multiple clauses!
if (<condition 1>){
statement(s)
}
else if (<condition 2>){
statements(s)
}

else if (<condition N>)


statements(s)
}
else {
statements(s)
}
21.10.2015

Advanced Software Engineering

36

Control Flow Statements


A complex example
public class IfElseDemo {
public static void main(String[] args) {
int testscore = 76;
char grade;
if (testscore >= 90) {
grade = 'A';
} else if (testscore >= 80) {
grade = 'B';
} else if (testscore >= 70) {
grade = 'C';
} else {
grade = 'F';
}
System.out.println("Grade = " + grade);
}
}
21.10.2015

Advanced Software Engineering

37

Control Flow Statements


Switch statement I

Arbitrary number of execution paths


Only discrete values are allowed
Variable types: byte, short, int, char
Tests expression based on a single integer or character

Structure of a switch statement


switch(<variable>){
case <value1>:
case <value2>:
case <value3>:

default:
}
21.10.2015

//instruction
//instruction
//instruction
//instruction

Advanced Software Engineering

38

Control Flow Statements


Switch statement II
Case translates to search for match and then execute every following
instruction (aka fall through)
Break terminates enclosing switch statement
Default handles values not handled by case sections

Example of a switch statement with break


int gear = 2;
String gearString;
switch (gear) {
case 1: gearString = "low"; break;
case 2: gearString = "medium"; break;
case 3: gearString = "high"; break
default: gearString = "undefined; break;
}
System.out.println(gearString);
21.10.2015

Advanced Software Engineering

Output:
medium
Without
break?
39

Control Flow Statements


Switch statement II
Case translates to search for match and then execute every following
instruction (aka fall through)
Break terminates enclosing switch statement
Default handles values not handled by case sections

Example of a switch statement without break


int gear = 2;
String gearString;
switch (gear) {
case 1: gearString = "low";
case 2: gearString = "medium";
case 3: gearString = "high";
default: gearString = "undefined";
}
System.out.println(gearString);
21.10.2015

Advanced Software Engineering

Output:
undefined

40

Control Flow Statements


for statement
Aka the for loop
Provides a way to iterate over a range of values
Terminates if a certain condition applies

Structure of a for statement


for (initialization; termination; increment) {
statement(s)
}

Initialization expression initializes the loop; executed once.


Loop terminates if termination evaluates to false
The increment is invoked after each iteration. Can also be a decrement.
21.10.2015

Advanced Software Engineering

41

Control Flow Statements


Example of a for statement I
public class LoopDemo{
public static void main(String[] args) {

Output:
Loop 0
Loop 1

Loop 14

for (int i = 0; i < 15; i++){

System.out.println("Loop "+i);
}
}

21.10.2015

Advanced Software Engineering

42

Control Flow Statements


Example of a for statement II
public class LoopDemo{
public static void main(String[] args) {
for (int i = 10; i > 0; i--){

System.out.println("Countdown "+i);
Output:
Countdown 10
Countdown 9

Countdown 1

}
}

21.10.2015

Advanced Software Engineering

43

Control Flow Statements


Example of an (odd) for statement III
public class LoopDemo{
public static void main(String[] args) {
for ( ; ; ){

Infinite
Output:
Loop
Loop

Loop

System.out.println("Loop");
}
}

21.10.2015

The three
expressions
are optional!

Advanced Software Engineering

44

Control Flow Statements


while statement
Executes statements while particular expression is true
If expression evaluates to false the execution stops
The expression is evaluated before every execution

Structure of a while statement


while(expression) {
statement(s)
}

21.10.2015

Advanced Software Engineering

45

Control Flow Statements


Example of a while statement
public class WhileDemo {
public static void main(String[] args){
int count = 1;

Output:
Count 1
Count 2

Count 10

while (count < 11) {


System.out.println("Count: " + count);
count++;
}
}
}

21.10.2015

Advanced Software Engineering

46

Control Flow Statements


do-while statement
Executes statements while particular expression is true
If expression evaluates to false the execution stops
The expression is evaluated after every execution. It always executes at least
once!
Notice the ; after the while statement!

Structure of a do-while statement


do {
statement(s)
}
while(expression);
21.10.2015

Advanced Software Engineering

47

Control Flow Statements


Example of a do-while statement
public class WhileDemo {
public static void main(String[] args){

Output:
Count 1

int count = 1;
do {
System.out.println("Count: " + count);

}
while (count < 1);
}
}

21.10.2015

Advanced Software Engineering

48

Control Flow Statements


Three branching statements
break: Instantly terminates a switch, for, while or do-while execution
continue: Skips the current iteration of a for, while or do-while
return: Exits from the current method. Used to return a value in case of non
void methods.

Example of continue statement


while (readNext(line)) {
if (line.isEmpty() || line.isComment())
continue;
// More code here
}

21.10.2015

Advanced Software Engineering

49

Control Flow Statements


Summary of control flow statements
Statement

Features

if-then-else

Executes section of code if test


evaluates to true. If test evaluates to
false else branch is executed.

switch

Arbitrary number of execution paths are


possible.

while

Continually executes a block of code


while condition is true. Evaluates at top.

while-do

Evaluates at bottom. Runs at least once.

for

Loops over a range of values.

break, continue, return

Instantly terminates flow or continues the


next iteration. Exits the current method.

21.10.2015

Advanced Software Engineering

50

Arrays
Recap and Motivation
Primitive data types (e.g. int) can only hold a single value
E.g. int val = 17;

Array Features

Arrays can hold multiple values (or elements)!


Can only hold one data type, i.e. no mixture of data types (e.g. int and char)
Length is established upon creation
After that its fixed!
Access to elements via index
Index starts with 0. That is, the first array element has the index 0:

21.10.2015

Advanced Software Engineering

51

Arrays
Two ways of array creation (Examples)
Initialize with values (e.g. six): int[] array1 = {1,2,3,4,5,6};
Declaration (e.g. length nine): int[] array2 = new int[9];

Access to elements I
public static void main(String[] args) {
int[] ar = new int[3];
ar[0] = 100;
ar[1] = 200;
ar[2] = 300;
System.out.println("Array value on pos 1:" +ar[0]);
System.out.println("Array value on pos 2:" +ar[1]);
System.out.println("Array value on pos 3:" +ar[2]);
}

21.10.2015

Advanced Software Engineering

52

Arrays
Access to elements II
public static void main(String[] args) {
int[]
ar[0]
ar[1]
ar[2]

ar = new int[3];
= 100;
= 200;
= 300;

Determines the
size of the array

for (int idx = 0; idx < ar.length; idx++){


System.out.println(ar[idx]);
}
}

21.10.2015

Advanced Software Engineering

53

Arrays
Multi dimensional arrays are possible
Example: Positions on a chessboard or a Matrix
Are realized with arrays of arrays
int[][] chessboard = new int[8][8];

21.10.2015

Advanced Software Engineering

54

Arrays
For the curious mind You can declare the following arrays:

byte[] anArrayOfBytes;
short[] anArrayOfShorts;
long[] anArrayOfLongs;
float[] anArrayOfFloats;
double[] anArrayOfDoubles;
boolean[] anArrayOfBooleans;
char[] anArrayOfChars;
String[] anArrayOfStrings;

21.10.2015

Advanced Software Engineering

55

Strings
Recap and Motivation

Single characters can be presented as char


E.g. char c = 'd';
How can names, passwords etc. be presented?
Nave approach: As char arrays. Drawbacks (arrays are fixed length)

String features
Keyword String
Strings are denoted by quotation marks, e.g. "A String"
Example: String name = "RWTH";

21.10.2015

Advanced Software Engineering

56

Upcoming Lecture
Outlook
Well continue with basics Java concepts
take a closer look at Methods
and well introduce the core concept of Java: Objects!

In the meantime
Make yourself familiar with todays topics
check the web for Java tutorials
theres a ton of Java Books out there.

21.10.2015

Advanced Software Engineering

57

Thank you for your attention!

You might also like