Ifi7107 lesson1- Programming languages
Transcript of Ifi7107 lesson1- Programming languages
IFI7102 – Lesson 1
Introduction and contextualization
@ slides adapted from Isaías da Rosa sources
@ Sonia Sousa 2
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
2015
@ Sonia Sousa 3
Java programming language
• Dynamic Web applications– Servlets, JSP
• Native applications– Android and blackberry
• Java is not – Javascript– Native IOS
2015
@ Sonia Sousa 4
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
2015
@ Sonia Sousa 5
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
2015
@ Sonia Sousa 6
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
2015
@ Sonia Sousa 7
Java Translation• Java is an
– interpreted language
– Is portable
• The Java compiler translates into
– Java bytecode
• We will use a Java virtual machine
– Eclipse
Java sourcecode Java
bytecode
Javacompiler
2015
@ Sonia Sousa 8
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
2015
@ Sonia Sousa 9
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
2015
@ Sonia Sousa 10
A bicycle modeled as a object
StateVariables (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
2015
@ Sonia Sousa 11
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
2015
@ Sonia Sousa 12
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
InstanceOf
class of objects known as bicycles
2015
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 bicyclesSuperclass of objects known as specific characteristic
@ Sonia Sousa 14
Instance
• An object and an instance in java language – are the same thing
2015
@ Sonia Sousa 15
Identifier
• What is it?– Identifiers are the "words" in a program
• How can it be represented?– letters, digits, the underscore character ( _ ),
and the dollar sign– Not with a digit
2015
@ Sonia Sousa 16
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
2015
@ Sonia Sousa 17
DEMO
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
2015
@ Sonia Sousa 21
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world" );
}
}
Java Program Structure
Hello World!
Class declaration
File name: HelloWorld.java Java is Case sensitive Language
=
Main method
Executable code
Compile resultsFile sources
HelloWorld.class
HelloWorld.java
Bytecode file
2015
@ Sonia Sousa 22
Java syntax
The method can be called anywhere
A method contains1 program statements
public class MyProgram{
}
// comments about the class
public static void main (String[] args)
{
}
// Main method declaration
method headermethod bodyDon’t have to create a instance of a class
Do not return anything from the class
2015
New public class called MyProgram
class body
@ Sonia Sousa 23
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
System.out.println ("Whatever you are, be a good one.");
information provided(arguments)
2015
@ Sonia Sousa 24
Resulting files
2015
Sum…
@ Sonia Sousa 26
Basic Program Development
errors?
errors?
Edit andsave program
Compile program
Execute program andevaluate results
2015
@ Sonia Sousa 27
Java Translation
Java sourcecode
Machinecode
Javabytecode
Bytecodeinterpreter
Bytecodecompiler
Javacompiler
2015
@ Sonia Sousa 28
A class in java
• Can be inside of a package– That is a group of classes with common characteristics
• Java includes a library of classes – Each class -> has a property
• Most common used is– Java.lang (Packages)– Search on google for java 6 api docs
• Java program is made of an aggregation of – 1 or + classes
• We are going to use – The System class -> belongs to Java.lang– The out variable -> PrintStream class -> System class – println and print method2015
@ Sonia Sousa 29
Errors
• A program can have three types of errors1) 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 30
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:
// 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 */
2015
@ Sonia Sousa 31
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
2015
@ Sonia Sousa 32
Reserved words
• Identifiers with a predefined meaning in the language– println
• A reserved word cannot be used in any other way
2015
@ Sonia Sousa 33
Reserved Words
• The Java reserved words:abstractassertbooleanbreakbytecasecatchcharclassconstcontinuedefaultdodouble
elseenumextendsfalsefinalfinallyfloatforgotoifimplementsimportinstanceofint
interfacelongnativenewnullpackageprivateprotectedpublicreturnshortstaticstrictfpsuper
switchsynchronizedthisthrowthrowstransienttruetryvoidvolatilewhile
2015
@ Sonia Sousa 34
EXERCISE 1
2015
@ Sonia Sousa 35
Quick CheckWhich of the following are valid Java identifiers?
grade
quizGrade
NetworkConnection
frame2
3rdTestScore
MAXIMUM
MIN_CAPACITY
student#
Shelves1&2
2015
@ Sonia Sousa 36
Quick CheckWhich 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
2015
@ Sonia Sousa 37
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
2015
@ Sonia Sousa 38
Character Strings
• A string literal is represented by putting double quotes around the text
• Examples:
"This is a string literal.""123 Main Street""X”
2015
@ Sonia Sousa 39
EXERCISE 2
2015
@ Sonia Sousa 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."); }}
2015
@ Sonia Sousa 41
//********************************************************************// 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.
2015
@ Sonia Sousa 42
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
2015
@ Sonia Sousa 43
EXERCISE 3
2015
@ Sonia Sousa 44
//********************************************************************// 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
2015
@ Sonia Sousa 45
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"); }}
2015
@ Sonia Sousa 46
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"); }}
OutputWe present the following facts for your extracurricular edification:
Letters in the Hawaiian alphabet: 12Dialing code for Antarctica: 672Year in which Leonardo da Vinci invented the parachute: 1515Speed of ketchup: 40 km per year
2015
@ Sonia Sousa 47
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
2015
@ Sonia Sousa 48
EXERCISE 4
2015
@ Sonia Sousa 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)); }}
2015
@ Sonia Sousa 50
//********************************************************************// 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: 244524 and 45 added: 69
2015
@ Sonia Sousa 51
EXERCISE 5
2015
@ Sonia Sousa 52
Quick Check
• What output is produced by the following?
System.out.println ("X: " + 25);System.out.println ("Y: " + (15 + 50));System.out.println ("Z: " + 300 + 50);
2015
@ Sonia Sousa 53
Quick Check
X: 25Y: 65Z: 30050
• What output is produced by the following?
System.out.println ("X: " + 25);System.out.println ("Y: " + (15 + 50));System.out.println ("Z: " + 300 + 50);
2015
@ Sonia Sousa 54
EXERCISE 6
2015
@ Sonia Sousa 55
Quick Check
• What output is produced by the following?
System.out.println ("I said "Hello" to you.");
2015
@ Sonia Sousa 56
Quick Check
An escape sequence begins with a backslash character (\)
System.out.println ("I said \"Hello\" to you.");
• The compiler becomes confuse– would interpret the second quote as the end
of the string
System.out.println ("I said "Hello" to you.");
2015
@ Sonia Sousa 57
EXERCISE 7
2015
@ Sonia Sousa 58
Escape Sequences
• Some Java escape sequences:
Escape Sequence
\b\t\n\r\"\'\\
Meaning
backspacetabnewlinecarriage returndouble quotesingle quotebackslash
2015
@ Sonia Sousa 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,” + “Violets are blue," + "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tAt this point in our " + "relationship."); }}
2015
@ Sonia Sousa 60
//********************************************************************// 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,\n\tViolets are blue,\n" + "Sugar is sweet,\n\tBut I have \"commitment issues\",\n\t" + "So I'd rather just be friends\n\tAt 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 friendsAt this point in our relationship.
2015
@ Sonia Sousa 61
EXERCISE 8
2015
@ Sonia Sousa 62
Quick Check
• Write a single println statement that produces the following output:
"Thank you all for coming to my hometonight," he said mysteriously.
2015
@ Sonia Sousa 63
• Write a single println statement that produces the following output:
Quick Check
"Thank you all for coming to my hometonight," he said mysteriously.
System.out.println ("\"Thank you all for " + "coming to my home\ntonight,\" he said " + "mysteriously.");
2015
@ Sonia Sousa 64
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
2015
@ Sonia Sousa 65
EXERCISE 9
2015
@ Sonia Sousa 66
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
int total;
int count, temp, result;
Multiple variables can be created in one declaration
data type variable name
2015
@ Sonia Sousa 67
Variable Initialization
• You can add a initial value to your variable
int sum = 0;int base = 32, max = 149;
data type variable namevariable value = 0
2015
@ Sonia Sousa 68
EXERCISE 10
2015
@ Sonia Sousa 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."); }}
2015
@ Sonia Sousa 70
//********************************************************************// 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.
2015
@ Sonia Sousa 71
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
total = 55;
Assignment operator
2015
@ Sonia Sousa 72
EXERCISE 11
2015
@ Sonia Sousa 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."); }}
2015
@ Sonia Sousa 74
//********************************************************************// 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.
2015
@ Sonia Sousa 75
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;
2015
@ Sonia Sousa 76
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 77
Outline
Java programing language
Object-oriented concepts
Java IDEs
Eclipse working environment
Variables and Types
Strings
Variables and Assignment
Primitive Data Types
2015
@ Sonia Sousa 78
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 79
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 80
Numeric Primitive Data
• The difference between the numeric primitive types is their size and the values they can store:
2015
Type
byteshortintlong
floatdouble
Storage
8 bits16 bits32 bits64 bits
32 bits64 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
12732,7672,147,483,647> 9 x 1018
@ Sonia Sousa 81
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 82
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 83
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
uppercase letterslowercase letterspunctuationdigitsspecial symbolscontrol characters
A, B, C, …a, b, c, …period, semi-colon, …0, 1, 2, …&, |, \, …carriage return, tab, ...
@ Sonia Sousa 84
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