Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao.

Slides:



Advertisements
Similar presentations
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
Advertisements

Hip Hip Array! AP Computer Science. Remember Strings? Strings are an array of characters An array is a collection of variables all of the same type. Arrays.
Designing Classes Chapter 8. Classes Collection of objects Objects are not actions Class names – Nouns Method names – Verbs What Makes a Good Class Represent.
CIT 590 Intro to Programming Java lecture 4. Agenda Types Collections – Arrays, ArrayLists, HashMaps Variable scoping Access modifiers – public, private,
Dialogs. Displaying Text in a Dialog Box Windows and dialog boxes –Up to this our output has been to the screen –Many Java applications use these to display.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Chapter 7 – Arrays.
Copyright 2008 by Pearson Education Building Java Programs Chapter 7 Lecture 7-1: Arrays reading: 7.1 self-checks: #1-9 videos: Ch. 7 #4.
Arrays. Example Write a program to keep track of all students’ scores on exam 1. Need a list of everyone’s score Declare 14 double variables? What about.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
Review Java.
ARRAYS AND ARRAYLISTS Chapter 7. Array  Sequence of values of the same type  Primitive types  Objects  Create an Array  double[] values = new double[10]
For each primitive type there is a wrapper class for storing values of that type: Double d = new Double(29.95); Wrapper Classes Wrapper objects can be.
Week 9-10 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
ICOM 4015: Advanced Programming Lecture 7 Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Reading: Chapter Seven:
Class Library, Formatting, Wrapper Classes, and JUnit Testing
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
7. Arrays. Topics Declaring and Using Arrays Some Array Algorithms Arrays of Objects Variable Length Parameter Lists Two-Dimensional Arrays The ArrayList.
ArrayList, Multidimensional Arrays
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
Arrays and ArrayLists in Java L. Kedigh. Array Characteristics List of values. A list of values where every member is of the same type. Each member in.
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.
Arrays Chapter 8. What if we need to store test scores for all students in our class. We could store each test score as a unique variable: int score1.
Static. Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A static method does not operate on an object double dY.
Arrays Construct array: new double[10] Store in variable of type double[] double[] data = new double[10];
1 Programming Java Java Basics. 2 Java Program Java Application Program Application Program written in general programming language Applet Program running.
OBJECTS FOR ORGANIZING DATA -- As our programs get more sophisticated, we need assistance organizing large amounts of data. : array declaration and use.
ArrayList Class An ArrayList is an object that contains a sequence of elements that are ordered by position. An ArrayList is an object that contains a.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
Objects & Classes Weiss ch. 3. So far: –Point (see java.awt.Point) –String –Arrays of various kinds –IPAddress (see java.net.InetAddress) The Java API.
16-August-2002cse Libraries © 2002 University of Washington1 Class Libraries CSE 142, Summer 2002 Computer Programming 1
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. A class represents a single concept from the problem domain, or a.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Chapter 6 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Copyright © 2013 by John Wiley & Sons. All rights reserved. ARRAYS and ARRAYLISTS CHAPTER Slides by Donald W. Smith TechNeTrain.com 6 Final Draft 10/30/2011.
Array length = maximum number of elements in array Usually, array is partially filled Need companion variable to keep track of current size Uniform naming.
1 Chap. 3 Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L, 3.1 – 3.6.
1 Chapter 6 Programming with Objects and Classes F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive.
1 Wrapper Classes  Sometimes we want to use a primitive type as an object, so there are wrapper classes that will help us.  In particular, we need to.
April 20, 1998CS102-02Lecture 4-1 A Method to the Madness CS Lecture 4-1 Java's Work Horses.
int [] scores = new int [10];
JAC444: Intro to Java Arrays and Vectors Tim McKenna
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Outline Creating Objects The String Class The Random and Math Classes Formatting Output Enumerated Types Wrapper Classes Components and Containers Images.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Chapter 7 – Arrays and Array Lists Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
© 2004 Pearson Addison-Wesley. All rights reserved3-1 Objects Declaration: String title;  title (object variable) of type String( Class )  title is just.
Basic Class Structure. Class vs. Object class - a template for building an object –defines the instance data that the object will hold –defines instance.
1 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used as a type to declare an object reference.
Objects and Classes. F OO Programming Concepts F Creating Objects and Object Reference Variables –Differences between primitive data type and object type.
Chapter 7 – Arrays and Array Lists
Sixth Lecture ArrayList Abstract Class and Interface
Array Lists An array list stores a sequence of values whose size can change. An array list can grow and shrink as needed. ArrayList class supplies methods.
Chapter 7 User-Defined Methods.
7.6 Common Array Algorithm: Filling
Lecture Notes – Basics (Ch1-6)
Lecture Notes – Arrays and ArrayLists (Ch 7-8)
Implementing Classes Yonglei Tao.
Classes, Libraries & Packages
CMSC 202 Static Methods.
ARRAYS & ARRAY LISTS.
Slides by Donald W. Smith
CS 302 Week 8 Jim Williams, PhD.
Classes and Objects 5th Lecture
AKA the birth, life, and death of variables.
int [] scores = new int [10];
Classes and Objects Static Methods
Using java libraries CGS3416 spring 2019.
Presentation transcript:

Lecture Notes – Classes and Objects (Ch 7-8) Yonglei Tao

