Http://vm Vladimir Misic: [email protected] Java1 Week 2 – Java and more.

91
Java 1 http://www.cs.rit.edu/~vm Vladimir Misic: [email protected] Week 2 – Java and more

Transcript of Http://vm Vladimir Misic: [email protected] Java1 Week 2 – Java and more.

Java 1 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Week 2 – Java and more

Java 2 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Programming

• For the next ten weeks you will learn basic programming principles– There is much more to programming than knowing a

programming language

• When programming you need to use a tool, in this case the tool will be a language– In this course you will use java to explore programming

– You will use other languages to program

Java 3 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Syntax and Semantics

• When using a programming language you must understand both the syntax and the semantics of the language.– Syntax refers to the rules you must follow to form valid

statements in the language.• The syntax of a language is like English grammar.

– Semantics describe the meaning of a statement in a language.

Java 4 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

What Is Java?

• Java started as a programming language for embedded systems (toasters, microwave ovens, washers, etc.).– needed to be portable.

– had to be reliable.

• The original language was called oak (rumor has it that Gosling has a large oak tree outside the window of his office). Marketing decided Java was a better name.

Java 5 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Sun’s Slant

• According to Sun:– Java is a simple, object-oriented, distributed, interpreted,

robust, secure, architecture neutral, portable, high-performance, multithreaded, and dynamic language

• Java is a lot like C/C++ but there are a number of important differences

Java 6 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Program Structure

• A program in Java consists of one or more class definitions. One of these classes must define a method main( ), which is where the program starts running

// A Java Hello World Program

public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello World" ); }}

// A Java Hello World Program

public class HelloWorld { public static void main( String args[] ) { System.out.println( "Hello World" ); }}

Java 7 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

How Is Java Different

• Java differs from other popular languages:– It is interpreted

– Architecture neutral

– There are no C/C++ style pointers, only references

– Garbage collected

– Comes with a sophisticated class library

– Includes support for concurrency, networking, and graphics

Java 8 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Interpreted Languages

• An interpreter translates and immediately executes a program– Someone, who understands German, reads the book in

German and translates while reading to English

Source Code Execute

interpret

Java 9 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Executing Java Programs

Win98/NT JVM MacOS JVM Solaris JVM

Java Source Program

Java Class File

Java Compiler

emacs filename.java

javac filename.java

java filename

Java 10 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Java Environments

• There are lots of commercial Java programming environments.– IBM’s Visual Age.

– Visual J++.

– Semantic Café.

– many others (most of which cost money).

• Sun provides the JDK (Java development Kit) for free.

Java 11 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

The JDK

• The JDK consists of the following:– The Java development tools, including the compiler,

debugger and the Java Interpreter.

– The Java class libraries organized as a collection of packages.

– A number of demonstration programs.

– Various supporting tools and components, including the source code of the classes in the library.

• Get it from http://www.java.sun.com.

Java 12 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Java Resources

• Java Home Page– http://www.java.sun.com (http://www.javasoft.com)

• The Java Tutorial– http://www.java.sun.com/docs/books/tutorial

• Java Developer Connection– http://developer.java.sun.com

• The Swing Connection– http://java.sun.com/products/jfc/tsc

Java 13 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Other Resources

• RIT Course Pages– http://www.cs.rit.edu/~cs1

• NT-EMACS– http://www.cs.washington.edu/homes/voelker/

ntemacs.html

• JDE– http://sunsite.auc.dk/jde/

Java 14 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Applications and Applets

• Java programs come in two forms:– Applications.

– Applets.

• Applets typically are downloaded into a browser and are run by the Java Virtual Machine that is part of the browser.– Usually are restricted as to what they can do.

• Applications are standalone programs that can do just about anything.

Java 15 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Basic Java Syntax

• The Java language will be described by working through its features:– variable types and expressions.

– selection and iteration.

– classes.

– exceptions.

• Small sample programs will be provided to illustrate how each feature is used.

Java 16 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Things & Stuff

• Any program that you will write will manipulate things– Numbers

