CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: 2015- Illinois Institute of Technology/George Koutsogiannakis 1.

Slides:



Advertisements
Similar presentations
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Advertisements

CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology/George Koutsogiannakis 1.
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Chapter 7 User-Defined Methods. Chapter Objectives  Understand how methods are used in Java programming  Learn about standard (predefined) methods and.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
CS 106 Introduction to Computer Science I 02 / 18 / 2008 Instructor: Michael Eckmann.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 Chapter 2 Introductory Programs. 2 Getting started To create and run a Java program –Create a text file with a.java extension for the source code. For.
CS 225 Java Review. Java Applications A java application consists of one or more classes –Each class is in a separate file –Use the main class to start.
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II GEORGE KOUTSOGIANNAKIS Copyright: 2015 Illinois Institute of Technology- George Koutsogiannakis.
Applying OO Concepts Using Java. In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The.
Java Unit 9: Arrays Declaring and Processing Arrays.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Chapter 8 Single-Dimensional Arrays. Topics Declaring and Instantiating Arrays Accessing Array Elements Writing Methods Aggregate Array Operations Using.
Announcements  I will discuss the labtest and the written test #2 common mistakes, solution, etc. in the next class  not today as I am still waiting.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Spring 2008 Mark Fontenot CSE 1341 Principles of Computer Science I Note Set 2.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 9 Multidimensional Arrays and the ArrayList Class.
Arrays BCIS 3680 Enterprise Programming. Overview 2  Array terminology  Creating arrays  Declaring and instantiating an array  Assigning value to.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Applications Development
Topic 1 Object Oriented Programming. 1-2 Objectives To review the concepts and terminology of object-oriented programming To discuss some features of.
Introduction to Methods. Previously discussed There are similarities in make up of that can help you remember the construct of a class a class in the.
COP INTERMEDIATE JAVA Designing Classes. Class Template or blueprint for creating objects. Their definition includes the list of properties (fields)
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS Copyright: 2014 Illinois Institute of Technology- George Koutsogiannakis 1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
By Mr. Muhammad Pervez Akhtar
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 2 *Includes materials provided by George Koutsogiannakis and Matt Bauer 1.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
CS 116 Lecture 1 John Korah Contains content provided by George Koutsogiannakis & Matt Bauer.
In this class, we will cover: Overriding a method Overloading a method Constructors Mutator and accessor methods The import statement and using prewritten.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
CS 116: OBJECT ORIENTED PROGRAMMING II LECTURE 3 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer 1.
Chapter 5: Arrays in Java. The objectives of this chapter are:  1. To discuss the creation and use of Arrays.   2. To continue to use the String class.
CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS Copyright: 2016 Illinois Institute of Technology/George Koutsogiannakis 1.
CS 116 Object Oriented Programming II Lecture 4 Acknowledgement: Contains materials provided by George Koutsogiannakis and Matt Bauer.
JAVA Programming (Session 2) “When you are willing to make sacrifices for a great cause, you will never be alone.” Instructor: รัฐภูมิ เถื่อนถนอม
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 6_1 GEORGE KOUTSOGIANNAKIS Copyright: FALL 2015 Illinois Institute of Technology- George Koutsogiannakis 1.
CS 115 OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS 1 Copyright: 2015 Illinois Institute of Technology_ George Koutsogiannakis.
Chapter 9 Introduction to Arrays Fundamentals of Java.
The need for Programming Languages
Chapter 7 User-Defined Methods.
3 Introduction to Classes and Objects.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 12 GEORGE KOUTSOGIANNAKIS
Yanal Alahmad Java Workshop Yanal Alahmad
OBJECT ORIENTED PROGRAMMING II LECTURE 2 GEORGE KOUTSOGIANNAKIS
CS116 OBJECT ORIENTED PROGRAMMING II LECTURE 1 Part II
OBJECT ORIENTED PROGRAMMING II LECTURE 2_1 GEORGE KOUTSOGIANNAKIS
Java Review Hello..This ppt is to give you an introduction about java and why it is soo special The segments all discussed here are the crucial parts of.
OBJECT ORIENTED PROGRAMMING I LECTURE 7 GEORGE KOUTSOGIANNAKIS
Starting JavaProgramming
Defining Classes and Methods
Chap 1 Chap 2 Chap 3 Chap 5 Surprise Me
Applying OO Concepts Using Java
OBJECT ORIENTED PROGRAMMING I LECTURE 9 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 5 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 13_2 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING II LECTURE 4 GEORGE KOUTSOGIANNAKIS
OBJECT ORIENTED PROGRAMMING I LECTURE 11 GEORGE KOUTSOGIANNAKIS
Presentation transcript:

