Vladimir Misic vmcs rit edu Week 2 Java

  • Slides: 91
Download presentation
Vladimir Misic: vm@cs. rit. edu Week 2 – Java and more Java 1 http:

Vladimir Misic: vm@cs. rit. edu Week 2 – Java and more Java 1 http: //www. cs. rit. edu/~vm

Programming • For the next ten weeks you will learn basic programming principles Vladimir

Programming • For the next ten weeks you will learn basic programming principles Vladimir Misic: vm@cs. rit. edu – 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 2 http: //www. cs. rit. edu/~vm

Syntax and Semantics • When using a programming language you must understand both the

Syntax and Semantics • When using a programming language you must understand both the syntax and the semantics of the language. Vladimir Misic: vm@cs. rit. edu – 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 3 http: //www. cs. rit. edu/~vm

What Is Java? • Java started as a programming language for embedded systems (toasters,

What Is Java? • Java started as a programming language for embedded systems (toasters, microwave ovens, washers, etc. ). Vladimir Misic: vm@cs. rit. edu – 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 4 http: //www. cs. rit. edu/~vm

Sun’s Slant • According to Sun: Vladimir Misic: vm@cs. rit. edu – Java is

Sun’s Slant • According to Sun: Vladimir Misic: vm@cs. rit. edu – Java is a simple, object-oriented, distributed, interpreted, robust, secure, architecture neutral, portable, highperformance, multithreaded, and dynamic language • Java is a lot like C/C++ but there a number of important differences Java 5 http: //www. cs. rit. edu/~vm

Program Structure Vladimir Misic: vm@cs. rit. edu • A program in Java consists of

Program Structure Vladimir Misic: vm@cs. rit. edu • 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 Hello. World { public static void main( String args[] ) { System. out. println( "Hello World" ); } } Java 6 http: //www. cs. rit. edu/~vm

How Is Java Different Vladimir Misic: vm@cs. rit. edu • Java differs from other

How Is Java Different Vladimir Misic: vm@cs. rit. edu • 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 7 http: //www. cs. rit. edu/~vm

Interpreted Languages • An interpreter translates and immediately executes a program Vladimir Misic: vm@cs.

Interpreted Languages • An interpreter translates and immediately executes a program Vladimir Misic: vm@cs. rit. edu – Someone, who understands German, reads the book in German and translates while reading to English Source Code Execute interpret Java 8 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Executing Java Programs Java Source Program emacs filename. java

Vladimir Misic: vm@cs. rit. edu Executing Java Programs Java Source Program emacs filename. java Java Compiler javac filename. java Java Class File Win 98/NT JVM Mac. OS JVM java filename Solaris JVM Java 9 http: //www. cs. rit. edu/~vm

Java Environments Vladimir Misic: vm@cs. rit. edu • There are lots of commercial Java

Java Environments Vladimir Misic: vm@cs. rit. edu • 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 10 http: //www. cs. rit. edu/~vm

The JDK Vladimir Misic: vm@cs. rit. edu • The JDK consists of the following:

The JDK Vladimir Misic: vm@cs. rit. edu • 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 11 http: //www. cs. rit. edu/~vm

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

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 Vladimir Misic: vm@cs. rit. edu • Java Developer Connection – http: //developer. java. sun. com • The Swing Connection – http: //java. sun. com/products/jfc/tsc Java 12 http: //www. cs. rit. edu/~vm

Other Resources • RIT Course Pages – http: //www. cs. rit. edu/~cs 1 •

Other Resources • RIT Course Pages – http: //www. cs. rit. edu/~cs 1 • NT-EMACS Vladimir Misic: vm@cs. rit. edu – http: //www. cs. washington. edu/homes/voelker/ntemacs. ht ml • JDE – http: //sunsite. auc. dk/jde/ Java 13 http: //www. cs. rit. edu/~vm

Applications and Applets • Java programs come in two forms: Vladimir Misic: vm@cs. rit.

Applications and Applets • Java programs come in two forms: Vladimir Misic: vm@cs. rit. edu – 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 14 http: //www. cs. rit. edu/~vm

Basic Java Syntax Vladimir Misic: vm@cs. rit. edu • The Java language will be

Basic Java Syntax Vladimir Misic: vm@cs. rit. edu • 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 15 http: //www. cs. rit. edu/~vm

Things & Stuff Vladimir Misic: vm@cs. rit. edu • Any program that you will

Things & Stuff Vladimir Misic: vm@cs. rit. edu • 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 16 http: //www. cs. rit. edu/~vm

Identifiers • Identifiers are used in a programming language to refer to things Vladimir

Identifiers • Identifiers are used in a programming language to refer to things Vladimir Misic: vm@cs. rit. edu – 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 17 http: //www. cs. rit. edu/~vm

Rules • Identifiers – start with an alphabetic character – can contain letters, digits,

Rules • Identifiers – start with an alphabetic character – can contain letters, digits, or “_” – are unlimited in length Vladimir Misic: vm@cs. rit. edu • Examples Answer, total, last_total, relative. Position, grid. Element Person, Place, Stack, Queue Java 18 http: //www. cs. rit. edu/~vm

Identifiers • Identifiers in Java are composed of a series of letters and digits

Identifiers • Identifiers in Java are composed of a series of letters and digits where the first character must be a letter. Vladimir Misic: vm@cs. rit. edu – Identifiers should help to document what a classes, variables, or methods are used for. – Upper and lower case letters are different in Java. • This. One is not the same as this. One. – Identifiers should not include punctuation and can not include spaces. Java 19 http: //www. cs. rit. edu/~vm

Identifiers – A good programming standard for identifiers composed of multiple words is to

Identifiers – A good programming standard for identifiers composed of multiple words is to capitalize the first character of the additional words. Vladimir Misic: vm@cs. rit. edu • The case of the first letter of the first word will depend upon the use of the identifier. • For Example, – my. Car, or bob. And. Susie. Are. Friends Java 20 http: //www. cs. rit. edu/~vm

Identifiers • Class names begin with a capital letter. – This standard makes it

Identifiers • Class names begin with a capital letter. – This standard makes it easier to understand which identifiers represent classes. – In the My. First. Application we have two class names: Vladimir Misic: vm@cs. rit. edu • My. First. Application and Main. Window Java 21 http: //www. cs. rit. edu/~vm

Identifiers • Variable (object names) and method names begin with a lower case letter.

Identifiers • Variable (object names) and method names begin with a lower case letter. – In My. First. Application we have one object: Vladimir Misic: vm@cs. rit. edu • main. Window • Note that main. Window is different from Main. Window. – In My. First. Application we have one method: • main(…) Java 22 http: //www. cs. rit. edu/~vm

Creating a Java Program • The first step to creating a Java program is

Creating a Java Program • The first step to creating a Java program is to define a class containing the main method. – The My. First. Application program on page 39 of Wu is an example of a Java class containing a main method. Vladimir Misic: vm@cs. rit. edu • This Java class definition can be thought of as the driver class or the ring leader class. Java 23 http: //www. cs. rit. edu/~vm

Declaring Variables • The basic syntax for declaring variables is: Vladimir Misic: vm@cs. rit.

Declaring Variables • The basic syntax for declaring variables is: Vladimir Misic: vm@cs. rit. edu – 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 24 http: //www. cs. rit. edu/~vm

Categories of Variables • There are two categories of variables: Vladimir Misic: vm@cs. rit.

Categories of Variables • There are two categories of variables: Vladimir Misic: vm@cs. rit. edu – 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 25 http: //www. cs. rit. edu/~vm

Primitive Types • The primitive types represent the basic, built-in types that are part

Primitive Types • The primitive types represent the basic, built-in types that are part of the Java language. • Two basic categories: Vladimir Misic: vm@cs. rit. edu – Boolean - boolean. – Numeric. • Integer - byte, short, int, long, char. • Floating point - float, double. Java 26 http: //www. cs. rit. edu/~vm

Primitive Data Types Vladimir Misic: vm@cs. rit. edu • The Java primitive data types

Primitive Data Types Vladimir Misic: vm@cs. rit. edu • 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 27 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Primitive Types Note: these types are platform independent Java

Vladimir Misic: vm@cs. rit. edu Primitive Types Note: these types are platform independent Java 28 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Primitive Types Java 29 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Primitive Types Java 29 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Real Values • Real or floating point numbers are

Vladimir Misic: vm@cs. rit. edu 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 * 2 exponent Java 30 http: //www. cs. rit. edu/~vm

Real Values • Real numbers are characterized by their precision and range. • Precision

Real Values • Real numbers are characterized by their precision and range. • Precision is the number of significant digits that is represented in the number. Vladimir Misic: vm@cs. rit. edu – 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 31 http: //www. cs. rit. edu/~vm

Real Values – Real Data Types • float uses 32 bits and represents the

Real Values – Real Data Types • float uses 32 bits and represents the numbers 3. 40292347 E+38 to 3. 40292347 E+38 Vladimir Misic: vm@cs. rit. edu – 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. 79769313486231570 E+308 to 1. 79769313486231570 E+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 32 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Real Values – Round-Off Error • When a double

Vladimir Misic: vm@cs. rit. edu 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 33 http: //www. cs. rit. edu/~vm

Character Values • May be printable and non-printable characters Vladimir Misic: vm@cs. rit. edu

Character Values • May be printable and non-printable characters Vladimir Misic: vm@cs. rit. edu – 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: u 0343, u 2 f 4, uabcd Java 34 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Unicode • An International Standard that defines the representation

Vladimir Misic: vm@cs. rit. edu 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 35 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Literals Java 36 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Literals Java 36 http: //www. cs. rit. edu/~vm

Assignment Vladimir Misic: vm@cs. rit. edu • Declarations associates a type with an identifier

Assignment Vladimir Misic: vm@cs. rit. edu • 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 37 http: //www. cs. rit. edu/~vm

Assignment Statements • The basic syntax of an assignment statement is: Vladimir Misic: vm@cs.

Assignment Statements • The basic syntax of an assignment statement is: Vladimir Misic: vm@cs. rit. edu – <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 38 http: //www. cs. rit. edu/~vm

Assignment Statements Vladimir Misic: vm@cs. rit. edu • An assignment statement can be used

Assignment Statements Vladimir Misic: vm@cs. rit. edu • An assignment statement can be used to put values into a variable both by simple assignment or by an expression. – zebra. Count = 5; – zebra. Count = zebra. Count + num. In. Herd * 0. 3; Java 39 http: //www. cs. rit. edu/~vm

Arithmetic Operators Vladimir Misic: vm@cs. rit. edu • The following table summarizes the arithmetic

Arithmetic Operators Vladimir Misic: vm@cs. rit. edu • The following table summarizes the arithmetic operators available in Java. This is an integer division where the fractional part is truncated. Java 40 http: //www. cs. rit. edu/~vm

Things Affecting How Expressions are Evaluated Operator Precedence Numeric Promotion Assignment Conversion Casting Conversion

Things Affecting How Expressions are Evaluated Operator Precedence Numeric Promotion Assignment Conversion Casting Conversion Vladimir Misic: vm@cs. rit. edu • • Java 41 http: //www. cs. rit. edu/~vm

Precedence and Operators Vladimir Misic: vm@cs. rit. edu Highest Lowest Java 42 http: //www.

Precedence and Operators Vladimir Misic: vm@cs. rit. edu Highest Lowest Java 42 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Operator Precedence • First the contents of all parentheses

Vladimir Misic: vm@cs. rit. edu Operator Precedence • 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. X = (1 + ( 2 - 4 + 6) * ( 5 + 3 * 5 ) - 16 ) Java 43 http: //www. cs. rit. edu/~vm

Mixed Mode Expressions • What happens if an expression contains two different types of

Mixed Mode Expressions • What happens if an expression contains two different types of numbers? Vladimir Misic: vm@cs. rit. edu – 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 44 http: //www. cs. rit. edu/~vm

Automatic Type Conversion (Numeric Promotion) • Java provides a variety of automatic type conversions.

Automatic Type Conversion (Numeric Promotion) • Java provides a variety of automatic type conversions. • The following conversions are supported: Vladimir Misic: vm@cs. rit. edu – 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 45 http: //www. cs. rit. edu/~vm

Assignment Conversion • Assignment conversion occurs when the result of the expression is a

Assignment Conversion • Assignment conversion occurs when the result of the expression is a different data type than the data type of the result. Vladimir Misic: vm@cs. rit. edu – 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 46 http: //www. cs. rit. edu/~vm

Assignment Conversion – Narrowing conversion occurs when the result is demoted to a smaller

Assignment Conversion – Narrowing conversion occurs when the result is demoted to a smaller data type. Vladimir Misic: vm@cs. rit. edu • 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 47 http: //www. cs. rit. edu/~vm

Casting Conversion • In some situations Java will not perform automatic conversions – int

Casting Conversion • In some situations Java will not perform automatic conversions – int x = 3. 1456; Vladimir Misic: vm@cs. rit. edu • 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 48 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Casting Conversion • Widening conversion using type casting is

Vladimir Misic: vm@cs. rit. edu 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) 50235645642 L; • x = 2147483648 Java 49 http: //www. cs. rit. edu/~vm