Arrays  Hold sequences of values of primitive types or objects  When an array is created, its values are initialized  zero, false, or null int [] scores; scores = new int [10]; for (int i = 0; i < scores.length; i++) scores[i] = i * i; for (int n: scores)// a “for each” loop System.out.println (n);

Arrays (Cont.) String[] names = {“Ed”, “Bob”, “Cindy”}; System.out.println( names[0] ); if ( names[0].equals(“Ed”)) … String[] list = new String[5]; list[0] = new String(“Tom”); … A two-dimensional array int rows = 10, cols = 20; int [][] table = new int[rows][cols];

Partially Filled Arrays - Loading int numValues = 0; Scanner in = new Scanner(System.in); while (in.hasNextDouble()) { if (numValues < values.length) { values[numValues] = in.nextDouble(); numValues ++; } for (int i = 0; i < numValues; i++) { System.out.println(values[i]); }

Class ArrayList  A sequence of objects  Can grow and shrink as needed  A generic class with a type parameter ArrayList classlist = new ArrayList (); classlist.add ( “Ed” ); classlist.add ( “Bob” ); classlist.add ( “Cindy” );

ArrayList (Cont.) for (int i = 0; i < classlist.size(); i++ ) { String name = classlist.get(i); System.out.println (name); // Ed, Bob, Cindy } for ( String name: classlist ) System.out.println (name); classlist.set (1, “Tim”);// Ed, Tim, Cindy classlist.add (1, “Ron”);// Ed, Ron, Tim, Cindy classlist.remove (2);// Ed, Ron, Cindy

Wrapper Classes

Auto Boxing and Unboxing int n = 25; Integer num = n; // same as num = new Integer (n); Double rate = 5.25; double d = rate; rate = rate + i; Boolean isDone = new Boolean(false); ArrayList values = new ArrayList (); values.add(29.95); double x = values.get(0);// inefficient

Arrays vs. ArrayLists  When do you use which?  Element type  Number of elements  Basic operations  Locate  insert (at the front, in the middle, at the end)  delete (the first, a middle one, the last)

Common Array Algorithm - Search int pos = 0; boolean found = false; while (pos < values.size() && !found) { if (values.get(pos) > 100) { found = true; } else { pos++; } } if (found) { System.out.println("Position: " + pos); } else { System.out.println("Not found"); }

Common Array Algorithm - Insert ArrayList: use method add Unordered array: if (numValues < values.length) { values[numValues] = newElement; numValues++; }

Common Array Algorithm - Insert  Ordered array: if (numValues < values.length) { for (int i = numValues ; i > pos; i--) values[i] = values[i - 1]; values[pos] = newElement; numValues ++; }

Common Array Algorithm – Array Copy double[] values = new double[6];... // Fill array double[] prices = values;? double[] prices = Arrays.copyOf(values, values.length); values = Arrays.copyOf(values, 2 * values.length);

Classes  Each has a responsibility  Each provides services for clients  Objects are instances of a class  Members  Instance variablesprivate  Instance methodsprivate  Instance methodspublic- interface

Method Call  A call obj.doIt (num, name);  Method definition public void doIt (int n, String s) { n += 4; System.out.println (“Start with “ + s.charAt(0)); }  Every thing is passed by value  What if having s = “Mr. “+ s; in method doIt()? “tom” 6 6

Overloaded Methods // Methods of class MyClass public void doIt (int n) { … } public void doIt (char c) { … } public void doIt (int n, String s) { … } // Method calls MyClass obj = new MyClass(); obj.doIt(5); obj.doIt(‘a’); obj.doIt(“xyz”);

Constructors public class A { private int num; private String name; public A () { this(10, “tom”); } public A (int n) { num = n; } public A (int n, String s) { num = n; name = s; } … } // use of constructors A ref1 = new A(); A ref2 = new A(5); A ref3 = new A(10, “tom”);

Static Members of a Class  Instance variable  One copy per object  Static variable  One copy per class  Static Method  Operating on class-wide data  Examples  Integer.MAX_VALUE, Integer.MIN_VALUE  Math.pow(x, y), Math.sqrt(x)

Scope of Local Variables public class RectangleTester { public static double area(Rectangle rect) { double r = rect.getWidth() * rect.getHeight(); return r; } public static void main(String[] args) { Rectangle r = new Rectangle(5, 10, 20, 30); double a = area(r); System.out.println(r); } }

Scope of Local Variables if (x >= 0) { double r = Math.sqrt(x);... } // Scope of r ends here else { Rectangle r = new Rectangle(5, 10, 20, 30); // OK - it is legal to declare another r here... }

Overlapping Scope public class Coin {... public double getExchangeValue(double exchangeRate) { double value;... return value; } private String name; private double value; }  Which one to refer to if using value in this method?  How to refer to instance variable value in this method?

Built-in Reference this  Referring to an object from within public A (int num, String name) { this.num = num; this.name = name; }  Referring to the current object A x = new A(10, “bob”); A y = new A(5, “ed”); x.setNum(1);

Packages in Java PackagePurposeSample Class java.lang Language support Math java.util Utilities Random java.io Input and output PrintStream java.awt Abstract Windowing Toolkit Color java.applet Applets Applet java.net Networking Socket java.sql Database Access ResultSet javax.swing Swing user interface JButton omg.w3c.dom Document Object Model for XML documents Document

Packages - Organizing related classes To put classes in a package package cis500.proj1; public class MyClass {... } To use class with importing import cis500.proj1.MyClass; Or import cis500.proj1.*;