Presentation is loading. Please wait.

Presentation is loading. Please wait.

Vladimir Misic: Java1 Week 2 – Java and more.

Similar presentations


Presentation on theme: "Vladimir Misic: Java1 Week 2 – Java and more."— Presentation transcript:

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

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

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

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

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

6 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java6 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" ); }

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

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

9 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java9 Executing Java Programs Win98/NT JVMMacOS JVMSolaris JVM Java Source Program Java Class File Java Compiler emacs filename.java javac filename.java java filename

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

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

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

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

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

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

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

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

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

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

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

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

22 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java22 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(…)

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

58 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java58 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; * finalfloat PI_FLOAT= (float) 3.1; final int MONTH_IN_YEAR = 12; final short FARADAY_CONSTANT = (short) 23060; These are constants, also called named constant. The reserved word final is used to declare constants. These are called literal constant. * A real literal is double by default

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

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

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

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

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

64 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java64 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: ; –The class must be defined before you can declare the object.

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

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

67 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java67 Object Instantiation=Object Creation ; = new ( ); The is the name(identifier) for the object as you declared it in your program. The is the name of the class that this object has been declared to belong to. The represent possible data that may be required to create the object instance, i.e. needed by the constructor.

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

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

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

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

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

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

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

75 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java75 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( ) );

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

77 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java77 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:. ( ); Receiving object Method name Parameters customer.getAccountBalance(accNum)

78 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java78 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();

79 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java79 Method Declarations The method declaration provides the function implementation in the program. –The basic format of a method declaration is: ( ) { }

80 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java80 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 ( ) { }

81 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java81 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 ( ) { }

82 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java82 Method Declarations ( ) { } public double getAccountBalance(accNum) { return accountBalance[accNum]; } public double getAccountBalance(accNum) { return accountBalance[accNum]; }

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

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

85 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java85 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() ); }

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

87 http://www.cs.rit.edu/~vm Vladimir Misic: vm@cs.rit.edu Java87 Import Statement import. ; –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.*;

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

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

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

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


Download ppt "Vladimir Misic: Java1 Week 2 – Java and more."

Similar presentations


Ads by Google