CS 116 OBJECT ORIENTED PROGRAMMING II LECTURE 3 GEORGE KOUTSOGIANNAKIS Copyright: Illinois Institute of Technology/George Koutsogiannakis 1

OOP Review In previous lecture we discussed: – Service classes versus Client classes. – Packaging of classes using Command Line. – Input using Command Line arguments. – How to read text files with scanner object. – The scope of a variable. – Enumerations. – Using the StringTokenizer object. – Formatting of Numbers. 2

Arrays – Single Dimension Topics in Today’s Lecture Review Material – Declaring and Instantiating Arrays – Entering Array Elements – Accessing Array Elements – Aggregate Array Operations – Arrays of Objects. – Using Arrays in classes. New Material not covered in CS115 – Creating packages – Creating Documentation with javadocs command (optional- not responsible for it in exams or labs). 3

Arrays An array is a sequence of variables of the same data type. Arrays are useful for many applications, including calculating statistics or representing the state of a game. The data type can be any of Java's primitive types (int, short, byte, long, float, double, boolean, char), an array, or a class. Each variable in the array is an element. We use an index to specify the position of each element in the array. An array is an Object by itself. Remember that we can also have arrays of objects. The objects can be representative of pre defined classes (library classes) or user defined classes 4

Declaring and Instantiating Arrays Arrays are objects, so creating an array requires two steps: 1.declaring a reference to the array 2.instantiating the array To declare a reference to the array, use this syntax: datatype [] arrayName; To instantiate an array, use this syntax: arrayName = new datatype[ size ]; where size is an expression that evaluates to an integer and specifies the number of elements. 5

Examples Declaring arrays: double [] dailyTemps; // elements are doubles String [] cdTracks; // elements are Strings boolean [] answers; // elements are booleans Auto [] cars; // elements are Auto references int [] cs101, bio201; // two integer arrays Instantiating these arrays: dailyTemps = new double[365]; // 365 elements cdTracks = new String[15]; // 15 elements int numberOfQuestions = 30; answers = new boolean[numberOfQuestions]; cars = new Auto[3]; // 3 elements cs101 = new int[5]; // 5 elements bio201 = new int[4]; // 4 elements 6

Default Values for Elements When an array is instantiated, the elements are assigned default values according to the array data type. 7 Array data typeDefault value byte, short, int, long0 float, double0.0 charspace booleanfalse Any object reference (for example, a String) null

Example array of integers int [ ] myarray=new int[5]; – The array size is 5 and the index will run from 0 to 4. index Notice that initial values are 0 s since the array was declared to be an array of integer data types

Assigning Initial Values to Arrays Arrays can be instantiated by specifying a list of initial values. Syntax: datatype [] arrayName = { value0, value1, … }; where valueN is an expression evaluating to the data type of the array and is the value to assign to the element at index N. Examples: int nine = 9; int [] oddNumbers = { 1, 3, 5, 7, nine, nine + 2, 13, 15, 17, 19 }; Auto sportsCar = new Auto( "Ferrari", 0, 0.0 ); Auto [] cars = { sportsCar, new Auto( ), new Auto("BMW", 100, 15.0 ) }; 9

Instantiating an Array Or you can declare and then instantiate the array by indicating its size and then enter values one at a time i.e double [] myarray; myarray=new double[10]; Where 10 is the size of the array myarray. 10

Entering Array Elements Enter an element in a specific index location. Suppose that we want to enter the number 10 in the position with index=2 in the array myintarray int [] myintarray=new int[5]; myintarray[2]=10; We can of course fill the array with multiple element values by using a for loop. 11

