comp 248 introduction to programming chapter 1 - getting started dr. aiman hanna department of...

73
Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University, Montreal, Canada These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by Pearson Education / Addison-Wesley. Copyright © 2007-2013 Pearson Addison-Wesley

Upload: owen-small

Post on 03-Jan-2016

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Comp 248 Introduction to Programming

Chapter 1 - Getting Started

Dr. Aiman HannaDepartment of Computer Science & Software Engineering

Concordia University, Montreal, Canada

These slides has been extracted, modified and updated from original slides of Absolute Java 3 rd Edition by Savitch; which has originally been prepared by Rose Williams of Binghamton University. Absolute Java is published by

Pearson Education / Addison-Wesley.

Copyright © 2007-2013 Pearson Addison-WesleyCopyright © 2008-2014 Aiman Hanna

All rights reserved

Page 2: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Origins of the Java Origins of the Java LanguageLanguage

Created by Sun Microsystems team Created by Sun Microsystems team led by James Gosling (1991)led by James Gosling (1991)

Originally designed for programming Originally designed for programming home applianceshome appliances Difficult task because appliances are Difficult task because appliances are

controlled by a wide variety of computer controlled by a wide variety of computer processorsprocessors

Team developed a two-step translation Team developed a two-step translation process to simplify the task of compiler process to simplify the task of compiler writing for each class of applianceswriting for each class of appliances

1-2

Page 3: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Origins of the Java Origins of the Java LanguageLanguage

Java evolved to a general purpose Java evolved to a general purpose programming language, that is very programming language, that is very suitable for many Internet suitable for many Internet applicationsapplications

The syntax of expressions and The syntax of expressions and assignments is similar to that of assignments is similar to that of other high-level languages, such as other high-level languages, such as C++C++

1-3

Page 4: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Origins of the Java Origins of the Java LanguageLanguage

Significance of Java translation processSignificance of Java translation process Writing a compiler (translation program) for each Writing a compiler (translation program) for each

type of appliance processor would have been very type of appliance processor would have been very costlycostly

The same rule applies to writing compilers: The same rule applies to writing compilers: different compilers are needed for different different compilers are needed for different systems (processor/Operating System) systems (processor/Operating System)

Example: Example:

1-4

Page 5: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Origins of the Java Origins of the Java LanguageLanguage

Instead, Java designers developed Instead, Java designers developed intermediate language that is the same for all intermediate language that is the same for all types of processors: Java types of processors: Java byte-codebyte-code

One compiler is designed to translate Java One compiler is designed to translate Java Source code to byte code. Source code to byte code.

The byte-code is viewed as suitable to every The byte-code is viewed as suitable to every machine (actually it is not; it is only suitable to machine (actually it is not; it is only suitable to a fictitious, or imaginary machine; which we a fictitious, or imaginary machine; which we refer to as refer to as Virtual MachineVirtual Machine))

1-5

Page 6: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Origins of the Java Origins of the Java LanguageLanguage

The byte-code can be viewed as suitable to The byte-code can be viewed as suitable to every machine since it is easily possible to write every machine since it is easily possible to write a small program (interpreter) to translate byte-a small program (interpreter) to translate byte-code into the proper machine code for each code into the proper machine code for each processorprocessor

1-6

Page 7: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Objects and MethodsObjects and Methods

Java is an Java is an object-oriented object-oriented programming (OOP)programming (OOP) language language Programming methodology that views a Programming methodology that views a

program as consisting of program as consisting of objects objects that that interact with one another by means of interact with one another by means of actions (called actions (called methodsmethods; sometimes ; sometimes referred to as referred to as functionsfunctions))

All programming constructs in Java, All programming constructs in Java, including including methodsmethods, are part of a , are part of a classclass

Objects of the same kind are said to have Objects of the same kind are said to have the same the same typetype or be in the same or be in the same classclass

1-7

Page 8: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Java Application Java Application ProgramsPrograms

There are two types of Java programs: There are two types of Java programs: applicationsapplications and and appletsapplets

A Java A Java application program application program or "regular" Java or "regular" Java program is a class with a method named program is a class with a method named mainmain

When a Java application program is run, the When a Java application program is run, the run-run-time systemtime system automatically invokes the method automatically invokes the method named named mainmain

All Java application programs start with the All Java application programs start with the mainmain methodmethod

1-8

Page 9: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

AppletsApplets A Java A Java appletapplet ( (little Java applicationlittle Java application) is a Java ) is a Java

program that is meant to be run from a Web program that is meant to be run from a Web browserbrowser

Can be run from a location on the InternetCan be run from a location on the Internet

Can also be run with an applet viewer program for Can also be run with an applet viewer program for debuggingdebugging

Applets always use a windowing interfaceApplets always use a windowing interface

In contrast, application programs may use a In contrast, application programs may use a windowing interface or console (i.e., text) I/Owindowing interface or console (i.e., text) I/O

1-9