Assignment Operators Vladimir Misic: vm@cs. rit. edu • We have seen Java’s basic assignment

Assignment Operators Vladimir Misic: vm@cs. rit. edu • 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 50 http: //www. cs. rit. edu/~vm

Assignment Operators • The += operator allows you to represent: a = a +

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; Vladimir Misic: vm@cs. rit. edu • 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 51 http: //www. cs. rit. edu/~vm

Increment/Decrement Operators • Java contains two unary operators the increment ++ and decrement --

Increment/Decrement Operators • Java contains two unary operators the increment ++ and decrement -- operators. Vladimir Misic: vm@cs. rit. edu – When these operators are combined with an integer variable, they increment or decrement that variable by 1. • a++ == a + 1 == a +=1 • a-- == a - 1 == a -=1 Java 52 http: //www. cs. rit. edu/~vm

Increment/Decrement Operators Vladimir Misic: vm@cs. rit. edu • There are two types of increment

Increment/Decrement Operators Vladimir Misic: vm@cs. rit. edu • 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 53 http: //www. cs. rit. edu/~vm

Increment/Decrement Operators • The Preincrement/decrement operators Vladimir Misic: vm@cs. rit. edu – place the

Increment/Decrement Operators • The Preincrement/decrement operators Vladimir Misic: vm@cs. rit. edu – 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 54 http: //www. cs. rit. edu/~vm