– Strings

– Objects

– …

• We need to be able to refer to these sorts of items in a program

Java 17 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Identifiers

• Identifiers are used in a programming language to refer to things– You can think of an identifier as a shortcut to a memory

location somewhere in the computer

• Declarations in a program introduce identifiers and the type of thing they will refer to

• All identifiers must be declared before they may be used

Java 18 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Rules

• Identifiers– start with an alphabetic character

– can contain letters, digits, or “_”

– are unlimited in length

• Examples

Answer, total, last_total, relativePosition, gridElementPerson, Place, Stack, Queue

Java 19 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Identifiers

• Identifiers in Java are composed of a series of letters and digits where the first character must be a letter.– Identifiers should help to document what a classes,

variables, or methods are used for.

– Upper and lower case letters are different in Java.• ThisOne is not the same as thisOne.

– Identifiers should not include punctuation and can not include spaces.

Java 20 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Identifiers

– A good programming standard for identifiers composed of multiple words is to capitalize the first character of the additional words.

• The case of the first letter of the first word will depend upon the use of the identifier.

• For Example,– myCar, or bobAndSusieAreFriends

Java 21 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Identifiers

• Class names begin with a capital letter.– This standard makes it easier to understand which

identifiers represent classes.

– In the MyFirstApplication we have two class names:• MyFirstApplication and MainWindow

Java 22 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Identifiers

• Variable (object names) and method names begin with a lower case letter.– In MyFirstApplication we have one object:

• mainWindow

• Note that mainWindow is different from MainWindow.

– In MyFirstApplication we have one method:• main(…)

Java 23 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Creating a Java Program

• The first step to creating a Java program is to define a class containing the main method.– The MyFirstApplication program on page 39 of Wu is an

example of a Java class containing a main method.• This Java class definition can be thought of as the driver class or

the ring leader class.

Java 24 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Declaring Variables

• The basic syntax for declaring variables is:– typename identifer;

• It is possible to declare two or more variables of the same type in a single declaration statement, although this is NOT recommended (See RIT Java Coding Standard).

Java 25 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Categories of Variables

• There are two categories of variables:– Variables of primitive type which directly contain a

representation of a value of a primitive type.

– Variables of a reference type which hold a reference to an object or the value null (which is the null reference).

• All variables must be declared and initialized before being used.

Java 26 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Primitive Types

• The primitive types represent the basic, built-in types that are part of the Java language.

• Two basic categories:– Boolean - boolean.

– Numeric.• Integer - byte, short, int, long, char.

• Floating point - float, double.

Java 27 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Primitive Data Types