Page 10: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Java Program Structure Java Program Structure

1-10

public class MyProgram

{

}

// comments about the class

class header

class body

Comments can be placed almost anywhere

Page 11: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Java Program Structure Java Program Structure

1-11

public class MyProgram

{

}

public static void main (String[] args)

{

}

// comments about the class

// comments about the method

method headermethod body

Page 12: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

A Sample Java A Sample Java Application ProgramApplication Program

1-12

Greetings.java ((MS-Word file))

Page 13: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

System.out.printlnSystem.out.println

Java programs work by having Java programs work by having things called things called objectsobjects perform actions perform actions System.outSystem.out: an object used for sending : an object used for sending

output to the screenoutput to the screen The actions performed by an object The actions performed by an object

are called are called methodsmethods printlnprintln: the method or action that the : the method or action that the System.outSystem.out object performs object performs

1-13

Page 14: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

System.out.printlnSystem.out.println

InvokingInvoking or or callingcalling a method: When an object a method: When an object performs an action using a methodperforms an action using a method

Method invocation syntax (in order): an objectMethod invocation syntax (in order): an object,, a dot a dot (period), the method name, and a pair of parentheses(period), the method name, and a pair of parentheses

ArgumentsArguments: : Zero or more pieces of information needed Zero or more pieces of information needed by the method that are placed inside the parenthesesby the method that are placed inside the parentheses

Examples: Examples:

System.out.println("This is an argument");

System.out.println();

1-14

Page 15: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Variable declarations Variable declarations

Variable declarations in Java are Variable declarations in Java are similar to those in other similar to those in other programming languagesprogramming languages

Simply give the Simply give the typetype of the variable of the variable followed by its name and a semicolon followed by its name and a semicolon

Examples:Examples:int numOfDoors;int numOfDoors;

double price;double price; 1-15

Page 16: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Using Using == and and ++

In Java, the equal sign (In Java, the equal sign (==) is used as ) is used as the the assignment operatorassignment operator The variable on the left side of the The variable on the left side of the

assignment operator is assignment operator is assigned the assigned the valuevalue of the expression on the right side of the expression on the right side of the assignment operatorof the assignment operator

numOfDoors = 4;numOfDoors = 4;

1-16

Page 17: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Using Using == and and ++

In Java, the plus sign (In Java, the plus sign (++) can be used ) can be used to denote addition or to denote addition or concatenationconcatenationExamples:Examples:

int total;int total;

total = 2 + 5;total = 2 + 5;

Using Using ++, two strings can also be , two strings can also be connected togetherconnected togetherSystem.out.println("2 plus 5 is " + total);

1-17

MathOperations1.java (MS-Word file)(MS-Word file)

Page 18: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Compiling a Java Compiling a Java Program or ClassProgram or Class

Each class definition must be in a file whose Each class definition must be in a file whose name is the same as the class name followed name is the same as the class name followed by by ..javajava For example, the class For example, the class FirstProgramFirstProgram must be in a must be in a

file named file named FirstProgram.javaFirstProgram.java

Each class is compiled with the command Each class is compiled with the command javacjavac followed by the name of the file in followed by the name of the file in which the class resideswhich the class resides

javac FirstProgram.javajavac FirstProgram.java

The result is a byte-code program whose filename The result is a byte-code program whose filename is the same as the class name followed by is the same as the class name followed by ..classclass

FirstProgram.classFirstProgram.class1-18

Page 19: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Running a Java ProgramRunning a Java Program A Java program can be given the A Java program can be given the run run

commandcommand ( (javajava) after all its classes have ) after all its classes have been compiledbeen compiled

Only run the class that contains the Only run the class that contains the mainmain method (the system will automatically load and method (the system will automatically load and run the other classes, if any)run the other classes, if any)

The The mainmain method begins with the line: method begins with the line:public static void main(String[ ] args)public static void main(String[ ] args)

Follow the run command by the name of the Follow the run command by the name of the class only (no class only (no .java.java or or ..classclass extension) extension)

java FirstProgramjava FirstProgram

1-19

Page 20: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Syntax and SemanticsSyntax and Semantics

SyntaxSyntax: The arrangement of words : The arrangement of words and punctuations that are legal in a and punctuations that are legal in a language, the language, the grammar rulesgrammar rules of a of a languagelanguage

SemanticsSemantics: The meaning of things : The meaning of things written while following the syntax written while following the syntax rules of a languagerules of a language

1-20

Page 21: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Tip: Error MessagesTip: Error Messages

BugBug: A mistake in a program: A mistake in a program The process of eliminating bugs is The process of eliminating bugs is

called called debuggingdebugging

Syntax error: Syntax error: A grammatical A grammatical mistake in a programmistake in a program The compiler can detect these errors, The compiler can detect these errors,

and will output an error message saying and will output an error message saying what it thinks the error is, and where it what it thinks the error is, and where it thinks the error isthinks the error is

1-21

Page 22: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Tip: Error MessagesTip: Error Messages

