Vladimir Misic: Java1 Week 2 – Java and more.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
1 Java Basics. 2 Compiling A “compiler” is a program that translates from one language to another Typically from easy-to-read to fast-to-run e.g. from.
CMT Programming Software Applications
COMPSCI 125 Spring 2005 ©TheMcGraw-Hill Companies, Inc. Permission required for reproduction or display. Chapter 3: Numeric Data *Variables *Numeric data.
© Janice Regan, CMPT 102, Sept CMPT 102 Introduction to Scientific Computer Programming Expressions and Operators Program Style.
Pemrograman Dasar - Data Types1 THINGS & STUFF Identifier, Variable, Constant, Data type, operator, expression, assignment, javadoc.
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
Chapter 3 Numerical Data. Topics Variables Numeric data types Assignment Expressions.
Data types and variables
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Chapter 2 Data Types, Declarations, and Displays
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
String Escape Sequences
Basic Elements of C++ Chapter 2.
What is a variable?  A variable holds data in memory so the program may use that data, or store results.  Variables have a data type. int, boolean, char,
© The McGraw-Hill Companies, 2006 Chapter 1 The first step.
Objectives You should be able to describe: Data Types
Java Chapter 2 Creating Classes. Class Defines structure of an object or set of objects; Includes variables (data) and methods (actions) which determine.
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
1 Variables, Constants, and Data Types Primitive Data Types Variables, Initialization, and Assignment Constants Characters Strings Reading for this class:
 Value, Variable and Data Type  Type Conversion  Arithmetic Expression Evaluation  Scope of variable.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
DEPARTMENT OF COMPUTER SCIENCE & TECHNOLOGY FACULTY OF SCIENCE & TECHNOLOGY UNIVERSITY OF UWA WELLASSA 1 CST 221 OBJECT ORIENTED PROGRAMMING(OOP) ( 2 CREDITS.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
1 Do you have a CS account? Primitive types –“ building blocks ” for more complicated types Java is strongly typed –All variables in a Java program must.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Input, Output, and Processing
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
Vladimir Misic: Java1 Basic Java Syntax The java language will be described by working through its features: –Variable types and expressions.
Object-Oriented Program Development Using Java: A Class-Centered Approach, Enhanced Edition.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Object-Oriented Programming •Object-Oriented Programming (OOP) allows you to create your program based upon modeling objects.  Your program’s properties.
Copyright Curt Hill Variables What are they? Why do we need them?
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.
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
Chapter 2 Variables.
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
Numeric Data Types There are six numeric data types: byte, short, int, long, float, and double. Sample variable declarations: int i, j, k; float numberOne,
1 Week 5 l Primitive Data types l Assignment l Expressions l Documentation & Style Primitive Types, Assignments, and Expressions.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
Chapter 3 Numerical Data. Objectives After you have read and studied this chapter, you should be able to Select proper types for numerical data. Write.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
SESSION 1 Introduction in Java. Objectives Introduce classes and objects Starting with Java Introduce JDK Writing a simple Java program Using comments.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Java Programming: Guided Learning with Early Objects Chapter 1 Basic Elements of Java.
Chapter 2 Variables.
Chapter Topics The Basics of a C++ Program Data Types
Java Primer 1: Types, Classes and Operators
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Basic Elements of C++.
Multiple variables can be created in one declaration
Primitive and Reference Data Values
Java Programming: From Problem Analysis to Program Design, 4e
Basic Elements of C++ Chapter 2.
Primitive and Reference Data Values
Chapter 2 Variables.
Expressions and Assignment
In this class, we will cover:
Primitive Types and Expressions
Chapter 2 Variables.
Presentation transcript:

Vladimir Misic: Java1 Week 2 – Java and more

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: 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.

Vladimir Misic: 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

Vladimir Misic: 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" ); }

Vladimir Misic: 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

Vladimir Misic: 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

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: 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

Vladimir Misic: Java12 Java Resources Java Home Page – ( The Java Tutorial – Java Developer Connection – The Swing Connection –

Vladimir Misic: Java13 Other Resources RIT Course Pages – NT-EMACS – ml JDE –

Vladimir Misic: 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.

Vladimir Misic: 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.

Vladimir Misic: 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

Vladimir Misic: 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

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: 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

Vladimir Misic: 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

Vladimir Misic: 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(…)

Vladimir Misic: 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.

Vladimir Misic: 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).

Vladimir Misic: 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.

Vladimir Misic: 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.

Vladimir Misic: 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.

Vladimir Misic: Java28 Primitive Types Note: these types are platform independent

Vladimir Misic: Java29 Primitive Types

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: Java32 Real Values – Real Data Types float uses 32 bits and represents the numbers E+38 to E+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 E+308 to 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.

Vladimir Misic: 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.

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: Java36 Literals

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: 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;

Vladimir Misic: Java40 Arithmetic Operators The following table summarizes the arithmetic operators available in Java. This is an integer division where the fractional part is truncated.

Vladimir Misic: Java41 Things Affecting How Expressions are Evaluated Operator Precedence Numeric Promotion Assignment Conversion Casting Conversion

Vladimir Misic: Java42 Precedence and Operators Highest Lowest

Vladimir Misic: Java43 X = (1 + ( ) * ( * 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

Vladimir Misic: Java44 Mixed Mode Expressions What happens if an expression contains two different types of numbers? –For example, *.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?

Vladimir Misic: 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.

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: Java48 Casting Conversion In some situations Java will not perform automatic conversions –int x = ; 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

Vladimir Misic: 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) L; x =

Vladimir Misic: 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.

Vladimir Misic: 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;

Vladimir Misic: 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

Vladimir Misic: 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--

Vladimir Misic: 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?

Vladimir Misic: 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?

Vladimir Misic: 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.

Vladimir Misic: 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.

Vladimir Misic: 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 = ; * 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

Vladimir Misic: 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).

Vladimir Misic: 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

Vladimir Misic: Java61 Mathematical Methods Assume that we want to calculate the following: y = sin( x * ) 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 );