Increment/Decrement Operators • The Postincrement/decrement operators Vladimir Misic: vm@cs. rit. edu – place the

Increment/Decrement Operators • The Postincrement/decrement operators Vladimir Misic: vm@cs. rit. edu – 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 55 http: //www. cs. rit. edu/~vm

Increment/Decrement Operators • It is legal to combine increment and decrement operators but can

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++++ Vladimir Misic: vm@cs. rit. edu – Error!!!! ++ or – can only apply to simple variables, not expressions! • It is best to avoid combining multiple increment and decrement operators. Java 56 http: //www. cs. rit. edu/~vm

Constant Data Values Vladimir Misic: vm@cs. rit. edu • A constant is a value

Constant Data Values Vladimir Misic: vm@cs. rit. edu • 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 57 http: //www. cs. rit. edu/~vm

Constants Vladimir Misic: vm@cs. rit. edu • We can change the value of a

Constants Vladimir Misic: vm@cs. rit. edu • We can change the value of a variable. If we want the value to remain the same, we use a constant. final double float int short The reserved word final is used to declare constants. PI PI_FLOAT MONTH_IN_YEAR FARADAY_CONSTANT These are constants, also called named constant. = = 3. 14159; * (float) 3. 1; 12; (short) 23060; These are called literal constant. * A real literal is double by default Java 58 http: //www. cs. rit. edu/~vm