Run-time error: Run-time error: An error that is not An error that is not detected until a program is rundetected until a program is run The compiler cannot detect these errors: an The compiler cannot detect these errors: an

error message is not generated after error message is not generated after compilation, but after executioncompilation, but after execution

Logic error: Logic error: A mistake in the underlying A mistake in the underlying algorithm for a programalgorithm for a program The compiler cannot detect these errors, and The compiler cannot detect these errors, and

no error message is generated after no error message is generated after compilation or execution, but the program compilation or execution, but the program does not do what it is supposed to dodoes not do what it is supposed to do 1-22

Page 23: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

IdentifiersIdentifiers IdentifierIdentifier: The name of a variable or other : The name of a variable or other

item (class, method, object, etc.) defined in a item (class, method, object, etc.) defined in a programprogram

The name of a Java identifier may include letters, The name of a Java identifier may include letters, digits, or the underscore symbol, and must not digits, or the underscore symbol, and must not start with a digitstart with a digit

Java identifiers can theoretically be of any lengthJava identifiers can theoretically be of any length

Java is a case-sensitive language: Java is a case-sensitive language: RateRate, , raterate, and , and RATERATE are the names of three different variables are the names of three different variables

1-23

Page 24: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

IdentifiersIdentifiers

Which of the following is a valid Which of the following is a valid identifier? identifier?

IntRateIntRate (A: Valid, B: Not Valid)(A: Valid, B: Not Valid) Five_speedFive_speed (A: Valid, B: Not Valid)(A: Valid, B: Not Valid) 5_speed5_speed (A: Valid, B: Not Valid)(A: Valid, B: Not Valid) _5 speed_5 speed (A: Valid, B: Not Valid)(A: Valid, B: Not Valid) MercedesSL500MercedesSL500 (A: Valid, B: Not Valid)(A: Valid, B: Not Valid) Time.and.spaceTime.and.space (A: Valid, B: Not Valid)(A: Valid, B: Not Valid) ___3___3 (A: Valid, B: Not Valid)(A: Valid, B: Not Valid) Less<5Less<5 (A: Valid, B: Not Valid)(A: Valid, B: Not Valid)

1-24

Page 25: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

IdentifiersIdentifiers Keywords and Reserved words: Identifiers Keywords and Reserved words: Identifiers

that have a predefined meaning in Javathat have a predefined meaning in Java Cannot be used to name anything elseCannot be used to name anything else

public class void staticpublic class void static

Predefined identifiers: Identifiers that are Predefined identifiers: Identifiers that are defined in libraries required by the Java defined in libraries required by the Java language standardlanguage standard They can be redefined, however this could be They can be redefined, however this could be

confusing and possibly dangerous since this confusing and possibly dangerous since this would change their standard meaning; so do not would change their standard meaning; so do not do that even if it is allowed hy the language!do that even if it is allowed hy the language!

System String printlnSystem String println1-25

Page 26: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Naming ConventionsNaming Conventions Start the names of variables, methods, Start the names of variables, methods,

and objects with a lowercase letter, and objects with a lowercase letter, indicate "word" boundaries with an indicate "word" boundaries with an uppercase letter, and restrict the uppercase letter, and restrict the remaining characters to digits and remaining characters to digits and lowercase letterslowercase letters

topSpeed bankRate1 timeOfArrivaltopSpeed bankRate1 timeOfArrival

Start the names of classes with an Start the names of classes with an uppercase letter and, otherwise, adhere to uppercase letter and, otherwise, adhere to the rules abovethe rules above

FirstProgram MyClass StringFirstProgram MyClass String

1-26

Note that this is just one possible conventionNote that this is just one possible convention

Page 27: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Variable DeclarationsVariable Declarations Every variable in a Java program must be Every variable in a Java program must be declareddeclared

before it is usedbefore it is used A variable declaration tells the compiler what kind of data A variable declaration tells the compiler what kind of data

(type) will be stored in the variable(type) will be stored in the variable

The type of the variable is followed by one or more variable The type of the variable is followed by one or more variable names separated by commas, and terminated with a names separated by commas, and terminated with a semicolonsemicolon

Examples:Examples: int numberOfBeans;int numberOfBeans;double distance, price, totalWeight;double distance, price, totalWeight;

