2 Lecture Two
2 Lecture Two
‹#›
What is Java? [Recap]
‹#›
Software Development with Java
● All source code is first written in plain text files ending with the “.java”
extension.
● Those source files are then compiled into “.class” files by the javac compiler.
● A “.class” file does not contain code that is native to your processor; it
instead contains bytecodes — the machine language of the Java Virtual
Machine (Java VM).
● The java launcher tool then runs your application with an instance of the
Java Virtual Machine, i.e. your code is run by JVM.
http://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html ‹#›
Platform Independence:
Write Once Run Anywhere
● Because the Java VM is available on many different operating systems, the
same .class files are capable of running on Microsoft Windows, the Solaris™
Operating System (Solaris OS), Linux, or Mac OS.
http://docs.oracle.com/javase/tutorial/getStarted/intro/definition.html ‹#›
The Java Platform
● A platform is the hardware or software environment in which a program runs.
● The Java platform has two components:
●The Java Virtual Machine: It's the base for the Java platform
and is ported onto various hardware-based platforms
●The Java Application Programming Interface (API): It is a large
collection of ready-made software components that provide
many useful capabilities.
‹#›
Basic Programming Elements
● Variables, Types and Expressions
● Flow of Control
● Branching
● Loops
‹#›
Variables
● Variables in a program are used to store data such as numbers
and letters. They can be thought of as containers of a sort.
● You should choose variable names that are helpful. Every
variable in a Java program must be declared before it is used for
the first time.
● A variable declaration consists of a type name, followed by a list
of variable names separated by commas. The declaration ends
with a semicolon.
Syntax:
char answer;
‹#›
Primitive Data Types
There are also Class Data Types which we will cover later.
‹#›
Identifiers
● The technical term for a name in a programming language, such as
the name of a variable, is an identifier.
● An identifier can contain only letters, digits 0 through 9, and the
underscore character “_”.
● The first character in an identifier cannot be a digit.
● There is no limit to the length of an identifier.
● Java is case sensitive (e.g., personName, PERSONNAME and
personname are two different variables).
Identifier Valid?
Yes
outputStream No
No
4you
Yes
my.work Yes
public is a
FirstName No
reserved word.
_tmp ‹#›
Java Reserved Words
‹#›
Naming Conventions
● Class types begin with an uppercase letter (e.g. String).
‹#›
Assignment Statements
● An assignment statement is used to assign a value to a variable.
● The "equal sign" is called the assignment operator
● Syntax:
variable_name = expression;
amount = 100;
interestRate = 0.12;
answer = ‘Y’;
‹#›
Initializing Variables
● A variable that has been declared, but not yet given a value is said to
be uninitialized.
● Uninitialized class variables have the value null.
● Uninitialized primitive variables may have a default value.
‹#›
Imprecision in Floating Point Numbers
● Floating-point numbers often are only approximations since
they are stored with a finite number of bits.
‹#›
Named Constants
● Java provides a mechanism that allows you to define a variable,
initialise it, and moreover fix the variable’s value so that it
cannot be changed.
‹#›
Assignment Compatibility
● Java is strongly typed.
● A value of one type can be assigned to a variable of any type further to the
right (not to the left):
‹#›
Type Conversion (Casting)
● Implicit conversion
int intVariable = 5; // 5
● Explicit conversion
‹#›
Operators and Precedence
● Precedence
● First: The unary operators: plus (+), minus(-), not (!), increment (++) and
decrement (--)
● Second: The binary arithmetic operators: multiplication (*), integer division (/)
and modulus (%)
● Third: The binary arithmetic operators: addition (+) and subtraction (-)
‹#›
Operators and Precedence - Example
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, ‹#›
Arrays
● Array is a sequence of values.
● Array indices begin at zero.
● Defining Arrays
int[] numbers;
numbers = new int[100];
● Initialising Arrays
‹#›
Strings
● A value of type String is a
● Sequence (Array) of characters treated as a single item
● Character positions start with 0
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, ‹#›
Concatenating Strings
● You can connect—or join or paste—two strings together to
obtain a larger string. This operation is called concatenation and
is performed by using the “+” operator.
‹#›
Boolean Type
● Java has the logical type boolean
‹#›
Java Comparison Operators
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, ‹#›
Java Logical Operators
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, ‹#›
Flow of Control
● Flow of control is the order in which a program performs
actions.
‹#›
Basic if Statement
● Syntax
if (Expression)
Action
‹#›
if-else Statement
● Syntax
if (Expression)
Action1
else
Action2
● If Expression is true then execute Action1 otherwise execute
Action2
● The actions are either a single statement or a list of statements
within braces
int maximum;
if (value1 < value2) { // is value2 larger?
maximum = value2; // yes: value2 is larger
}
else { // (value1 >= value2)
maximum = value1; // no: value2 is not larger
}
‹#›
if-else Statement
● If statements can be nested (also called as multi-way, multi-
branch if statement)
if (a == ‘0’)
System.out.println (“zero”);
else if (a == ‘1’)
System.out.println (“one”);
else if (a == ‘2’)
System.out.println (“two”);
else if (a == ‘3’)
System.out.println (“three”);
else if (a == ‘4’)
System.out.println (“four”);
else
System.out.println (“five+”);
‹#›
Switch Statement
● Switch statement can be used instead of multi-way if statement.
● Syntax
switch(controlling_expression) {
case expression1:
action1;
break;
case expression2:
action2;
break;
…
default:
actionN;
}
switch (a) {
case ‘0’:
System.out.println (“zero”); break;
case ‘1’:
System.out.println (“one”); break;
case ‘2’:
System.out.println (“two”); break;
case ‘3’:
System.out.println (“three”); break;
case ‘4’:
System.out.println (“four”); break;
default:
System.out.println (“five+”); break;
}
‹#›
The Conditional (Ternary) Operator
● The ? and : together are called the conditional operator or
ternary operator.
‹#›
for Loops
● The for loop is a pretest loop statement. It has the following
form.
‹#›
Varying Control Variable
● for ( int i = 1; i <= 100; i++ )
● from 1 to 100 in increments of 1
‹#›
For Loop Example
String[] classList = {"Jean", "Claude", "Van",
"Damme"};
‹#›
While Loop
● The while loop is a pretest loop statement. It has the following
form.
while (boolean-expression) {
nested-statements
}
‹#›
While Loop Example
int[] numbers = { 1, 5, 3, 4, 2 };
int i=0, key
key == 33;
3; Let’s look for something that does not
exist.
boolean found = false;
if (found)
System.out.println("Key is found in the array");
else
System.out.println("Key is NOT found!");
‹#›
While Loop Example
int[] numbers = { 1, 5, 3, 4, 2 };
int i=0, key
key == 33;
3;
if (found)
System.out.println("Key is found in the array");
else
System.out.println("Key is NOT found!");
Figure from “Java - An Introduction to Problem Solving and Programming, Walter Savitch, ‹#›
Do-While Loop
● The do-while loop is a post-test loop statement. It has the
following form.
do {
nested-statements
} while (boolean-expression);
‹#›
Do-While Example
do {
System.out.println(
"Enter a number between 0 and 100: ");
myNumber = scan.nextInt();
‹#›
Break Statement
● The break statement is used in loop (for, while, and do-while)
statements and switch statements to terminate execution of the
statement. A break statement has the following form.
break;
‹#›
Continue Statement
● A continue statement
● Ends current loop iteration
● Begins the next one
‹#›
Breaking a Loop
int[] numbers = { 1, 5, 3, 4, 2 };
int i = 0, key = 3;
if (i < numbers.length)
System.out.println("Key is found in the array");
else
System.out.println("Key is NOT!");
‹#›
Object-Oriented Paradigm -Review
●Centered on the concept of the object
●Object
● Physical entity
Truck
Bank
Account
● Conceptual entity Chemical
Process
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
What is Really an Object?
●Formally, an object is a concept, abstraction, or thing with sharp
boundaries and meaning for an application.
‹#›
What is a Class?
●A class is a description of a group of objects with common
properties (attributes), behavior (operations), relationships, and
semantics
● An object is an instance of a class
‹#›
Example Class
Class
Course
Attributes Behavior
Name Add a student
Location Delete a student
a + b = 10
Days offered Get course roster
Credit hours Determine if it is
Start time full
End time
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Representing Classes
●A class is represented using a compartmented rectangle
Professor a + b = 10
Professor
Clark
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Class Compartments
●A class is comprised of three sections
● The first section contains the class name
● The second section shows the structure (attributes)
● The third section shows the behavior (operations)
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
How Many Classes do you See?
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Relationship between Classes and Objects
●A class is an abstract definition of an object
● It defines the structure and behavior of each object in the
class
● It serves as a template for creating objects
●Objects are grouped into classes
Objects Class
Professor
Professor
Professor Mellon
Smith
Professor
Jones
‹#›
State of an Object (property or attribute)
●The state of an object encompasses all of the (usually static)
properties of the object plus the current (usually dynamic)
values of each of these properties.
Object Attribute
Value
Class
CourseOffering
number = 101
startTime = 9:00
CourseOffering endTime = 11:00
Attribute
number
startTime
endTime CourseOffering
number = 104
startTime = 13:00
endTime = 15:00
‹#›
Behavior of an Object (operation or method)
●Behavior is how an object acts and reacts, in terms of its state
changes and message passing.
Class CourseOffering
addStudent
Operation deleteStudent
getStartTime
getEndTime
‹#›
Identity of an Object
●Each object has a unique identity, even if the state is identical to
that of another object.
OOAD Using the UML - Introduction to Object Orientation, v 4.2, 1998-1999 Rational Software ‹#›
Sample Class: Automobile
● Attributes
● manufacturer’s name
● model name
● year made
● color
● number of doors
● size of engine
● Methods
● Define attributes (specify manufacturer’s name, model, year, etc.)
● Change a data item (color, engine, etc.)
● Display data items
● Calculate cost
‹#›
Sample Class: Circle
●Attributes
● Radius
● Center Coordinates
●X and Y values
●Methods
● Define attributes (radius and center coordinates)
● Find area of the circle
● Find circumference of the circle
‹#›
Summary
●So far, we covered basics of objects and object oriented paradigm.
● We tried to think in terms of objects.
●We will continue next week with actually creating objects by using
Java.
‹#›