Mathematical Methods • Java provides a Math library (class file) that implements many common

Mathematical Methods • Java provides a Math library (class file) that implements many common mathematical functions. Vladimir Misic: vm@cs. rit. edu – The Math class contains mathematical constants such as PI (Math. PI). Java 59 http: //www. cs. rit. edu/~vm

The Math Class Vladimir Misic: vm@cs. rit. edu • The Math class in the

The Math Class Vladimir Misic: vm@cs. rit. edu • 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 60 http: //www. cs. rit. edu/~vm

Mathematical Methods • Assume that we want to calculate the following: y = sin(

Mathematical Methods • Assume that we want to calculate the following: y = sin( x * 3. 14159 ) Vladimir Misic: vm@cs. rit. edu • 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 61 http: //www. cs. rit. edu/~vm

Overloaded Math Methods Vladimir Misic: vm@cs. rit. edu • If you look at the

Overloaded Math Methods Vladimir Misic: vm@cs. rit. edu • 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 62 http: //www. cs. rit. edu/~vm

Math Methods using Coercion Vladimir Misic: vm@cs. rit. edu • Some Math methods only

Math Methods using Coercion Vladimir Misic: vm@cs. rit. edu • 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 63 http: //www. cs. rit. edu/~vm

Declaring Objects (Reference Types) Vladimir Misic: vm@cs. rit. edu • In order to create

Declaring Objects (Reference Types) Vladimir Misic: vm@cs. rit. edu • 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 64 http: //www. cs. rit. edu/~vm

Declaring Objects (Reference Types) Vladimir Misic: vm@cs. rit. edu • Think about our cars.

Declaring Objects (Reference Types) Vladimir Misic: vm@cs. rit. edu • 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 clints. Porsche; Car jessicas. BMW; Car johns. Lamborghini; Java 65 http: //www. cs. rit. edu/~vm

Reference Types (Objects) Vladimir Misic: vm@cs. rit. edu • Reference types are used to

Reference Types (Objects) Vladimir Misic: vm@cs. rit. edu • 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 66 http: //www. cs. rit. edu/~vm

Object Instantiation=Object Creation Vladimir Misic: vm@cs. rit. edu <class name> <object name>; <object name>

Object Instantiation=Object Creation Vladimir Misic: vm@cs. rit. edu <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 67 http: //www. cs. rit. edu/~vm

Creating Objects • Before a reference to an object may be assigned to a

Creating Objects • Before a reference to an object may be assigned to a variable, the object must be created Vladimir Misic: vm@cs. rit. edu – 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 68 http: //www. cs. rit. edu/~vm

Vladimir Misic: vm@cs. rit. edu Reference Variables • These variables/identifiers refer to objects; they

Vladimir Misic: vm@cs. rit. edu 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 69 http: //www. cs. rit. edu/~vm

Primitive Data Declaration and Assignments int first. Number, second. Number; first. Number = 234;

Primitive Data Declaration and Assignments int first. Number, second. Number; first. Number = 234; second. Number = 87; A. Variables are allocated in memory. first. Number Vladimir Misic: vm@cs. rit. edu A int first. Number, , second. Number; ; first. Number = 234; B second. Number = 87; second. Number 234 87 B. Values are assigned to variables. State of Memory Code Java 70 http: //www. cs. rit. edu/~vm

Assigning Numerical Data int number; number = 237; number = 35; number 35 237

Assigning Numerical Data int number; number = 237; number = 35; number 35 237 Vladimir Misic: vm@cs. rit. edu A. The variable int number; number = 237; number = 35; is allocated in memory. A B B. The value 237 is assigned to number C C. The value 35 overwrites the previous value 237. State of Memory Code Java 71 http: //www. cs. rit. edu/~vm

Assigning Objects customer Customer customer; customer = new Customer( ); Customer Vladimir Misic: vm@cs.

Assigning Objects customer Customer customer; customer = new Customer( ); Customer Vladimir Misic: vm@cs. rit. edu A Customer customer; B A. The variable is allocated in memory. customer = new Customer( ); B. The reference to the customer = new Customer( ); new object is assigned to customer C C. The reference to another object overwrites the reference in customer. State of Memory Code Java 72 http: //www. cs. rit. edu/~vm

Having Two References to a Single Object clemens Customer clemens, twain; clemens = new

Having Two References to a Single Object clemens Customer clemens, twain; clemens = new Customer( ); twain = clemens; twain Vladimir Misic: vm@cs. rit. edu A Customer clemens, twain; Customer B A. Variables are allocated in memory. clemens = new Customer( ); twain B. The reference to the = clemens; new object is assigned to clemens C C. The reference in clemens is assigned to customer. State of Memory Code Java 73 http: //www. cs. rit. edu/~vm

Types of Methods There are 4 basic types of methods: • Modifier (sometimes called

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) Vladimir Misic: vm@cs. rit. edu • 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 74 http: //www. cs. rit. edu/~vm

Methods • A reference to an object can be used to invoke a method

Methods • A reference to an object can be used to invoke a method of the object Vladimir Misic: vm@cs. rit. edu – 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. my. Car. start( ) ); Java 75 http: //www. cs. rit. edu/~vm