Variables are typically declared just before they are used or Variables are typically declared just before they are used or at the start of a block (indicated by an opening brace at the start of a block (indicated by an opening brace {{ ) )

Basic types in Java are called Basic types in Java are called primitive typesprimitive types1-27

Page 28: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Primitive TypesPrimitive Types

1-28

Page 29: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Assignment Statements With Assignment Statements With Primitive TypesPrimitive Types

In Java, the assignment statement is In Java, the assignment statement is used to change the value of a variableused to change the value of a variable The equal sign (The equal sign (==) is used as the assignment ) is used as the assignment

operatoroperator An assignment statement consists of a An assignment statement consists of a

variable on the left side of the operator, and variable on the left side of the operator, and an an expressionexpression on the right side of the on the right side of the operatoroperator

Variable = Expression;Variable = Expression;

An An expressionexpression consists of a variable, number, consists of a variable, number, or mix of variables, numbers, operators, or mix of variables, numbers, operators, and/or method invocationsand/or method invocations

temperature = 98.6;temperature = 98.6;count = numberOfBeans;count = numberOfBeans;

1-29

Page 30: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Assignment Statements With Assignment Statements With Primitive TypesPrimitive Types

When an assignment statement is executed, the When an assignment statement is executed, the expression is first evaluated, and then the variable expression is first evaluated, and then the variable on the left-hand side of the equal sign is set equal to on the left-hand side of the equal sign is set equal to the value of the expressionthe value of the expression

distance = rate * time;distance = rate * time; Note that a variable can occur on both sides of the Note that a variable can occur on both sides of the

assignment operatorassignment operatorcount = count + 2;count = count + 2;

The assignment operator is automatically executed The assignment operator is automatically executed from right-to-left, so assignment statements can be from right-to-left, so assignment statements can be chainedchained

number2 = number1 = 3;number2 = number1 = 3;

1-30

MathOperations2.java MathOperations2.java (MS-Word file)(MS-Word file)

Page 31: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Tip: Initialize VariablesTip: Initialize Variables A variable that has been declared but that A variable that has been declared but that

has not yet been given a value by some has not yet been given a value by some means is said to be means is said to be uninitializeduninitialized

In certain cases, such as local variables In certain cases, such as local variables inside a method, the compiler will fail if an inside a method, the compiler will fail if an uninitialized variable is used (to read from)uninitialized variable is used (to read from)

In other cases an uninitialized variable is In other cases an uninitialized variable is given a default valuegiven a default value It is best not to rely on thisIt is best not to rely on this Explicitly initialized variables have the added Explicitly initialized variables have the added

benefit of improving program claritybenefit of improving program clarity

1-31

Page 32: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Tip: Initialize VariablesTip: Initialize Variables The declaration of a variable can be combined The declaration of a variable can be combined

with its initialization via an assignment with its initialization via an assignment statementstatement

int count = 0;int count = 0;double distance = 55 * .5;double distance = 55 * .5;char grade = 'A';char grade = 'A';double total = Price + taxes;double total = Price + taxes;

Note that some variables can be initialized and Note that some variables can be initialized and others can remain un-initialized in the same others can remain un-initialized in the same declarationdeclaration

int initialCount = 50, finalCount;int initialCount = 50, finalCount;

1-32

Initialization1.java Initialization1.java (MS-Word file)(MS-Word file)

Initialization2.java Initialization2.java (MS-Word file)(MS-Word file)

Page 33: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Shorthand Assignment Shorthand Assignment StatementsStatements

Shorthand assignment notation combines the Shorthand assignment notation combines the assignment operatorassignment operator ( (==) and an ) and an arithmetic arithmetic operatoroperator

It is used to change the value of a variable by It is used to change the value of a variable by adding, subtracting, multiplying, or dividing by a adding, subtracting, multiplying, or dividing by a specified valuespecified value

The general form isThe general form isVariable OpVariable Op== Expression Expression

which is equivalent to which is equivalent to Variable Variable == Variable Op (Expression) Variable Op (Expression)

The The ExpressionExpression can be another variable, a constant, or a can be another variable, a constant, or a more complicated expressionmore complicated expression

Some examples of what Some examples of what OpOp can be are can be are ++, , --, , **, , //,, or or %%

1-33

Page 34: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Shorthand Assignment Shorthand Assignment StatementsStatements

Example:Example: Equivalent To:Equivalent To:

count += 2;count += 2; count = count + 2;count = count + 2;

sum -= discount;sum -= discount; sum = sum – discount;sum = sum – discount;

bonus *= 2;bonus *= 2; bonus = bonus * 2;bonus = bonus * 2;

time /= time /=

rushFactor;rushFactor;time = time =

time / rushFactor;time / rushFactor;

change %= 100;change %= 100; change = change % 100;change = change % 100;

amount *= amount *=

count1 + count2;count1 + count2;amount = amount * amount = amount * (count1 + count2);(count1 + count2);

1-34

Page 35: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Assignment Assignment CompatibilityCompatibility

In general, the value of one type cannot In general, the value of one type cannot be stored in a variable of another typebe stored in a variable of another type

int intVariable = 2.99; //Illegalint intVariable = 2.99; //Illegal The above example results in a type mismatch The above example results in a type mismatch

because a because a doubledouble value cannot be stored in an value cannot be stored in an intint variable variable

However, there are exceptions to thisHowever, there are exceptions to thisdouble doubleVariable = 2;double doubleVariable = 2;

For example, an For example, an intint value can be stored in a value can be stored in a doubledouble type type

1-35

Page 36: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Assignment Assignment CompatibilityCompatibility

More generally, a value of any type in the following More generally, a value of any type in the following list can be assigned to a variable of any type that list can be assigned to a variable of any type that appears to the right of itappears to the right of itbytebyteshortshortintintlonglongfloatfloatdoubledoublecharchar Note that as your move down the list from left to right, the Note that as your move down the list from left to right, the

range of allowed values for the types becomes largerrange of allowed values for the types becomes larger

An explicit An explicit type cast type cast is required to assign a value of is required to assign a value of one type to a variable whose type appears to the left one type to a variable whose type appears to the left of it on the above list (e.g., of it on the above list (e.g., doubledouble to to intint))

Note that in Java an Note that in Java an intint cannot be assigned to a cannot be assigned to a variable of type variable of type booleanboolean, nor can a , nor can a booleanboolean be be assigned to a variable of type assigned to a variable of type intint

1-36

MathOperations3.java MathOperations3.java (MS-Word file)(MS-Word file)

Page 37: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

ConstantsConstants ConstantConstant (or (or literalliteral): An item in Java which has ): An item in Java which has

one specific value that cannot changeone specific value that cannot change

Constants of an integer type may not be written with Constants of an integer type may not be written with a decimal point (e.g. a decimal point (e.g. 1010, not , not 10.010.0))

Constants of a floating-point type can be written in Constants of a floating-point type can be written in ordinary decimal fraction form (e.g., ordinary decimal fraction form (e.g., 367000.0367000.0 or or 0.0005890.000589) )

Constant of a floating-point type can also be written Constant of a floating-point type can also be written in in scientific scientific (or (or floating-pointfloating-point) ) notation notation (e.g., (e.g., 3.67e53.67e5 or or 5.89e-45.89e-4))

Note that the number before the Note that the number before the ee may contain a decimal may contain a decimal point, but the number after the point, but the number after the ee may not may not

1-37

Page 38: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

ConstantsConstants Constants of type Constants of type charchar are expressed by are expressed by

placing a single character in single quotes placing a single character in single quotes (e.g., (e.g., ''ZZ''))

Constants for strings of characters are Constants for strings of characters are enclosed by double quotes (e.g., enclosed by double quotes (e.g., ""WelcomeWelcome to Java"to Java"))

There are only two There are only two booleanboolean type type constants, constants, truetrue and and falsefalse Note that they must be spelled with all Note that they must be spelled with all

lowercase letterslowercase letters

1-38

Page 39: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Naming ConstantsNaming Constants Instead of using "anonymous" numbers in a program, Instead of using "anonymous" numbers in a program,

always declare them as named constants, and use their always declare them as named constants, and use their name insteadname instead

public static final int INCHES_PER_FOOT = 12;public static final int INCHES_PER_FOOT = 12;public static final double RATE = 0.14;public static final double RATE = 0.14;

This prevents a value from being changed inadvertently. It This prevents a value from being changed inadvertently. It alsohas the added advantage that when a value must be alsohas the added advantage that when a value must be modified, it need only be changed in one placemodified, it need only be changed in one place

Note the naming convention for constants: Use all uppercase Note the naming convention for constants: Use all uppercase letters, and designate word boundaries with an underscore letters, and designate word boundaries with an underscore charactercharacter

1-39Copyright © 2007 Pearson Addison-Wesley. Copyright © 2007 Aiman Hanna. All rights reserved.

MathOperations5.java MathOperations5.java (MS-Word file)(MS-Word file)

MathOperations4.java MathOperations4.java (MS-Word file)(MS-Word file)

Page 40: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Arithmetic Operators and Arithmetic Operators and ExpressionsExpressions

As in most languages, As in most languages, expressionsexpressions can be formed in Java using variables, can be formed in Java using variables, constants, and arithmetic operatorsconstants, and arithmetic operators

These operators are These operators are ++ (addition), (addition), -- (subtraction), (subtraction), ** (multiplication), (multiplication), // (division), and (division), and %% (modulo, remainder) (modulo, remainder)

An expression can be used anyplace it is An expression can be used anyplace it is legal to use a value of the type produced legal to use a value of the type produced by the expressionby the expression

1-40Copyright © 2007 Pearson Addison-Wesley. Copyright © 2007 Aiman Hanna. All rights reserved.

Page 41: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

If an arithmetic operator is combined with two If an arithmetic operator is combined with two intint operands, then the resulting type is operands, then the resulting type is intint

If an arithmetic operator is combined with one or If an arithmetic operator is combined with one or two two doubledouble operands, then the resulting type is operands, then the resulting type is doubledouble

If different types are combined in an expression, If different types are combined in an expression, then the resulting type is the right-most type on the then the resulting type is the right-most type on the following list that is found within the expressionfollowing list that is found within the expressionbytebyteshortshortintintlonglongfloatfloatdoubledoubleCharChar

Exception: If the type produced should be Exception: If the type produced should be bytebyte or or shortshort (according to the rules above), then the type produced will (according to the rules above), then the type produced will actually be an actually be an intint. In other words, an expression never . In other words, an expression never evaluates to the types byte or shortevaluates to the types byte or short

Arithmetic Operators and Arithmetic Operators and ExpressionsExpressions

1-41

Page 42: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Increment & Decrement Increment & Decrement OperatorsOperators

The The increment operatorincrement operator ( (++++) adds one ) adds one to the value of a variableto the value of a variable If If nn is equal to is equal to 22, then , then n++n++ or or ++n++n will will

change the value of change the value of nn to to 33

The The decrement operatordecrement operator ( (----) subtracts ) subtracts one from the value of a variableone from the value of a variable If If nn is equal to is equal to 44, then , then n--n-- or or --n--n will will

change the value of change the value of nn to to 33

1-42

Page 43: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

When either operator precedes its variable, and When either operator precedes its variable, and is part of an expression, then the expression is is part of an expression, then the expression is evaluated using the changed value of the variableevaluated using the changed value of the variable If If nn is equal to is equal to 66, then , then 2*(++n)2*(++n) evaluates to evaluates to 1414

When either operator follows its variable, and is When either operator follows its variable, and is part of an expression, then the expression is part of an expression, then the expression is evaluated using the original value of the variable, evaluated using the original value of the variable, and only then is the variable value changedand only then is the variable value changed If If nn is equal to is equal to 66, then , then 2*(n++)2*(n++) evaluates to evaluates to 1212

In both of the above cases, the value of n will In both of the above cases, the value of n will finally be changed to 7finally be changed to 7

1-43

Increment & Decrement Increment & Decrement OperatorsOperators

Page 44: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Parentheses and Parentheses and Precedence RulesPrecedence Rules

An expression can be An expression can be fully parenthesizedfully parenthesized in in order to specify exactly what sub-order to specify exactly what sub-expressions are combined with each expressions are combined with each operatoroperator

If some or all of the parentheses in an If some or all of the parentheses in an expression are omitted, Java will follow expression are omitted, Java will follow precedenceprecedence rules to determine, in effect, rules to determine, in effect, where to place themwhere to place them

However, it's best (and sometimes necessary) to However, it's best (and sometimes necessary) to include theminclude them

1-44

Page 45: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Precedence RulesPrecedence Rules

1-45

Page 46: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Precedence and Precedence and Associativity RulesAssociativity Rules

When the order of two adjacent When the order of two adjacent operations must be determined, the operations must be determined, the operation of higher precedence (and its operation of higher precedence (and its apparent arguments) is grouped before apparent arguments) is grouped before the operation of lower precedencethe operation of lower precedence

base + rate * hoursbase + rate * hours is evaluated as is evaluated asbase + (rate * hours)base + (rate * hours)

When two operations have equal When two operations have equal precedence, the order of operations is precedence, the order of operations is determined by determined by associativityassociativity rules rules

1-46

Page 47: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Precedence and Precedence and Associativity RulesAssociativity Rules

Unary operators of equal precedence are Unary operators of equal precedence are grouped right-to-leftgrouped right-to-left+-+rate+-+rate is evaluated as is evaluated as +(-(+rate))+(-(+rate))

Binary operators of equal precedence are Binary operators of equal precedence are grouped left-to-rightgrouped left-to-rightbase + rate + hoursbase + rate + hours is evaluated asis evaluated as

(base + rate) + hours(base + rate) + hours

Exception: A string of assignment operators is Exception: A string of assignment operators is grouped right-to-leftgrouped right-to-leftn1 = n2 = n3;n1 = n2 = n3; is evaluated asis evaluated as n1 = (n2 = n3);n1 = (n2 = n3);

1-47

Page 48: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Pitfall: Round-Off Errors in Pitfall: Round-Off Errors in Floating-Point NumbersFloating-Point Numbers

Floating point numbers are only approximate Floating point numbers are only approximate quantitiesquantities Mathematically, the floating-point number 1.0/3.0 Mathematically, the floating-point number 1.0/3.0

is equal to 0.3333333 . . .is equal to 0.3333333 . . .

A computer has a finite amount of storage spaceA computer has a finite amount of storage space It may store 1.0/3.0 as something like 0.3333333333, It may store 1.0/3.0 as something like 0.3333333333,

which is slightly smaller than one-thirdwhich is slightly smaller than one-third

Computers actually store numbers in binary Computers actually store numbers in binary notation, but the consequences are the same: notation, but the consequences are the same: floating-point numbers may lose accuracyfloating-point numbers may lose accuracy

1-48

Page 49: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Integer and Floating-Integer and Floating-Point DivisionPoint Division

When one or both operands are a floating-point When one or both operands are a floating-point type, division results in a floating-point typetype, division results in a floating-point type15.0/215.0/2 evaluates toevaluates to 7.57.5

When both operands are integer types, division When both operands are integer types, division results in an integer typeresults in an integer type Any fractional part is discarded Any fractional part is discarded The number is not roundedThe number is not rounded

15/215/2 evaluates toevaluates to 77

Be careful to make at least one of the operands a Be careful to make at least one of the operands a floating-point type if the fractional portion is floating-point type if the fractional portion is neededneeded

1-49

Page 50: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The The %% (Modula) Operator (Modula) Operator The The %% operator is used with operands of operator is used with operands of

type type intint to recover the information lost to recover the information lost after performing integer divisionafter performing integer division15/215/2 evaluates to the quotientevaluates to the quotient 7715%215%2 evaluates to the remainderevaluates to the remainder 1116%416%4 evaluates to the remainderevaluates to the remainder 00

The The %% operator can be used to count by 2's, operator can be used to count by 2's, 3's, or any other number3's, or any other number To count by twos, perform the operation To count by twos, perform the operation numbernumber % 2% 2, and when the result is , and when the result is 00, , numbernumber is even is even

1-50

Page 51: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Type CastingType Casting A A type casttype cast takes a value of one type and produces a takes a value of one type and produces a

value of another type with an "equivalent" valuevalue of another type with an "equivalent" value

If If nn and and mm are integers to be divided, and the fractional are integers to be divided, and the fractional portion of the result must be preserved, at least one of the portion of the result must be preserved, at least one of the two must be type cast to a floating-point type two must be type cast to a floating-point type beforebefore the the division operation is performeddivision operation is performeddouble ans = n / (double)m;double ans = n / (double)m;

Note that the desired type is placed inside parentheses Note that the desired type is placed inside parentheses immediately in front of the variable to be castimmediately in front of the variable to be cast

Note also that the type and value of the variable to be cast Note also that the type and value of the variable to be cast does not changedoes not change

1-51

MathOperations6.java MathOperations6.java (MS-Word file)(MS-Word file)

Page 52: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

More Details About Type More Details About Type CastingCasting

When type casting from a floating-point to an When type casting from a floating-point to an integer type, the number is truncated, not integer type, the number is truncated, not roundedrounded (int)2.9(int)2.9 evaluates to evaluates to 22, not , not 33

When the value of an integer type is assigned to When the value of an integer type is assigned to a variable of a floating-point type, Java performs a variable of a floating-point type, Java performs an automatic type cast called a an automatic type cast called a type coerciontype coercion

double d = 5;double d = 5; In contrast, it is illegal to place a In contrast, it is illegal to place a doubledouble value value

into an into an intint variable without an explicit type cast variable without an explicit type castint i = 5.5; // Illegalint i = 5.5; // Illegalint i = (int)5.5 // Correctint i = (int)5.5 // Correct

1-52

Page 53: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Escape SequencesEscape Sequences

A backslash (A backslash (\\) immediately preceding a ) immediately preceding a character (i.e., without any space) character (i.e., without any space) denotes an denotes an escape sequenceescape sequence or an or an escape characterescape character

The character following the backslash does The character following the backslash does not have its usual meaningnot have its usual meaning

Although it is formed using two symbols, it Although it is formed using two symbols, it is regarded as a single characteris regarded as a single character

1-53

Page 54: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Escape SequencesEscape Sequences

1-54

Page 55: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

CommentsComments A A line commentline comment begins with the begins with the

symbols symbols ////, and causes the compiler to , and causes the compiler to ignore the remainder of the lineignore the remainder of the line This type of comment is used for the code This type of comment is used for the code

writer or for a programmer who modifies the writer or for a programmer who modifies the codecode

A A block commentblock comment begins with the symbol begins with the symbol pair pair /*/*, and ends with the symbol pair , and ends with the symbol pair */*/ The compiler ignores anything in betweenThe compiler ignores anything in between This type of comment can span several linesThis type of comment can span several lines This type of comment provides documentation This type of comment provides documentation

for the users of the programfor the users of the program

1-55

Page 56: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Comments & Named Comments & Named ConstantConstant

1-56

Page 57: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

The Class The Class StringString There is no primitive type for strings in JavaThere is no primitive type for strings in Java

The class The class StringString is a predefined class in Java is a predefined class in Java that is used to store and process stringsthat is used to store and process strings

Objects of type Objects of type StringString are made up of strings of are made up of strings of characters that are written within double quotescharacters that are written within double quotes Any quoted string is a constant of type Any quoted string is a constant of type StringString

"Live long and prosper.""Live long and prosper."

A variable of type A variable of type StringString can be given the value can be given the value of a of a StringString object objectString blessing = "Live long and prosper.";String blessing = "Live long and prosper.";

1-57

Page 58: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Concatenation of StringsConcatenation of Strings ConcatenationConcatenation: Using the : Using the ++ operator on two operator on two

strings in order to connect them to form one longer strings in order to connect them to form one longer stringstring If If greetinggreeting is equal to is equal to "Hello"Hello "", and , and javaClassjavaClass is equal is equal

to to "class""class", then , then greeting + javaClassgreeting + javaClass is equal to is equal to "Hello class""Hello class"

Any number of strings can be concatenated Any number of strings can be concatenated togethertogether

When a string is combined with almost any other When a string is combined with almost any other type of item, the result is a stringtype of item, the result is a string "The answer is " + 42"The answer is " + 42 evaluates to evaluates to "The answer is 42""The answer is 42"

1-58

Page 59: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Classes, Objects, and Classes, Objects, and MethodsMethods

A A classclass is the name for a type whose values are objects is the name for a type whose values are objects

ObjectsObjects are entities that store data and take actions are entities that store data and take actions Objects of the Objects of the StringString class store data consisting of class store data consisting of

strings of charactersstrings of characters

The actions that an object can take are called The actions that an object can take are called methodsmethods Methods can return a value of a single type and/or Methods can return a value of a single type and/or

perform an actionperform an action All objects within a class have the same methods, All objects within a class have the same methods,

but each can have different data valuesbut each can have different data values

1-59

Page 60: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Classes, Objects, and Classes, Objects, and MethodsMethods

InvokingInvoking or or calling a methodcalling a method: a method is : a method is called into action by writing the name of called into action by writing the name of the calling object, followed by a dot, the calling object, followed by a dot, followed by the method name, followed by followed by the method name, followed by parenthesesparentheses

The parentheses contain the information (if The parentheses contain the information (if any) needed by the methodany) needed by the method

This information is called an This information is called an argumentargument (or (or argumentsarguments))

1-60

Page 61: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

String MethodsString Methods The The StringString class contains many useful methods class contains many useful methods

for string-processing applicationsfor string-processing applications

A A StringString method is called by writing a method is called by writing a StringString object, a object, a dot, the name of the method, and a pair of parentheses to dot, the name of the method, and a pair of parentheses to enclose any argumentsenclose any arguments

If a If a StringString method returns a value, then it can be placed method returns a value, then it can be placed anywhere that a value of its type can be usedanywhere that a value of its type can be usedString greeting = "Hello";String greeting = "Hello";int count = greeting.length();int count = greeting.length();System.out.println("Length is " + System.out.println("Length is " + greeting.length());greeting.length());

Always count from zero when referring to the Always count from zero when referring to the positionposition or or index index of a character in a stringof a character in a string

1-61

Page 62: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 1 of 8)(Part 1 of 8)

1-62

Page 63: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 2 of 8)(Part 2 of 8)

