IFI7184.DT – Lesson 1
Introduction and contextualization
@ slides adapted from Isaías da Rosa sources
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
2@ Sonia Sousa2015
Java programming language
• Dynamic Web applications
– Servlets, JSP
• Native applications
– Android and blackberry
• Java is not
– Javascript
– Native IOS
@ Sonia Sousa 32015
Java is…
• A complied language
– Has restrictive rules but is not difficult
• Similar languages
– C, C + +, c#, Javascript, PHP
• Although…
– You need to understand
• Rules – basic programming vocabulary
• The principles of object-oriented language
@ Sonia Sousa 42015
First steps on Java
• Basic Structure
– Object-oriented concepts
• Understand programming concepts like
– What is a statement
– What is a variable
– What is a function
– What is a condition
@ Sonia Sousa 52015
Development Environments
• Applications that support Java development:
– Eclipse SE Development Kit (JDK)
• Runtime, compiler and other tools
– NetBeans
– BlueJ
• Though the details of these environments
differ,
– the basic compilation and execution process is
essentially the same
6@ Sonia Sousa2015
Java Translation
• Java is an
– interpreted language
– Is portable
• The Java compiler translates into
– Java bytecode
• We will use a Java virtual machine
– Eclipse
7
Java source
code Java
bytecode
Java
compiler
@ Sonia Sousa2015
Basic Program Development
errors?
errors?
Edit and
save program
Compile program
Execute program and
evaluate results
8@ Sonia Sousa2015
Runtime Architecture
2015 @ Sonia Sousa 9
Operating System
Java Virtual Machine (JVM)
Core runtime and additional libraries
Compiled bytecode
Java Translation
Java source
code
Machine
code
Java
bytecode
Bytecode
interpreter
Bytecode
compiler
Java
compiler
10@ Sonia Sousa2015
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
11@ Sonia Sousa2015
Object-oriented concepts
• What is an Object?
– An object-oriented -> aims to -> model real-world
objects
• examples of real-world objects: dog, desk, computer,
bicycle
– Characteristics of real-world object
• have state and behaviour
– State = name, color, breed, hungry
– Behaviour = barking, fetching, wagging tail
@ Sonia Sousa 122015
A bicycle modeled as a object
State
Variables (fields)
behaviours
functions (methods)
speed
Pedal cadence
gear
that allow to change the state
Function to change the gear (bicycle has 3 gears)
1. Reject values < 1
or > than 3
2. Verify what is the
current gear
3. Change the gear
@ Sonia Sousa 132015
What we know
• What are variables -> state
– state of an object in real-world
• What are functions (methods) -> behaviours
– Behaviour of that object in real world
• But…
– Take the bicycle example
• 1 model/brand can have similar types of bicycle
• How to represent in object-oriented terms?
– Using classes
@ Sonia Sousa 142015
What Is a Class?
• A Class represent 1 object (bicycle)
– or 1 or more objects (bicycles)
• Objects with similar characteristics of Object bicycle:
– Same model, same company, same set of blueprints, same
components
Instance
Of
class of objects known as bicycles
@ Sonia Sousa 152015
object
What Is a Inheritance?
• Represent 1 object (bicycle)
– Which shares
• general and specific characteristics
– Object bicycle:
• Shared characteristics
– class bicycles
• Specific characteristics
– superclass – MountainBike and TandemBike
– How do you represent as object term?
inherit
characteristics
class of objects known as bicycles
Superclass of objects known as specific characteristic
A class in java
• Java includes a library of classes
• Java program is made of an aggregation of
– 1 or + classes - package
– Most common used is
• Java.lang (Packages)
• Search on google for java 6 api docs
• We are going to use
– The System class -> belongs to Java.lang
– The out variable -> PrintStream class -> System class
– Print method - println
@ Sonia Sousa 172015
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
18@ Sonia Sousa2015
Java Development kit
• Includes
– Compiler - command javac
– Runtime - java
– Package - jar
– Documentation builder - javadoc
2015 @ Sonia Sousa 19
Java Application
• Consists
– Of many classes (.java) – command line runtime
– The packager (jar) – aggregates the many
classes
– The javadoc – the documentation builder
– The command line compiler - javac
2015 @ Sonia Sousa 20
First step
• Set up the workspace
• Create 1 application
– Create a project
– SRC AND BIN folders
• Every Java App Is Build Inside A Class
• Create a new class
– System.out.println(“Hello World”)
– Compile or run java application
@ Sonia Sousa 212015
Eclipse IDE
@ Sonia Sousa 222015
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world" );
}
}
Java Program Structure
23
Hello World!
Class declaration
File name: HelloWorld.java Java is Case sensitive Language
=
Main method
Executable code
Compile results
File sources
HelloWorld.class
HelloWorld.java
Bytecode file
@ Sonia Sousa2015
Java syntax
The method can
be called
anywhere
A method contains
1 program statements
public class MyProgram
{
}
// comments about the class
public static void main (String[] args)
{
}
// Main method declaration
method header
method body
Don’t have to
create a
instance of a
class
Do not return
anything from
the class
@ Sonia Sousa 242015
New public
class called
MyProgram
class
body
The println Method
• The println method prints a character
string
• The System.out object represents a
destination (the monitor screen) to which
we can send output
25
System.out.println ("Whatever you are, be a good one.");
information provided
(arguments)
@ Sonia Sousa2015
Resulting files
2015 @ Sonia Sousa 26
Errors
• A program can have three types of errors
1) Compile-time errors
• The compiler will find syntax errors and other basic
problems
• If compile-time errors exist, an executable version of the
program is not created
2) Run-time errors
• A problem can occur during program execution, such as
– trying to divide by zero, which causes a program to terminate
abnormally
3) Logical errors
• A program may run, but produce incorrect results, perhaps
using an incorrect formula
2015 @ Sonia Sousa 27
DEMO
@ Sonia Sousa 282015
Comments
• Comments should always be included
– To explain the purpose of the program; and
– Describe processing steps.
• They do not affect how a program works
• Java comments can take three forms:
29
// this comment runs to the end of the line
/* this comment runs to the terminating
symbol, even across line breaks */
/** this is a javadoc comment */
@ Sonia Sousa2015
Java is Case sensitive
• Java is case sensitive:
– Total, total, and TOTAL are different
identifiers
• Rules on how to…
– use different case styles for different types of
identifiers
• Class names start with upper case – MyProgram
• Variables with lower case - value
@ Sonia Sousa 302015
Reserved words
• Identifiers with a predefined meaning in the
language
– println
• A reserved word cannot be used in any
other way
@ Sonia Sousa 312015
Reserved Words
• The Java reserved words:
32
abstract
assert
boolean
break
byte
case
catch
char
class
const
continue
default
do
double
else
enum
extends
false
final
finally
float
for
goto
if
implements
import
instanceof
int
interface
long
native
new
null
package
private
protected
public
return
short
static
strictfp
super
switch
synchronized
this
throw
throws
transient
true
try
void
volatile
while
@ Sonia Sousa2015
EXERCISE 1
@ Sonia Sousa 332015
Quick Check
Which of the following are valid Java identifiers?
grade
quizGrade
NetworkConnection
frame2
3rdTestScore
MAXIMUM
MIN_CAPACITY
student#
Shelves1&2
34@ Sonia Sousa2015
Quick Check
Which of the following are valid Java identifiers?
grade
quizGrade
NetworkConnection
frame2
3rdTestScore
MAXIMUM
MIN_CAPACITY
student#
Shelves1&2
Valid
Valid
Valid
Valid
Invalid – cannot begin with a digit
Valid
Valid
Invalid – cannot contain the '#' character
Invalid – cannot contain the '&' character
35@ Sonia Sousa2015
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
36@ Sonia Sousa2015
Character Strings
• A string literal is represented by putting
double quotes around the text
• Examples:
"This is a string literal."
"123 Main Street"
"X”
37@ Sonia Sousa2015
EXERCISE 2
@ Sonia Sousa 382015
//********************************************************************
// Countdown.java Author: Lewis/Loftus
//
// Demonstrates the difference between print and println.
//********************************************************************
public class Countdown
{
//-----------------------------------------------------------------
// Prints two lines of output representing a rocket countdown.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!"); // appears on first output line
System.out.println ("Houston, we have a problem.");
}
}
39@ Sonia Sousa2015
//********************************************************************
// Countdown.java Author: Lewis/Loftus
//
// Demonstrates the difference between print and println.
//********************************************************************
public class Countdown
{
//-----------------------------------------------------------------
// Prints two lines of output representing a rocket countdown.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.print ("Three... ");
System.out.print ("Two... ");
System.out.print ("One... ");
System.out.print ("Zero... ");
System.out.println ("Liftoff!"); // appears on first output line
System.out.println ("Houston, we have a problem.");
}
}
Output
Three... Two... One... Zero... Liftoff!
Houston, we have a problem.
40@ Sonia Sousa2015
String Concatenation
• The string concatenation operator (+) is
used to append one string to the end of
another
"Peanut butter " + "and jelly"
• It can also be used to append a number to
a string
• A string literal cannot be broken across
two lines in a program
41@ Sonia Sousa2015
EXERCISE 3
@ Sonia Sousa 422015
//********************************************************************
// Facts.java Author: Lewis/Loftus
//
// Demonstrates the use of the string concatenation operator and the
// automatic conversion of an integer to a string.
//********************************************************************
public class Facts
{
//-----------------------------------------------------------------
// Prints various facts.
//-----------------------------------------------------------------
public static void main (String[] args)
{
// Strings can be concatenated into one long string
System.out.println ("We present the following facts for your "
+ "extracurricular edification:");
System.out.println ();
// A string can contain numeric digits
System.out.println ("Letters in the Hawaiian alphabet: 12");
continue
43@ Sonia Sousa2015
continue
// A numeric value can be concatenated to a string
System.out.println ("Dialing code for Antarctica: " + 672);
System.out.println ("Year in which Leonardo da Vinci invented "
+ "the parachute: " + 1515);
System.out.println ("Speed of ketchup: " + 40 + " km per year");
}
}
44@ Sonia Sousa2015
continue
// A numeric value can be concatenated to a string
System.out.println ("Dialing code for Antarctica: " + 672);
System.out.println ("Year in which Leonardo da Vinci invented "
+ "the parachute: " + 1515);
System.out.println ("Speed of ketchup: " + 40 + " km per year");
}
}
Output
We present the following facts for your extracurricular edification:
Letters in the Hawaiian alphabet: 12
Dialing code for Antarctica: 672
Year in which Leonardo da Vinci invented the parachute: 1515
Speed of ketchup: 40 km per year
45@ Sonia Sousa2015
String Concatenation
• The + operator is also used for arithmetic addition
– The function that it performs depends on the type of the
information on which it operates
• If both operands are strings, or if one is a string and one is a
number,
– it performs string concatenation
• If both operands are numeric, it adds them
• The + operator is evaluated left to right, but parentheses
can be used to force the order
46@ Sonia Sousa2015
EXERCISE 4
@ Sonia Sousa 472015
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************
public class Addition
{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);
System.out.println ("24 and 45 added: " + (24 + 45));
}
}
48@ Sonia Sousa2015
//********************************************************************
// Addition.java Author: Lewis/Loftus
//
// Demonstrates the difference between the addition and string
// concatenation operators.
//********************************************************************
public class Addition
{
//-----------------------------------------------------------------
// Concatenates and adds two numbers and prints the results.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("24 and 45 concatenated: " + 24 + 45);
System.out.println ("24 and 45 added: " + (24 + 45));
}
}
Output
24 and 45 concatenated: 2445
24 and 45 added: 69
49@ Sonia Sousa2015
EXERCISE 5
@ Sonia Sousa 502015
Quick Check
• What output is produced by the following?
51
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);
@ Sonia Sousa2015
Quick Check
X: 25
Y: 65
Z: 30050
52
• What output is produced by the following?
System.out.println ("X: " + 25);
System.out.println ("Y: " + (15 + 50));
System.out.println ("Z: " + 300 + 50);
@ Sonia Sousa2015
EXERCISE 6
@ Sonia Sousa 532015
Quick Check
• What output is produced by the following?
54
System.out.println ("I said "Hello" to you.");
@ Sonia Sousa2015
Quick Check
An escape sequence begins with a backslash
character ()
System.out.println ("I said "Hello" to you.");
55
• The compiler becomes confuse
– would interpret the second quote as the end
of the string
System.out.println ("I said "Hello" to you.");
@ Sonia Sousa2015
EXERCISE 7
@ Sonia Sousa 562015
Escape Sequences
• Some Java escape sequences:
57
Escape Sequence
b
t
n
r
"
'