What Methods? • How do you know what methods are available for a given

What Methods? • How do you know what methods are available for a given object? Vladimir Misic: vm@cs. rit. edu – Look at the class definition – Look at the documentation for the class • The JDK provides documentation for its classes using a tool called Java. Doc Java 76 http: //www. cs. rit. edu/~vm

Message Passing Vladimir Misic: vm@cs. rit. edu • Once an object exists, the program

Message Passing Vladimir Misic: vm@cs. rit. edu • 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>); customer. get. Account. Balance(acc. Num) Receiving object Method name Parameters Java 77 http: //www. cs. rit. edu/~vm

Message Passing • Let’s create messages for cars. – We need to know how

Message Passing • Let’s create messages for cars. – We need to know how much gas BMW has. bmw. get. Gas. Level(); Vladimir Misic: vm@cs. rit. edu – We want to remotely start Audi. audi. remote. Start(); Java 78 http: //www. cs. rit. edu/~vm

Method Declarations • The method declaration provides the function implementation in the program. Vladimir

Method Declarations • The method declaration provides the function implementation in the program. Vladimir Misic: vm@cs. rit. edu – The basic format of a method declaration is: <modifiers> <return type> <method name> (<parameters>) { <method body> } Java 79 http: //www. cs. rit. edu/~vm