1-63

Page 64: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 3 of 8)(Part 3 of 8)

1-64

Page 65: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 4 of 8)(Part 4 of 8)

1-65

Page 66: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 5 of 8)(Part 5 of 8)

1-66

Page 67: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 6 of 8)(Part 6 of 8)

1-67

Page 68: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 7 of 8)(Part 7 of 8)

1-68

Page 69: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Some Methods in the Class Some Methods in the Class StringString (Part 8 of 8)(Part 8 of 8)

1-69

Strings1.java Strings1.java (MS-Word file)(MS-Word file)

Page 70: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

String IndexesString Indexes

1-70

Page 71: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

String ProcessingString Processing A A StringString object in Java is considered to be object in Java is considered to be

immutable, i.e., the characters it contains cannot immutable, i.e., the characters it contains cannot be changedbe changed

There is another class in Java called There is another class in Java called StringBufferStringBuffer that has methods for editing its that has methods for editing its string objectsstring objects

However, it is possible to change the value of a However, it is possible to change the value of a StringString variable by using an assignment variable by using an assignment statementstatement

String name = "Soprano";String name = "Soprano";name = "Anthony " + name;name = "Anthony " + name;

1-71

Page 72: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Character SetsCharacter Sets ASCIIASCII: A character set used by many : A character set used by many

programming languages that contains all the programming languages that contains all the characters normally used on an English-language characters normally used on an English-language keyboard, plus a few special characterskeyboard, plus a few special characters Each character is represented by a particular numberEach character is represented by a particular number

UnicodeUnicode: A character set used by the Java : A character set used by the Java language that includes all the ASCII characters language that includes all the ASCII characters plus many of the characters used in languages plus many of the characters used in languages with a different alphabet from Englishwith a different alphabet from English

1-72

Page 73: Comp 248 Introduction to Programming Chapter 1 - Getting Started Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,

Program DocumentationProgram Documentation Java comes with a program called Java comes with a program called javadocjavadoc that will automatically extract that will automatically extract documentation from block comments in documentation from block comments in the classes you definethe classes you define As long as their opening has an extra asterisk As long as their opening has an extra asterisk

((/**/**))

Ultimately, a well written program is self-Ultimately, a well written program is self-documentingdocumenting Its structure is made clear by the choice of Its structure is made clear by the choice of

identifier names and the indenting patternidentifier names and the indenting pattern When one structure is nested inside another, When one structure is nested inside another,

the inside structure is indented one more levelthe inside structure is indented one more level

1-73