Entering Array Elements i.e. for (int a=0 ; a<=myintarray.lenght-1; a++) myintarray[a]=(a+2); This loop enters the int values of a+2 into the array myintarray. 12

Entering Array Elements 13 Array IndexValue entered

Accessing Array Elements Array elements can be accessed by first declaring a data type variable similar to the data types held in the array and assigning the array element to that data type. i.e. int x; x=myarray[2]; the element in index position 2 is assigned to x (i.e x=4 from previous slide). 14

Calculating a Total Example This code calculates the total value of all elements in the array myintarray, which has previously been instantiated: int total = 0; // initialize total for ( int i = 0; i <= myintarray.length-1; i++ ) { total += myintarray[i]; } System.out.println( "The total is " + total ); The output should be: The total is 20 See Text Example 8.5 SummingArrayElements.java 15

Instantiating an Array of Objects To instantiate an array with a class data type: 1. instantiate the array (elements are object references, initialized to null) 2. instantiate the objects Example: // instantiate array; all elements are null Auto [] cars = new Auto[3]; // instantiate objects and assign to elements Auto sportsCar = new Auto( "Miata", 100, 5.0 ); cars[0] = sportsCar; cars[1] = new Auto( ); // cars[2] is still null See Text Example 8.2 AutoArray.java 16