Method Declarations Vladimir Misic: vm@cs. rit. edu <modifiers> <return type> <method name> (<parameters>) {

Method Declarations Vladimir Misic: vm@cs. rit. edu <modifiers> <return type> <method name> (<parameters>) { <method body> } • Modifiers represent terms that determine what kind of method is declared. (Chap 4) • 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. Java 80 http: //www. cs. rit. edu/~vm

Method Declarations Vladimir Misic: vm@cs. rit. edu <modifiers> <return type> <method name> (<parameters>) {

Method Declarations Vladimir Misic: vm@cs. rit. edu <modifiers> <return type> <method name> (<parameters>) { <method body> } • The method name should identify the task to be completed by the method • The parameters are the data that the method requires to complete the task. • The method body includes the code statements that implement the task. Java 81 http: //www. cs. rit. edu/~vm

Method Declarations Vladimir Misic: vm@cs. rit. edu <modifiers> <return type> <method name> (<parameters>) {

Method Declarations Vladimir Misic: vm@cs. rit. edu <modifiers> <return type> <method name> (<parameters>) { <method body> } public double get. Account. Balance(acc. Num) { return account. Balance[acc. Num]; } Java 82 http: //www. cs. rit. edu/~vm

Class Declarations • Java programs are composed of one or more classes. Vladimir Misic:

Class Declarations • Java programs are composed of one or more classes. Vladimir Misic: vm@cs. rit. edu – 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 83 http: //www. cs. rit. edu/~vm

Class Declarations Vladimir Misic: vm@cs. rit. edu class <class name> { <class member declarations>

Class Declarations Vladimir Misic: vm@cs. rit. edu class <class name> { <class member declarations> } • Every class must have unique name • The class member declarations include method definitions and variable (data value) declarations. Java 84 http: //www. cs. rit. edu/~vm

Class Declarations • One class in every program must include the main method. Vladimir

Class Declarations • One class in every program must include the main method. Vladimir Misic: vm@cs. rit. edu – This class is the driver class. – The main method is the first method that is called when a program is executed. public class Point. Test { public static void main( String args[] ) { Point my. Point = new Point( 12, 34 ); System. out. println( my. Point. get. Coordinates() ); } } Java 85 http: //www. cs. rit. edu/~vm

Import Statement • The import statement is used to allow a class definition to

Import Statement • The import statement is used to allow a class definition to access predefined Java classes. Vladimir Misic: vm@cs. rit. edu – Related predefined Java classes are stored in packages. – In order to import predefined classes: import <package name>. <class name>; Java 86 http: //www. cs. rit. edu/~vm

Import Statement import <package name>. <class name>; Vladimir Misic: vm@cs. rit. edu – The

Import Statement import <package name>. <class name>; Vladimir Misic: vm@cs. rit. edu – The package name represents 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. Main. Window; import javabook. *; Java 87 http: //www. cs. rit. edu/~vm

Comments Vladimir Misic: vm@cs. rit. edu • Providing a description of what the program

Comments Vladimir Misic: vm@cs. rit. edu • 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 88 http: //www. cs. rit. edu/~vm

Comments • Java provides three ways to comment code. Vladimir Misic: vm@cs. rit. edu

Comments • Java provides three ways to comment code. Vladimir Misic: vm@cs. rit. edu – 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 89 http: //www. cs. rit. edu/~vm

/* * Hello. World. java * * Version: * $Id$ * * Revisions: *

/* * Hello. World. java * * Version: * $Id$ * * Revisions: * $Log$ */ Java Coding Standard Comments for Hello World Vladimir Misic: vm@cs. rit. edu import java. *; /** * This program prints Hello World on the screen * * @author Paul Tymann */ public class Hello. World { /** * The main program. * * @param args command line arguments (ignored) */ public static void main( String args[] ) { System. out. println( "Hello World" ); } } Java 90 http: //www. cs. rit. edu/~vm

Creating a Java Program • The filename. class file is interpreted by the Java

Creating a Java Program • The filename. class file is interpreted by the Java interpreter every time it is run. Vladimir Misic: vm@cs. rit. edu Only Once Every Time Java Interpreter Java Compiler Editor Filename. java Filename. class javac Filename. java Filename Java 91 http: //www. cs. rit. edu/~vm