Vladimir Misic: 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.

Vladimir Misic: 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.

Vladimir Misic: 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.

Vladimir Misic: 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;

Vladimir Misic: 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;

Vladimir Misic: 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.

Vladimir Misic: 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”;

Vladimir Misic: 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

Vladimir Misic: 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

Vladimir Misic: 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 C. The value 35 overwrites the previous value

Vladimir Misic: 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

Vladimir Misic: 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.

Vladimir Misic: 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

Vladimir Misic: 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( ) );

Vladimir Misic: 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

Vladimir Misic: 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)

Vladimir Misic: 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();

Vladimir Misic: Java79 Method Declarations The method declaration provides the function implementation in the program. –The basic format of a method declaration is: ( ) { }

Vladimir Misic: 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 ( ) { }

Vladimir Misic: 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 ( ) { }

Vladimir Misic: Java82 Method Declarations ( ) { } public double getAccountBalance(accNum) { return accountBalance[accNum]; } public double getAccountBalance(accNum) { return accountBalance[accNum]; }

Vladimir Misic: 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 { }

Vladimir Misic: Java84 The class member declarations include method definitions and variable (data value) declarations. Every class must have unique name Class Declarations class { }

Vladimir Misic: 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() ); }

Vladimir Misic: 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. ;

Vladimir Misic: 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.*;

Vladimir Misic: 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.

Vladimir Misic: 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 * Vladimir Misic */

Vladimir Misic: Java90 /* * HelloWorld.java * * Version: * $Id$ * * Revisions: * $Log$ */ import java.*; /** * This program prints Hello World on the screen * Paul Tymann */ public class HelloWorld { } /** * The main program. * args command line arguments (ignored) */ public static void main( String args[] ) { System.out.println( "Hello World" ); } Java Coding Standard Comments for Hello World

Vladimir Misic: 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