• The Java primitive data types each have a set size (# of bits) and value range.

• Same on every type of computer (PC, Mac, Sun workstation) that runs Java programs.

• This is not true with other programming languages.

Java 28 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Primitive Types

Type Descriptionboolean Has two values, true and false.byte 8-bit signed 2’s complement integers, range: -128 to 127short 16-bit signed 2’s complement integers, range: -32768 to 32767int 32-bit signed 2’s complement integers, range: -2147483648 to

2147483647long 64-bit signed 2’s complement integers, range: -

9223372036854775808 to 9223372036854775807char 16-bit unsigned values from 0 to 65535, representing Unicode

charactersfloat Single precision, 32-bit format IEEE 754 floating-point values, range:

1.40239846e-45 to 3.40282347e+38double Double precision, 64-bit format IEEE 754 floating-point values,

range: 4.9406564581246544e-324 to 1.79769313486231570e+308

There are special floating point values: ‘positive infinity’, ‘negativeinfinity’, and ‘not a number’ (NaN).

Note: these types are platform independent

Java 29 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Primitive Types

Java 30 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Real Values

• Real or floating point numbers are represented in scientific notation inside a computer. The number is divided up into two parts the mantissa and the exponent:

• The mantissa contains a number between -1.0 and 1.0

• The exponent contains the power of 2 required to scale the number to its actual value.

• Value = mantissa * 2exponent

Java 31 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Real Values

• Real numbers are characterized by their precision and range.

• Precision is the number of significant digits that is represented in the number.– Depends upon the number of bits in the mantissa.

• Range is the difference between the largest and smallest numbers that can be represented.– Depends upon the number of bits in the exponent.

Java 32 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Real Values – Real Data Types

• float uses 32 bits and represents the numbers -3.40292347E+38 to 3.40292347E+38– The mantissa is 24 bits and the exponent is 8 bits.

– 6 to 7 decimal digits of precision.

• double uses 64 bits and represents the numbers -1.79769313486231570E+308 to 1.79769313486231570E+308. – The mantissa is 53 bits and the exponent is 11 bits

– 15 to 16 decimal digits of precision.

– The double data type is more precise than float.

Java 33 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Real Values – Round-Off Error

• When a double is stored as a float, part of the number is lost because a double is much larger than a float. The float cannot represent the same exact number. In this situation, the seven most significant digits are preserved and the rest of the information is lost.

• It is important to know which real data type is required for your calculations.

Java 34 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Character Values

• May be printable and non-printable characters– some printable characters are: 'a', '%'

– some non-printable characters are: newline - '\n', tab - '\t', carriage return - '\r‘

• Unicode escapes allow any character to be represented regardless of the editor being used

• A Unicode escape stands for a character and is represented using the \u escape sequence followed by the hexadecimal digits of the character code

• Examples: \u0343, \u2f4, \uabcd

Java 35 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Unicode

• An International Standard that defines the representation of characters from a wide range of alphabets.

• Unicode stores characters as 16-bit values providing 65,536 different characters.

• ASCII happens to be the first 127 characters in the Unicode standard.

• Java uses Unicode as opposed to ASCII.

Java 36 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Literals

Type ExamplesInteger 0, 123, -456, 55665, …

00, 0123, 0777, -045323, …0x0, 0x125, -0xffed, 0xfff

Literals of type long (64-bit) are denoted by appending L orl to any integer literal.

Floating point 1.2345, 1234.423, 0.1, -1.23, …

By default floating point literals are of type double. If theliteral is suffixed with F or f it will be of type float.

Boolean true, falseCharacters ‘a’, ‘A’, ‘!’, …

‘\b’, ‘\f’, ‘\n’, ‘\r’, ‘\t’, ‘\\’, ‘\’’Strings “This is a string”, “Hello World\n”Null null

Java 37 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assignment

• Declarations associates a type with an identifier• Assignment associates a value with an identifier

– Assignment is represented by = sign

– An identifier will always be on the left side of the equals sign

– The computer will place a copy of the thing on the right into the area named by the identifier on the left

• Assignment is not the same as algebraic equality

Java 38 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assignment Statements

• The basic syntax of an assignment statement is:– <variable> = <expression>;

– The expression is evaluated and the result is assigned to the variable name on the left of the equals sign.

• In this case ‘=‘ means assigned and is called an assignment operator.

• The expression is any valid combination of constants, variables, parenthesis, and arithmetic or boolean operators.

Java 39 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assignment Statements

• An assignment statement can be used to put values into a variable both by simple assignment or by an expression.

– zebraCount = 5;

– zebraCount = zebraCount + numInHerd * 0.3;

Java 40 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Arithmetic Operators

• The following table summarizes the arithmetic operators available in Java.

This is an integer division where the fractional part is truncated.

This is an integer division where the fractional part is truncated.

Java 41 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

uThings Affecting How Expressions are

Evaluated

• Operator Precedence• Numeric Promotion• Assignment Conversion• Casting Conversion

Java 42 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Precedence and Operators

Description Syntaxunary postfix [] . () ++ --unary prefix ++ -- + - ~ !creation and cast new ( type )multiplicative * / %additive + -shift << >> >>> (unsigned right shift)relational < > >= <= instanceofequality == !=and &xor ^or |boolean and &&boolean or ||conditional ?:assignment = += -= *= /= %= >>= <<=

>>>= &= ^= |=

Highest

Lowest

Java 43 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

X = (1 + ( 2 - 4 + 6) * ( 5 + 3 * 5 ) - 16 )

• First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis.

• Second all multiplications, divisions, and modulus operations are calculated from left to right.

• Third all additions and subtractions are evaluated from left to right.

Operator Precedence

Java 44 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Mixed Mode Expressions

• What happens if an expression contains two different types of numbers?– For example, 4 + 5 * .56;

• In most cases Java will automatically convert the values in the expression so that it may be evaluated

• What kind of variable can we directly store the results of this expression in?

Java 45 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

uAutomatic Type Conversion

(Numeric Promotion)

• Java provides a variety of automatic type conversions.

• The following conversions are supported:– Widening (range!) primitive conversions.

• byte to short, int, long, float, or double.

• short to int, long, float, or double.

• int to long, float, or double.

• long to float or double.

• float to double.

Java 46 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assignment Conversion

• Assignment conversion occurs when the result of the expression is a different data type than the data type of the result. – Widening conversion occurs when the result is promoted

to a larger data type. • For instance, an integer result is promoted to a double data type

because the result is stored into a double data type variable.

• Happens automatically in Java

Java 47 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assignment Conversion

– Narrowing conversion occurs when the result is demoted to a smaller data type.

• For instance, a double result is to be stored in an integer result.

• This is not allowed to automatically occur in Java and will result in a compile time error.

• This is allowed in Java if a cast operator is used.

Java 48 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Casting Conversion

• In some situations Java will not perform automatic conversions– int x = 3.1456;

• In these cases you can force a conversion by specifying a cast– int x = (int)3.1456;

• Here information is lost, but the assignment will take place

Java 49 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Casting Conversion

• Widening conversion using type casting is legal in Java and can remove any ambiguities as to the resultant value.

• Narrowing conversion using type casting is legal in Java but is discouraged because you are loosing value precision when this is done.– int x = (int) 89.99;

• x = 89

– int x = (int) 50235645642L;• x = 2147483648

Java 50 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assignment Operators

• We have seen Java’s basic assignment operator, but Java also has some special assignment operators that combine the assignment operator with a binary operator in a single statement. – Such operators can be used to create short cuts in your

code.

Java 51 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assignment Operators

• The += operator allows you to represent: a = a + 1 as a += 1.– The 1 is added to the value of a and stored back into a.

– a += c; a += 984;

• In addition to the += operator there are:– a -= 5; which is the same as a = a - 5;

– a *= c; which is the same as a = a * c;

– a /= 2; which is the same as a = a / 2;

– a %= 4; which is the same as a = a % 4;

Java 52 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Increment/Decrement Operators

• Java contains two unary operators the increment ++ and decrement -- operators. – When these operators are combined with an integer

variable, they increment or decrement that variable by 1.

• a++ == a = a + 1 == a +=1

• a-- == a = a - 1 == a -=1

Java 53 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Increment/Decrement Operators

• There are two types of increment and decrement operators called preincrement/decrement and postincrement/decrement.– A preincrement looks like: ++a and a predecrement looks

like: --a

– A postincrement looks like: a++ and a postdecrement looks like: a--

Java 54 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Increment/Decrement Operators

• The Preincrement/decrement operators– place the ++ or -- before the variable name

– and cause the variable to be incremented or decremented before it is used in an expression.

• Assume a = 5, what is: b given b = ++a + 6?

• What is b given b = --a + 7?

Java 55 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Increment/Decrement Operators

• The Postincrement/decrement operators– place the ++ or -- after the variable name

– and cause the variable to be incremented or decremented after it is used in an expression.

• Assume a = 5, what is b given b = a++ + 6?

• What is b given b = a-- + 7?

Java 56 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Increment/Decrement Operators

• It is legal to combine increment and decrement operators but can become very confusing.– Assume a = 7,

• What is the result of: ++--a++++– Error!!!! ++ or – can only apply to simple variables, not

expressions!

• It is best to avoid combining multiple increment and decrement operators.

Java 57 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Constant Data Values

• A constant is a value in a program that is assigned an initial value but can not be changed while the program runs.– If a program attempts to change a constant the result is a

syntax error.

– The keyword final is used to signify that a value is a constant. (I.e., this is the FINAL value this variable will ever have!)

– The data value can be referenced in the program using it’s name.

Java 58 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Constants

• We can change the value of a variable. If we want the value to remain the same, we use a constant.

final double PI = 3.14159;* final float PI_FLOAT = (float) 3.1; final int MONTH_IN_YEAR = 12; final short FARADAY_CONSTANT = (short) 23060;

These are constants, also called named constant.

These are constants, also called named constant.

The reserved word final is used to declare constants.

The reserved word final is used to declare constants.

These are called literal constant.

These are called literal constant.

* A real literal is double by default

Java 59 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Mathematical Methods

• Java provides a Math library (class file) that implements many common mathematical functions. – The Math class contains mathematical constants such as

PI (Math.PI).

Java 60 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

The Math Class

• The Math class in the java.lang package includes many common and useful mathematical functions such sin, cos, tan, square root, exponentiation, and others.

• The mathematical formula

is expressed in Java as Math.abs( Math.sin( Math.PI / 4.0) * x )

OR?

Math.abs( Math.sin( Math.PI / 4.0 * x ))

• See Table 3.5 page 101

Java 61 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Mathematical Methods

• Assume that we want to calculate the following: y = sin( x * 3.14159 )

• Assume y is a double and that x is an int.– final double DEG_2_RAD = Math.PI / 180;

– int x = 8;

– double y = Math.sin( x * DEG_2_RAD );

Java 62 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Overloaded Math Methods

• If you look at the table for the absolute value function you will notice that it can take float, double, int, or long as its input parameter. – The abs method is said to be overloaded because there

are three separate definitions or versions. The versions of abs differ only in the type of the input parameter.

• The methods have the same name, the same functionality, but have different parameter types.

• Java knows which version to call based upon the data type of the parameter passed to the method. The result is a;ways the same parameter data type.

Java 63 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Math Methods using Coercion

• Some Math methods only work with a specific data type but they still accept parameters of other data types. – Java will automatically convert the other data type into

the preferred data type before executing the method, this is call coercion of arguments.

• For instance the square root method, Math.sqrt(x) requires a parameter of type double. If x is of type byte, short, int, long, or float, Java will automatically convert x to type double. This method only returns a double.

Java 64 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Declaring Objects (Reference Types)

• In order to create objects to work within a Java program they must first be declared.– The object declaration includes the class name that the

object belongs to and the variable name for the object.

– The format for declaring an object is:<class name> <object(variable) name> ;

– The class must be defined before you can declare the object.

Java 65 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Declaring Objects (Reference Types)

• Think about our cars. – Car was the class name and we had three instances of

the this class.

– To declare each of the cars we had created we would type:

Car clintsPorsche;

Car jessicasBMW;

Car johnsLamborghini;

Java 66 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Reference Types (Objects)

• Reference types are used to declare variables that will refer to objects

• The JDK provides a number of classes– The String class allows us to declare, create, and

manipulate strings

• Declaring a string is no different from declaring a primitive type:– String name;

Java 67 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Object Instantiation=Object Creation

<class name> <object name>;

<object name> = new <class name> (<arguments>);

• The <object name> is the name(identifier) for the object as you declared it in your program.

• The <class name> is the name of the class that this object has been declared to belong to.

• The <arguments> represent possible data that may be required to create the object instance, i.e. needed by the constructor.

Java 68 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Creating Objects

• Before a reference to an object may be assigned to a variable, the object must be created– Operator new is used to create new objects– String name = new String();– String name =

new String( “Computer Science 1” );

– String name = “Computer Science 1”;

Java 69 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Reference Variables

• These variables/identifiers refer to objects; they do not contain the object

• Several different variables may all refer to the same object

• If an object is not referred to by any variables, the object will eventually be destroyed

Java 70 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Primitive Data Declaration and Assignments

Code State of Memory

int firstNumber, secondNumber;firstNumber = 234;secondNumber = 87;

AAint firstNumber, secondNumber;int firstNumber, secondNumber;

BBfirstNumber = 234;firstNumber = 234;secondNumber = 87;secondNumber = 87;

int firstNumber, secondNumber;int firstNumber, secondNumber;firstNumber = 234;firstNumber = 234;secondNumber = 87;secondNumber = 87;

firstNumber

secondNumber

A. A. Variables are allocated in memory.

A. A. Variables are allocated in memory.

B. B. Values are assigned to variables.

B. B. Values are assigned to variables.

234

87

Java 71 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assigning Numerical Data

Code State of Memory

int number;int number;number = 237;number = 237;number = 35;number = 35; number

A. A. The variable is allocated in memory.

A. A. The variable is allocated in memory.

B. B. The value 237237 is assigned to numbernumber.

B. B. The value 237237 is assigned to numbernumber.

237

int number;int number;

number = 237;number = 237;

number = 35;number = 35;

AAint number;int number;

BBnumber = 237;number = 237;

CCnumber = 35;number = 35;

C. C. The value 3535 overwrites the

previous value 237.237.

C. C. The value 3535 overwrites the

previous value 237.237.

35

Java 72 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Assigning Objects

Code State of Memory

Customer customer;Customer customer;customer = new Customer( );customer = new Customer( );customer = new Customer( );customer = new Customer( );

customer

A. A. The variable is allocated in memory.

A. A. The variable is allocated in memory.Customer customer;Customer customer;

customer = new Customer( );customer = new Customer( );

customer = new Customer( );customer = new Customer( );

AA

Customer customer;Customer customer;BB

customer = new Customer( );customer = new Customer( );

CC

customer = new Customer( );customer = new Customer( );B. B. The reference to the

new object is assigned to customercustomer.

B. B. The reference to the new object is assigned to customercustomer.

CustomerCustomer

C. C. The reference to another object overwrites the reference in customer.customer.

C. C. The reference to another object overwrites the reference in customer.customer.

CustomerCustomer

Java 73 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Having Two References to a Single Object

Code State of Memory

Customer clemens, twain;Customer clemens, twain;clemens = new Customer( );clemens = new Customer( );twain = clemens;twain = clemens;

Customer clemens, twain,Customer clemens, twain,

clemens = new Customer( );clemens = new Customer( );

twain = clemens;twain = clemens;

AA

Customer clemens, twain;Customer clemens, twain; BB

clemens = new Customer( );clemens = new Customer( );

CC

twain = clemens;twain = clemens;

A. A. Variables are allocated in memory.

A. A. Variables are allocated in memory.

clemens

twain

B. B. The reference to the new object is assigned to clemensclemens.

B. B. The reference to the new object is assigned to clemensclemens.

CustomerCustomer

C. C. The reference in clemensclemens is assigned to

customer.customer.

C. C. The reference in clemensclemens is assigned to

customer.customer.

Java 74 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Types of Methods

There are 4 basic types of methods:

• Modifier (sometimes called a mutator)– Changes the value associated with an attribute of the object (or

class)• Accessor

– Returns the value associated with an attribute of the object (or class)

• Constructor– Called once when the object is created (before any other method

will be invoked)• Destructor

– Called when the object is destroyed

Java 75 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Methods

• A reference to an object can be used to invoke a method of the object– The dot (.) operator specifies method invocation

• An attempt to invoke a method using a null reference is an error

In other words, to call the method, you have to write the name of the object, dot, and the name of the method (e.g. myCar.start( ) );

Java 76 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

What Methods?

• How do you know what methods are available for a given object?– Look at the class definition

– Look at the documentation for the class

• The JDK provides documentation for its classes using a tool called JavaDoc

Java 77 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Message Passing

• Once an object exists, the program can begin to send messages to the object.– The message must include the object to which the

message is addressed, the name of the task to be completed, and any data required to complete the task.

– In Java speak:

<object name>.<method name>(<arguments>);

Receiving object

Method name

Parameters

customer.getAccountBalance(accNum)

Java 78 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Message Passing

• Let’s create messages for cars.– We need to know how much gas BMW has.

bmw.getGasLevel();

– We want to remotely start Audi.audi.remoteStart();

Java 79 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Method Declarations

• The method declaration provides the function implementation in the program. – The basic format of a method declaration is:

<modifiers> <return type> <method name> (<parameters>) {

<method body>

}

Java 80 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

• The return type is the data type of the value returned by the method.

•If the method does not return a value this value is void.

• Modifiers represent terms that determine what kind of method is declared. (Chap 4)

Method Declarations

<modifiers> <return type> <method name> (<parameters>) {

<method body>

}

Java 81 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

• The method body includes the code statements that implement the task.

• The parameters are the data that the method requires to complete the task.

• The method name should identify the task to be completed by the method

Method Declarations

<modifiers> <return type> <method name> (<parameters>) {

<method body>

}

Java 82 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Method Declarations

<modifiers> <return type> <method name> (<parameters>) {

<method body>

}

public double getAccountBalance(accNum) {

return accountBalance[accNum];

}

public double getAccountBalance(accNum) {

return accountBalance[accNum];

}

Java 83 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Class Declarations

• Java programs are composed of one or more classes.– Some classes are already defined in Java but we also

need to be able to define our own classes.

class <class name> {

<class member declarations>

}

Java 84 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

• The class member declarations include method definitions and variable (data value) declarations.

• Every class must have unique name

Class Declarations

class <class name> {

<class member declarations>

}

Java 85 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Class Declarations

• One class in every program must include the main method. – This class is the driver class.

– The main method is the first method that is called when a program is executed.

public class PointTest { public static void main( String args[] ) {

Point myPoint = new Point( 12, 34 );System.out.println( myPoint.getCoordinates() );

}}

public class PointTest { public static void main( String args[] ) {

Point myPoint = new Point( 12, 34 );System.out.println( myPoint.getCoordinates() );

}}

Java 86 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Import Statement

• The import statement is used to allow a class definition to access predefined Java classes.– Related predefined Java classes are stored in packages.

– In order to import predefined classes:

import <package name>.<class name>;

Java 87 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Import Statement

import <package name>.<class name>;

– The package name represents the the particular package to look into for the class name.

• java.*

– The class name can be a specific class or every class in the package.

import javabook.MainWindow;

import javabook.*;

Java 88 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Comments

• Providing a description of what the program does is called commenting the code.– Commenting is used to provide an overall description of the class

and what it does, who the author is, when the class was created and modified, etc. – Header comments (See Java Coding Standard!)

– Commenting is also used throughout your code to provide a description of a method, as well as to provide descriptions of complicated code.

– The use of meaningful variable and method names helps “comment” the code.

Java 89 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Comments

• Java provides three ways to comment code.– The /* …. */ is used for multiple line comments.

– The // is used for a single line comment.

– The javadoc comments:

/** * This program prints Hello World on the screen * * @author Vladimir Misic*/

Java 90 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u/* * HelloWorld.java * * Version: * $Id$ * * Revisions: * $Log$ */

import java.*;

/** * This program prints Hello World on the screen * * @author Paul Tymann*/

public class HelloWorld {

}

/** * The main program. * * @param args command line arguments (ignored) */

public static void main( String args[] ) { System.out.println( "Hello World" ); }

Java Coding Standard Comments for Hello World

Java Coding Standard Comments for Hello World

Java 91 http://www.cs.rit.edu/~vm

Vla

dim

ir M

isic

: vm

@cs

.rit

.ed

u

Creating a Java Program

• The filename.class file is interpreted by the Java interpreter every time it is run.

Editor

Filename.java Filename.class

Java Compiler

JavaInterpreter

OnlyOnce

EveryTime

javac Filename.java

java Filename