Example of Arrays of Objects Suppose we have a Person service class with attributes: public class Person { String firstName=“ “; String lastName=“ “; int currentID=0; static int id=0; public Person(String fn, String ln) { setFirstName(fn); setLastName(ln); id++; currentID=id; } Followed by accessor /mutator and toString methods. NEVER INCLUDE THE id ATTRIBURES IN THE LIST OF ARGUMENTS OF THE CONSTRUCTOR

Arrays of Objects Suppose the following class uses the class Person. We want to create 50 person objects and store them in an array : public class CreatePersons { public static void main(String[] args) { //for each of the instance variable we create an array. String Fname=“ “; String Lname=“ “; //create (instantiate) an array of type Person to hold 50 Person objects. // Although we fixed the size to 50 in this example in most cases the size will //be determined programmatically from the data in the text file that has the data. Person [] personArray=new Person[50]; 18

Arrays of Objects //create 50 Person objects and place them in the array personArray for (int i=0; i<=personArray.length-1; i++ ) { FName="p"+i; LName="Doe"+i; personArray[i]=new Person(FName, LName); } 19

Arrays of Objects //Now output the ids and the Person objects attributes (instance variables) for each Person object in the array. for (int j=0; j<=personArray.length-1; j++) { System.out.println(" the id of each object is:"+" "+personArray[j].getCurrentID()); System.out.println(“The attributes of each object are:”+” “+personArray[j].toString()); } NOTE : calling the toString method in the above program is optiona, the same result will be accomplished if the code was written: System.out.println(“The attributes of each object are:”+” “+personArray[j]); 20

Using Arrays in Classes In a user-defined class, an array can be: – an instance variable of the class – a parameter to a method – a return value from a method – a local variable in a method 21

Methods with Array Parameters or Array return values To define a method that takes an array as a parameter, use this syntax: accessModifier returnType methodName( dataType [] arrayName ) i.e. public int myMethod( Person [] aPersonArray) To define a method that returns an array, use this syntax: accessModifier dataType [] methodName( parameterList ) i.e public Person [] myMethod (String [] aStringsArray) 22 Returned value data type Method argument data type

Methods with Array Parameters or Array return values To pass an array as an argument when calling a method, use the array name without brackets: i.e. in the following call the method returns an array. We need to have an array of the data type for the array inatsntiate dto capture the returned array from the method call: Person [] mynewPersonArray=new Person[50]; mynewPersonArray=myMethod(stringArray); 23

Arrays as Instance Variables A constructor (or mutator) that accepts an array parameter should instantiate the instance variable array and copy the elements from the parameter array to the instance variable. // constructor public CellPhone( double [] bills ) { // instantiate instance variable array // with same length as parameter cellBills = new double [bills.length]; // copy parameter array to cellBills array for ( int i = 0; i < cellBills.length; i++ ) cellBills[i] = bills[i]; } 24

Accessors for Arrays Similarly, an accessor method for the array instance variable should return a reference to a copy of the array. public double [] getCellBills( ) { // instantiate temporary array double [] temp = new double [cellBills.length]; // copy instance variable values to temp for ( int i = 0; i < cellBills.length; i++ ) temp[i] = cellBills[i]; // return copy of array return temp; } 25

Finding min max Value in an array of numbers. Suppose that we have an array of numeric data type like int. We need to develop an algorithm for finding the first instance of the maximum number stored in the array (it is possible that the same max number appears more than once in the array. 26

Finding min max Value in an array of numbers. Suppose that I have the array: int [] intarray=new int[20]; //Let us declare a variable called max int max=0; //Let us iterate through the elements of the array and for compare each element to the max variable’s number. //If we find an element with a value greater than the value held by max then assign the value of that element to max and continue with the next comparison //In the example code given next we also capture the index at which the element with the maximum value was found: 27

Finding min max Value in an array of numbers int indexOfmax=0; for(int i=0; i<=intarray.length-1; i++) { if(max<intarray[i]) { max=intarray[i]; indexOfmax=i; } To find the minimum value all we have to do is to reverse the inequality sign in the if selection if(min>intarray) 28

Java Packages- Reminder Let us repeat the basics about packaging one more time!!! User defined packaging. – Suppose that we created a package for our user defined template class Auto : package name1.name2.name3; import java.util.Scanner; import java.io.File; public class Auto { ……………………………… } 29

Java Packages We compile with the special command: >javac –d. Auto.java This command tells the compiler to create the folders name1 and name 2 and name 3 with respect to the current directory and place Auto.class inside folder name3. 30

Java Packages Current Directory (folder) Auto.java name1(folder) name2 (folder) name3 (folder) Auto.class 31

Java Packages How do we call the interpreter for class AutoClient from the current directory (folder)? We need to list the path to the AutoClass when we use the interpreter command: i.e >java name1.name2.AutoClient Notice that the reason we call the AutoClient class is because this class has the main method. The Auto class will be called automatically. 32

Java Packages Pre defined library classes are grouped into packages according to their functionality: i.e. package java.lang Provides classes that are fundamental to the design of the Java programming language. Every java program automatically imports all the classes of this package without the need for an import statement. – Includes such classes as : String, Math, System, Integer, Float and others. 33

Java Packages There are over 200 packages in the java library – Number of classes varies in each package with some having over 20 classes. – Remember that a package can include something called “interfaces”. – For now let us think of an interface as a class whose methods have no code (no implementation). We will come back to the subject of interfaces later on. 34

Javadocs (optional material) Automatic generation of documentation for your user defined classes in html format. It is another tool available in the jdk (see bin subfolder in the installation folder of the jdk). To generate documentation use the command javadoc and the nam eof your class followed by the.java extension: – >javadoc Persons.java or – >javadoc *.java (means all files in the folder that end with.java extansion). 35

Javadocs The tool reads all comments added (/** to */) plus additional information that we add in the source code file (i.e. describe parameters using the i.e. param id denotes the id number of a person advancing for each new Person object instantiated. 36

Javadoc Example /** This class describes Persons */ public class Person { firstName provides the first name of a Person */ String firstName; static int id; int currentid; public Person() { firstName="John"; id++; currentid=id; } 37

Output html File Package Class Tree Deprecated Index Help PackageTreeDeprecatedIndexHelp PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes All Classes SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHODFRAMESNO FRAMESAll Classes CONSTRMETHODCONSTRMETHOD Class Person java.lang.Object Person public class Person extends java.lang.Object This class describes Persons Constructor Summary Person() Method Summary void method1() Methods inherited from class java.lang.Object clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait Personmethod1 Constructor Detail Person public Person() Method Detail method1 public void method1() Package Class Tree Deprecated Index Help PackageTreeDeprecatedIndexHelp PREV CLASS NEXT CLASS FRAMES NO FRAMES All Classes All Classes SUMMARY: NESTED | FIELD | CONSTR | METHOD DETAIL: FIELD | CONSTR | METHODFRAMESNO FRAMESAll Classes CONSTRMETHODCONSTRMETHOD 38