Meaning
backspace
tab
newline
carriage return
double quote
single quote
backslash
@ Sonia Sousa2015
//********************************************************************
// Roses.java Author: Lewis/Loftus
//
// Demonstrates the use of escape sequences.
//********************************************************************
public class Roses
{
//-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,” + “Violets are blue," +
"Sugar is sweet,ntBut I have "commitment issues",nt" +
"So I'd rather just be friendsntAt this point in our " +
"relationship.");
}
}
58@ Sonia Sousa2015
//********************************************************************
// Roses.java Author: Lewis/Loftus
//
// Demonstrates the use of escape sequences.
//********************************************************************
public class Roses
{
//-----------------------------------------------------------------
// Prints a poem (of sorts) on multiple lines.
//-----------------------------------------------------------------
public static void main (String[] args)
{
System.out.println ("Roses are red,ntViolets are blue,n" +
"Sugar is sweet,ntBut I have "commitment issues",nt" +
"So I'd rather just be friendsntAt this point in our " +
"relationship.");
}
}
Output
Roses are red,
Violets are blue,
Sugar is sweet,
But I have "commitment issues",
So I'd rather just be friends
At this point in our relationship.
59@ Sonia Sousa2015
EXERCISE 8
@ Sonia Sousa 602015
Quick Check
• Write a single println statement that
produces the following output:
61
"Thank you all for coming to my home
tonight," he said mysteriously.
@ Sonia Sousa2015
• Write a single println statement that
produces the following output:
Quick Check
"Thank you all for coming to my home
tonight," he said mysteriously.
System.out.println (""Thank you all for " +
"coming to my homentonight," he said " +
"mysteriously.");
62@ Sonia Sousa2015
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
63@ Sonia Sousa2015
EXERCISE 9
@ Sonia Sousa 642015
Variables
• A variable is a name for a
– location in memory that holds a value
• When you declare a variable (variable declaration)
– you need to specify
65
int total;
int count, temp, result;
Multiple variables can be created in one declaration
data type variable name
@ Sonia Sousa2015
Variable Initialization
• You can add a initial value to your variable
66
int sum = 0;
int base = 32, max = 149;
data type variable name variable value = 0
@ Sonia Sousa2015
EXERCISE 10
@ Sonia Sousa 672015
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus
//
// Demonstrates the declaration, initialization, and use of an
// integer variable.
//********************************************************************
public class PianoKeys
{
//-----------------------------------------------------------------
// Prints the number of keys on a piano.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int keys = 88;
System.out.println ("A piano has " + keys + " keys.");
}
}
68@ Sonia Sousa2015
//********************************************************************
// PianoKeys.java Author: Lewis/Loftus
//
// Demonstrates the declaration, initialization, and use of an
// integer variable.
//********************************************************************
public class PianoKeys
{
//-----------------------------------------------------------------
// Prints the number of keys on a piano.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int keys = 88;
System.out.println ("A piano has " + keys + " keys.");
}
}
Output
A piano has 88 keys.
69@ Sonia Sousa2015
Assignment
• An assignment statement
– Changes the value of a variable
• What happens?
• The value that was in total is overwritten
• You need to assign a value to a variable = variable's declared type
• Int , byte, short, long, float, double, boolean, char
• See more about primitive Data types
70
total = 55;
Assignment operator
@ Sonia Sousa2015
EXERCISE 11
@ Sonia Sousa 712015
//********************************************************************
// Geometry.java Author: Lewis/Loftus
//
// Demonstrates the use of an assignment statement to change the
// value stored in a variable.
//********************************************************************
public class Geometry
{
//-----------------------------------------------------------------
// Prints the number of sides of several geometric shapes.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int sides = 7; // declaration with initialization
System.out.println ("A heptagon has " + sides + " sides.");
sides = 10; // assignment statement
System.out.println ("A decagon has " + sides + " sides.");
sides = 12;
System.out.println ("A dodecagon has " + sides + " sides.");
}
}
72@ Sonia Sousa2015
//********************************************************************
// Geometry.java Author: Lewis/Loftus
//
// Demonstrates the use of an assignment statement to change the
// value stored in a variable.
//********************************************************************
public class Geometry
{
//-----------------------------------------------------------------
// Prints the number of sides of several geometric shapes.
//-----------------------------------------------------------------
public static void main (String[] args)
{
int sides = 7; // declaration with initialization
System.out.println ("A heptagon has " + sides + " sides.");
sides = 10; // assignment statement
System.out.println ("A decagon has " + sides + " sides.");
sides = 12;
System.out.println ("A dodecagon has " + sides + " sides.");
}
}
Output
A heptagon has 7 sides.
A decagon has 10 sides.
a dodecagon has 12 sides.
73@ Sonia Sousa2015
Constants
• A constant is an identifier
– that is similar to a variable except that it holds the
same value during its entire existence
• As the name implies, it is constant, not variable
• The compiler will issue an error if you try to
change the value of a constant
• In Java, we use the final modifier to declare a
constant
final int MIN_HEIGHT = 69;
74@ Sonia Sousa2015
Constants
• Constants are useful for three important reasons
1) First, they give meaning to otherwise unclear literal
values
• Example: MIN_HEIGHT means more than the literal 69
2) Second, they facilitate program maintenance
• If a constant is used in multiple places, its value need only be
set in one place
3) Third, they formally establish that a value should not
change,
• Avoiding inadvertent errors by other programmers
2015 @ Sonia Sousa 75
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
76@ Sonia Sousa2015
Primitive Data
• There are eight primitive data types in Java
• Four of them represent integers:
– byte, short, int, long
• Two of them represent floating point numbers:
– float, double
• One of them represents characters:
– char
• And one of them represents boolean values:
– boolean
2015 @ Sonia Sousa 77
Most common Types
• int
– integer (most common. no decimal)
• long
– holds a really big integer
• float
– accurate up to 7 decimal places
• double
– accurate up to 15 decimal places I do believe (at work and don't have a book)
• boolean
– false or true (also 1 = true, 0 = false)
• string
– anything from numbers to letters to whole sentences. It will take the input
literately.
• char
– character, such as f or 6 or 
2015 @ Sonia Sousa 78
Numeric Primitive Data
• The difference between the numeric
primitive types is their size and the values
they can store:
2015 @ Sonia Sousa 79
Type
byte
short
int
long
float
double
Storage
8 bits
16 bits
32 bits
64 bits
32 bits
64 bits
Min Value
-128
-32,768
-2,147,483,648
< -9 x 1018
- 3.4 x 1038 3.4 x 1038
- 1.7 x 10308 1.7 x 10308
Max Value
127
32,767
2,147,483,647
> 9 x 1018
Characters
• A char variable stores a single character
• Character literals are delimited by single quotes:
'a' 'X' '7' '$' ',' 'n'
• Example declarations:
char topGrade = 'A';
char terminator = ';', separator = ' ';
• Note the difference between
– a primitive character variable, which holds only one
character, and
– a String object, which can hold multiple characters
2015 @ Sonia Sousa 80
Character Sets
• A character set is an ordered list of characters,
with each character corresponding to a unique
number
• A char variable in Java can store any character
from the Unicode character set
• The Unicode character set uses sixteen bits per
character, allowing for 65,536 unique characters
• It is an international character set, containing
symbols and characters from many world
languages
2015 @ Sonia Sousa 81
Characters
• The ASCII character set is older and smaller
than Unicode, but is still quite popular
• The ASCII characters are a subset of the
Unicode character set, including:
2015 @ Sonia Sousa 82
uppercase letters
lowercase letters
punctuation
digits
special symbols
control characters
A, B, C, …
a, b, c, …
period, semi-colon, …
0, 1, 2, …
&, |, , …
carriage return, tab, ...
Boolean
• A boolean value represents a true or false
condition
• The reserved words true and false are
the only valid values for a boolean type
boolean done = false;
• A boolean variable can also be used to
represent any two states, such as a light bulb
being on or off
2015 @ Sonia Sousa 83

IFI7184.DT lesson1- Programming languages

  • 1.
    IFI7184.DT – Lesson1 Introduction and contextualization @ slides adapted from Isaías da Rosa sources
  • 2.
    Outline Java programing language Object-orientedconcepts Java IDEs Eclipse working environment Variables and Types Strings Variables and Assignment Primitive Data Types 2@ Sonia Sousa2015
  • 3.
    Java programming language •Dynamic Web applications – Servlets, JSP • Native applications – Android and blackberry • Java is not – Javascript – Native IOS @ Sonia Sousa 32015
  • 4.
    Java is… • Acomplied language – Has restrictive rules but is not difficult • Similar languages – C, C + +, c#, Javascript, PHP • Although… – You need to understand • Rules – basic programming vocabulary • The principles of object-oriented language @ Sonia Sousa 42015
  • 5.
    First steps onJava • Basic Structure – Object-oriented concepts • Understand programming concepts like – What is a statement – What is a variable – What is a function – What is a condition @ Sonia Sousa 52015
  • 6.
    Development Environments • Applicationsthat support Java development: – Eclipse SE Development Kit (JDK) • Runtime, compiler and other tools – NetBeans – BlueJ • Though the details of these environments differ, – the basic compilation and execution process is essentially the same 6@ Sonia Sousa2015
  • 7.
    Java Translation • Javais an – interpreted language – Is portable • The Java compiler translates into – Java bytecode • We will use a Java virtual machine – Eclipse 7 Java source code Java bytecode Java compiler @ Sonia Sousa2015
  • 8.
    Basic Program Development errors? errors? Editand save program Compile program Execute program and evaluate results 8@ Sonia Sousa2015
  • 9.
    Runtime Architecture 2015 @Sonia Sousa 9 Operating System Java Virtual Machine (JVM) Core runtime and additional libraries Compiled bytecode
  • 10.
  • 11.
    Outline Java programing language Object-orientedconcepts Java IDEs Eclipse working environment Variables and Types Strings Variables and Assignment Primitive Data Types 11@ Sonia Sousa2015
  • 12.
    Object-oriented concepts • Whatis an Object? – An object-oriented -> aims to -> model real-world objects • examples of real-world objects: dog, desk, computer, bicycle – Characteristics of real-world object • have state and behaviour – State = name, color, breed, hungry – Behaviour = barking, fetching, wagging tail @ Sonia Sousa 122015
  • 13.
    A bicycle modeledas a object State Variables (fields) behaviours functions (methods) speed Pedal cadence gear that allow to change the state Function to change the gear (bicycle has 3 gears) 1. Reject values < 1 or > than 3 2. Verify what is the current gear 3. Change the gear @ Sonia Sousa 132015
  • 14.
    What we know •What are variables -> state – state of an object in real-world • What are functions (methods) -> behaviours – Behaviour of that object in real world • But… – Take the bicycle example • 1 model/brand can have similar types of bicycle • How to represent in object-oriented terms? – Using classes @ Sonia Sousa 142015
  • 15.
    What Is aClass? • A Class represent 1 object (bicycle) – or 1 or more objects (bicycles) • Objects with similar characteristics of Object bicycle: – Same model, same company, same set of blueprints, same components Instance Of class of objects known as bicycles @ Sonia Sousa 152015 object
  • 16.
    What Is aInheritance? • Represent 1 object (bicycle) – Which shares • general and specific characteristics – Object bicycle: • Shared characteristics – class bicycles • Specific characteristics – superclass – MountainBike and TandemBike – How do you represent as object term? inherit characteristics class of objects known as bicycles Superclass of objects known as specific characteristic
  • 17.
    A class injava • Java includes a library of classes • Java program is made of an aggregation of – 1 or + classes - package – Most common used is • Java.lang (Packages) • Search on google for java 6 api docs • We are going to use – The System class -> belongs to Java.lang – The out variable -> PrintStream class -> System class – Print method - println @ Sonia Sousa 172015
  • 18.
    Outline Java programing language Object-orientedconcepts Java IDEs Eclipse working environment Variables and Types Strings Variables and Assignment Primitive Data Types 18@ Sonia Sousa2015
  • 19.
    Java Development kit •Includes – Compiler - command javac – Runtime - java – Package - jar – Documentation builder - javadoc 2015 @ Sonia Sousa 19
  • 20.
    Java Application • Consists –Of many classes (.java) – command line runtime – The packager (jar) – aggregates the many classes – The javadoc – the documentation builder – The command line compiler - javac 2015 @ Sonia Sousa 20
  • 21.
    First step • Setup the workspace • Create 1 application – Create a project – SRC AND BIN folders • Every Java App Is Build Inside A Class • Create a new class – System.out.println(“Hello World”) – Compile or run java application @ Sonia Sousa 212015
  • 22.
    Eclipse IDE @ SoniaSousa 222015
  • 23.
    public class HelloWorld{ public static void main(String[] args) { System.out.println("Hello world" ); } } Java Program Structure 23 Hello World! Class declaration File name: HelloWorld.java Java is Case sensitive Language = Main method Executable code Compile results File sources HelloWorld.class HelloWorld.java Bytecode file @ Sonia Sousa2015
  • 24.
    Java syntax The methodcan be called anywhere A method contains 1 program statements public class MyProgram { } // comments about the class public static void main (String[] args) { } // Main method declaration method header method body Don’t have to create a instance of a class Do not return anything from the class @ Sonia Sousa 242015 New public class called MyProgram class body
  • 25.
    The println Method •The println method prints a character string • The System.out object represents a destination (the monitor screen) to which we can send output 25 System.out.println ("Whatever you are, be a good one."); information provided (arguments) @ Sonia Sousa2015
  • 26.
    Resulting files 2015 @Sonia Sousa 26
  • 27.
    Errors • A programcan have three types of errors 1) Compile-time errors • The compiler will find syntax errors and other basic problems • If compile-time errors exist, an executable version of the program is not created 2) Run-time errors • A problem can occur during program execution, such as – trying to divide by zero, which causes a program to terminate abnormally 3) Logical errors • A program may run, but produce incorrect results, perhaps using an incorrect formula 2015 @ Sonia Sousa 27
  • 28.
  • 29.
    Comments • Comments shouldalways be included – To explain the purpose of the program; and – Describe processing steps. • They do not affect how a program works • Java comments can take three forms: 29 // this comment runs to the end of the line /* this comment runs to the terminating symbol, even across line breaks */ /** this is a javadoc comment */ @ Sonia Sousa2015
  • 30.
    Java is Casesensitive • Java is case sensitive: – Total, total, and TOTAL are different identifiers • Rules on how to… – use different case styles for different types of identifiers • Class names start with upper case – MyProgram • Variables with lower case - value @ Sonia Sousa 302015
  • 31.
    Reserved words • Identifierswith a predefined meaning in the language – println • A reserved word cannot be used in any other way @ Sonia Sousa 312015
  • 32.
    Reserved Words • TheJava reserved words: 32 abstract assert boolean break byte case catch char class const continue default do double else enum extends false final finally float for goto if implements import instanceof int interface long native new null package private protected public return short static strictfp super switch synchronized this throw throws transient true try void volatile while @ Sonia Sousa2015
  • 33.
    EXERCISE 1 @ SoniaSousa 332015
  • 34.
    Quick Check Which ofthe following are valid Java identifiers? grade quizGrade NetworkConnection frame2 3rdTestScore MAXIMUM MIN_CAPACITY student# Shelves1&2 34@ Sonia Sousa2015
  • 35.
    Quick Check Which ofthe following are valid Java identifiers? grade quizGrade NetworkConnection frame2 3rdTestScore MAXIMUM MIN_CAPACITY student# Shelves1&2 Valid Valid Valid Valid Invalid – cannot begin with a digit Valid Valid Invalid – cannot contain the '#' character Invalid – cannot contain the '&' character 35@ Sonia Sousa2015
  • 36.
    Outline Java programing language Object-orientedconcepts Java IDEs Eclipse working environment Variables and Types Strings Variables and Assignment Primitive Data Types 36@ Sonia Sousa2015
  • 37.
    Character Strings • Astring literal is represented by putting double quotes around the text • Examples: "This is a string literal." "123 Main Street" "X” 37@ Sonia Sousa2015
  • 38.
    EXERCISE 2 @ SoniaSousa 382015
  • 39.
    //******************************************************************** // Countdown.java Author:Lewis/Loftus // // Demonstrates the difference between print and println. //******************************************************************** public class Countdown { //----------------------------------------------------------------- // Prints two lines of output representing a rocket countdown. //----------------------------------------------------------------- public static void main (String[] args) { System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); // appears on first output line System.out.println ("Houston, we have a problem."); } } 39@ Sonia Sousa2015
  • 40.
    //******************************************************************** // Countdown.java Author:Lewis/Loftus // // Demonstrates the difference between print and println. //******************************************************************** public class Countdown { //----------------------------------------------------------------- // Prints two lines of output representing a rocket countdown. //----------------------------------------------------------------- public static void main (String[] args) { System.out.print ("Three... "); System.out.print ("Two... "); System.out.print ("One... "); System.out.print ("Zero... "); System.out.println ("Liftoff!"); // appears on first output line System.out.println ("Houston, we have a problem."); } } Output Three... Two... One... Zero... Liftoff! Houston, we have a problem. 40@ Sonia Sousa2015
  • 41.
    String Concatenation • Thestring concatenation operator (+) is used to append one string to the end of another "Peanut butter " + "and jelly" • It can also be used to append a number to a string • A string literal cannot be broken across two lines in a program 41@ Sonia Sousa2015
  • 42.
    EXERCISE 3 @ SoniaSousa 422015
  • 43.
    //******************************************************************** // Facts.java Author:Lewis/Loftus // // Demonstrates the use of the string concatenation operator and the // automatic conversion of an integer to a string. //******************************************************************** public class Facts { //----------------------------------------------------------------- // Prints various facts. //----------------------------------------------------------------- public static void main (String[] args) { // Strings can be concatenated into one long string System.out.println ("We present the following facts for your " + "extracurricular edification:"); System.out.println (); // A string can contain numeric digits System.out.println ("Letters in the Hawaiian alphabet: 12"); continue 43@ Sonia Sousa2015
  • 44.
    continue // A numericvalue can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515); System.out.println ("Speed of ketchup: " + 40 + " km per year"); } } 44@ Sonia Sousa2015
  • 45.
    continue // A numericvalue can be concatenated to a string System.out.println ("Dialing code for Antarctica: " + 672); System.out.println ("Year in which Leonardo da Vinci invented " + "the parachute: " + 1515); System.out.println ("Speed of ketchup: " + 40 + " km per year"); } } Output We present the following facts for your extracurricular edification: Letters in the Hawaiian alphabet: 12 Dialing code for Antarctica: 672 Year in which Leonardo da Vinci invented the parachute: 1515 Speed of ketchup: 40 km per year 45@ Sonia Sousa2015
  • 46.
    String Concatenation • The+ operator is also used for arithmetic addition – The function that it performs depends on the type of the information on which it operates • If both operands are strings, or if one is a string and one is a number, – it performs string concatenation • If both operands are numeric, it adds them • The + operator is evaluated left to right, but parentheses can be used to force the order 46@ Sonia Sousa2015
  • 47.
    EXERCISE 4 @ SoniaSousa 472015
  • 48.
    //******************************************************************** // Addition.java Author:Lewis/Loftus // // Demonstrates the difference between the addition and string // concatenation operators. //******************************************************************** public class Addition { //----------------------------------------------------------------- // Concatenates and adds two numbers and prints the results. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("24 and 45 concatenated: " + 24 + 45); System.out.println ("24 and 45 added: " + (24 + 45)); } } 48@ Sonia Sousa2015
  • 49.
    //******************************************************************** // Addition.java Author:Lewis/Loftus // // Demonstrates the difference between the addition and string // concatenation operators. //******************************************************************** public class Addition { //----------------------------------------------------------------- // Concatenates and adds two numbers and prints the results. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("24 and 45 concatenated: " + 24 + 45); System.out.println ("24 and 45 added: " + (24 + 45)); } } Output 24 and 45 concatenated: 2445 24 and 45 added: 69 49@ Sonia Sousa2015
  • 50.
    EXERCISE 5 @ SoniaSousa 502015
  • 51.
    Quick Check • Whatoutput is produced by the following? 51 System.out.println ("X: " + 25); System.out.println ("Y: " + (15 + 50)); System.out.println ("Z: " + 300 + 50); @ Sonia Sousa2015
  • 52.
    Quick Check X: 25 Y:65 Z: 30050 52 • What output is produced by the following? System.out.println ("X: " + 25); System.out.println ("Y: " + (15 + 50)); System.out.println ("Z: " + 300 + 50); @ Sonia Sousa2015
  • 53.
    EXERCISE 6 @ SoniaSousa 532015
  • 54.
    Quick Check • Whatoutput is produced by the following? 54 System.out.println ("I said "Hello" to you."); @ Sonia Sousa2015
  • 55.
    Quick Check An escapesequence begins with a backslash character () System.out.println ("I said "Hello" to you."); 55 • The compiler becomes confuse – would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); @ Sonia Sousa2015
  • 56.
    EXERCISE 7 @ SoniaSousa 562015
  • 57.
    Escape Sequences • SomeJava escape sequences: 57 Escape Sequence b t n r " ' Meaning backspace tab newline carriage return double quote single quote backslash @ Sonia Sousa2015
  • 58.
    //******************************************************************** // Roses.java Author:Lewis/Loftus // // Demonstrates the use of escape sequences. //******************************************************************** public class Roses { //----------------------------------------------------------------- // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("Roses are red,” + “Violets are blue," + "Sugar is sweet,ntBut I have "commitment issues",nt" + "So I'd rather just be friendsntAt this point in our " + "relationship."); } } 58@ Sonia Sousa2015
  • 59.
    //******************************************************************** // Roses.java Author:Lewis/Loftus // // Demonstrates the use of escape sequences. //******************************************************************** public class Roses { //----------------------------------------------------------------- // Prints a poem (of sorts) on multiple lines. //----------------------------------------------------------------- public static void main (String[] args) { System.out.println ("Roses are red,ntViolets are blue,n" + "Sugar is sweet,ntBut I have "commitment issues",nt" + "So I'd rather just be friendsntAt this point in our " + "relationship."); } } Output Roses are red, Violets are blue, Sugar is sweet, But I have "commitment issues", So I'd rather just be friends At this point in our relationship. 59@ Sonia Sousa2015
  • 60.
    EXERCISE 8 @ SoniaSousa 602015
  • 61.
    Quick Check • Writea single println statement that produces the following output: 61 "Thank you all for coming to my home tonight," he said mysteriously. @ Sonia Sousa2015
  • 62.
    • Write asingle println statement that produces the following output: Quick Check "Thank you all for coming to my home tonight," he said mysteriously. System.out.println (""Thank you all for " + "coming to my homentonight," he said " + "mysteriously."); 62@ Sonia Sousa2015
  • 63.
    Outline Java programing language Object-orientedconcepts Java IDEs Eclipse working environment Variables and Types Strings Variables and Assignment Primitive Data Types 63@ Sonia Sousa2015
  • 64.
    EXERCISE 9 @ SoniaSousa 642015
  • 65.
    Variables • A variableis a name for a – location in memory that holds a value • When you declare a variable (variable declaration) – you need to specify 65 int total; int count, temp, result; Multiple variables can be created in one declaration data type variable name @ Sonia Sousa2015
  • 66.
    Variable Initialization • Youcan add a initial value to your variable 66 int sum = 0; int base = 32, max = 149; data type variable name variable value = 0 @ Sonia Sousa2015
  • 67.
    EXERCISE 10 @ SoniaSousa 672015
  • 68.
    //******************************************************************** // PianoKeys.java Author:Lewis/Loftus // // Demonstrates the declaration, initialization, and use of an // integer variable. //******************************************************************** public class PianoKeys { //----------------------------------------------------------------- // Prints the number of keys on a piano. //----------------------------------------------------------------- public static void main (String[] args) { int keys = 88; System.out.println ("A piano has " + keys + " keys."); } } 68@ Sonia Sousa2015
  • 69.
    //******************************************************************** // PianoKeys.java Author:Lewis/Loftus // // Demonstrates the declaration, initialization, and use of an // integer variable. //******************************************************************** public class PianoKeys { //----------------------------------------------------------------- // Prints the number of keys on a piano. //----------------------------------------------------------------- public static void main (String[] args) { int keys = 88; System.out.println ("A piano has " + keys + " keys."); } } Output A piano has 88 keys. 69@ Sonia Sousa2015
  • 70.
    Assignment • An assignmentstatement – Changes the value of a variable • What happens? • The value that was in total is overwritten • You need to assign a value to a variable = variable's declared type • Int , byte, short, long, float, double, boolean, char • See more about primitive Data types 70 total = 55; Assignment operator @ Sonia Sousa2015
  • 71.
    EXERCISE 11 @ SoniaSousa 712015
  • 72.
    //******************************************************************** // Geometry.java Author:Lewis/Loftus // // Demonstrates the use of an assignment statement to change the // value stored in a variable. //******************************************************************** public class Geometry { //----------------------------------------------------------------- // Prints the number of sides of several geometric shapes. //----------------------------------------------------------------- public static void main (String[] args) { int sides = 7; // declaration with initialization System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); sides = 12; System.out.println ("A dodecagon has " + sides + " sides."); } } 72@ Sonia Sousa2015
  • 73.
    //******************************************************************** // Geometry.java Author:Lewis/Loftus // // Demonstrates the use of an assignment statement to change the // value stored in a variable. //******************************************************************** public class Geometry { //----------------------------------------------------------------- // Prints the number of sides of several geometric shapes. //----------------------------------------------------------------- public static void main (String[] args) { int sides = 7; // declaration with initialization System.out.println ("A heptagon has " + sides + " sides."); sides = 10; // assignment statement System.out.println ("A decagon has " + sides + " sides."); sides = 12; System.out.println ("A dodecagon has " + sides + " sides."); } } Output A heptagon has 7 sides. A decagon has 10 sides. a dodecagon has 12 sides. 73@ Sonia Sousa2015
  • 74.
    Constants • A constantis an identifier – that is similar to a variable except that it holds the same value during its entire existence • As the name implies, it is constant, not variable • The compiler will issue an error if you try to change the value of a constant • In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69; 74@ Sonia Sousa2015
  • 75.
    Constants • Constants areuseful for three important reasons 1) First, they give meaning to otherwise unclear literal values • Example: MIN_HEIGHT means more than the literal 69 2) Second, they facilitate program maintenance • If a constant is used in multiple places, its value need only be set in one place 3) Third, they formally establish that a value should not change, • Avoiding inadvertent errors by other programmers 2015 @ Sonia Sousa 75
  • 76.
    Outline Java programing language Object-orientedconcepts Java IDEs Eclipse working environment Variables and Types Strings Variables and Assignment Primitive Data Types 76@ Sonia Sousa2015
  • 77.
    Primitive Data • Thereare eight primitive data types in Java • Four of them represent integers: – byte, short, int, long • Two of them represent floating point numbers: – float, double • One of them represents characters: – char • And one of them represents boolean values: – boolean 2015 @ Sonia Sousa 77
  • 78.
    Most common Types •int – integer (most common. no decimal) • long – holds a really big integer • float – accurate up to 7 decimal places • double – accurate up to 15 decimal places I do believe (at work and don't have a book) • boolean – false or true (also 1 = true, 0 = false) • string – anything from numbers to letters to whole sentences. It will take the input literately. • char – character, such as f or 6 or 2015 @ Sonia Sousa 78
  • 79.
    Numeric Primitive Data •The difference between the numeric primitive types is their size and the values they can store: 2015 @ Sonia Sousa 79 Type byte short int long float double Storage 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits Min Value -128 -32,768 -2,147,483,648 < -9 x 1018 - 3.4 x 1038 3.4 x 1038 - 1.7 x 10308 1.7 x 10308 Max Value 127 32,767 2,147,483,647 > 9 x 1018
  • 80.
    Characters • A charvariable stores a single character • Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' 'n' • Example declarations: char topGrade = 'A'; char terminator = ';', separator = ' '; • Note the difference between – a primitive character variable, which holds only one character, and – a String object, which can hold multiple characters 2015 @ Sonia Sousa 80
  • 81.
    Character Sets • Acharacter set is an ordered list of characters, with each character corresponding to a unique number • A char variable in Java can store any character from the Unicode character set • The Unicode character set uses sixteen bits per character, allowing for 65,536 unique characters • It is an international character set, containing symbols and characters from many world languages 2015 @ Sonia Sousa 81
  • 82.
    Characters • The ASCIIcharacter set is older and smaller than Unicode, but is still quite popular • The ASCII characters are a subset of the Unicode character set, including: 2015 @ Sonia Sousa 82 uppercase letters lowercase letters punctuation digits special symbols control characters A, B, C, … a, b, c, … period, semi-colon, … 0, 1, 2, … &, |, , … carriage return, tab, ...
  • 83.
    Boolean • A booleanvalue represents a true or false condition • The reserved words true and false are the only valid values for a boolean type boolean done = false; • A boolean variable can also be used to represent any two states, such as a light bulb being on or off 2015 @ Sonia Sousa 83

Editor's Notes

  • #23 Java development environment are cross-platform they work on all operative systems
  • #24 Main method = lower case Java look for it to execute Main method must receive an argument = array of String[]