Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

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.
Java Review Interface, Casting, Generics, Iterator.
Written by: Dr. JJ Shepherd
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Chapter 10 Introduction to Arrays
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
J.43 ARRAYS  A Java array is an Object that holds an ordered collection of elements.  Components of an array can be primitive types or may reference.
C#.NET C# language. C# A modern, general-purpose object-oriented language Part of the.NET family of languages ECMA standard Based on C and C++
1 CS 177 Week 15 Recitation Slides Review. Announcements Final Exam on Sat. May 8th  PHY 112 from 8-10 AM Complete your online review of your classes.
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.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Arrays, Loops weeks 4-6 (change from syllabus for week 6) Chapter 4.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
Previous Exam 1.0. Question 1 - a Is the following statement true or false? Briefly explain your answer. A && B is the same as B && A for any Boolean.
Exceptions and IO Dr. Andrew Wallace PhD BEng(hons) EurIng
Arrays And ArrayLists - S. Kelly-Bootle
1 Review of Java Higher Level Language Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – Selection –Flow of.
G51PRG-Sem2 A Reality Check a sort of quiz Dave Elliman.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CS125 Exam Review Winter Some Exam Info Tuesday (22nd) at 4:00-6:30pm in the PAC CHECK YOUR SEAT!!! Read Final Exam Information on website –Practice.
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
Geoff Holmes and Bernhard Pfahringer COMP206-08S General Programming 2.
From C++ to Java A whirlwind tour of Java for C++ programmers.
1 Java: AP Curriculum Focus and Java Subset Alyce Brady.
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 8: Collections: Arrays. 2 Objectives One-Dimensional Arrays Array Initialization The Arrays Class: Searching and Sorting Arrays as Arguments The.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
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.
Arrays An array is a data structure that consists of an ordered collection of similar items (where “similar items” means items of the same type.) An array.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Objects, Classes and Syntax Dr. Andrew Wallace PhD BEng(hons) EurIng
15440 Distributed Systems Recitation 1 Objected-Oriented Java Programming.
Introduction to Java Lecture Notes 3. Variables l A variable is a name for a location in memory used to hold a value. In Java data declaration is identical.
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.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Copyright Curt Hill Variables What are they? Why do we need them?
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
1 Review of Java Basic Concepts –Names and Reserved Words –Expressions and Precedence of Operators –Flow of Control – conditional statements –Flow of Control.
Fall 2002CS 150: Intro. to Computing1 Streams and File I/O (That is, Input/Output) OR How you read data from files and write data to files.
Inheritance Dr. Andrew Wallace PhD BEng(hons) EurIng
CMSC 341 Java Packages, Classes, Variables, Expressions, Flow Control, and Exceptions.
Java for C++ Programmers A Brief Tutorial. Overview Classes and Objects Simple Program Constructors Arrays Strings Inheritance and Interfaces Exceptions.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
Arrays and ArrayLists Topic 6. One Dimensional Arrays Homogeneous – all of the same type Contiguous – all elements are stored sequentially in memory For.
CSE 143 Lecture 4 More ArrayIntList : Pre/postconditions; exceptions; testing reading: slides created by Marty Stepp and Hélène Martin
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Written by: Dr. JJ Shepherd
CSC Java Programming, Fall, 2008 Week 3: Objects, Classes, Strings, Text I/O, September 11.
A High Flying Overview CS139 – Fall 2006 How far we have come.
CSC Java Programming, Spring, 2010 Week 2: Java Data Types, Control Constructs, and their C++ counterparts.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Chapter 9 Introduction to Arrays Fundamentals of Java.
Arrays Chap. 9 Storing Collections of Values 1. Introductory Example Problem: Teachers need to be able to compute a variety of grading statistics for.
Comp1004: Environments The Java Library. Coming up Recap – Encapsulation – Constructors – Loops – Arrays – ArrayList – Iterators The Java Library – Implementation.
Object Oriented Programming Lecture 2: BallWorld.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
Topic: Classes and Objects
Exceptions, Interfaces & Generics
CS139 – Fall 2010 How far we have come
null, true, and false are also reserved.
Java Programming Language
Simple Classes in Java CSCI 392 Classes – Part 1.
ArrayLists 22-Feb-19.
Objects with ArrayLists as Attributes
Review for Midterm 3.
Presentation transcript:

Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng

Overview Classes Programming in Java Bugs Arrays Collections Generics Autoboxing For loop

Classes (bits and bobs) Class names start with a capital letter String Label Object MyClass Methods start with a small letter println getAlignment toString myFunction

Classes (bits and bobs) Constants are written in all capitals Use “_” to separate words PI (defined in java.lang.Math) CENTER (defined in java.awt.Label) ACTION_EVENT (defined in java.awt.Event) Follow the convention and your code will look like Java’s inbylt code

Classes (bits and bobs) Visibility Keep things as local as possible! Key words private protected public default

Classes (bits and bobs) Key wordSame classSame packet Sub class Anywhere privateyesno protectedyes no publicyes “default”yes no Packet Class SubClass

Quiz List the four types of visibility modifiers in Java What is the Java convention for class and method names?

Classes (bits and bobs) Methods with the same name But differ signatures! Signature is : method name + parameters public int aMethod(int x) public int aMethod(int x, int y)

Classes (bits and bobs) Overloading constructors Call constructor in super class super(…); public Square() { this(50, 50); } Public Square(int x, int y) { m_nX = x; m_nY = y; }

Classes (bits and bobs) String Class String strText = “Hello World”; String methods: String concat(String str) char chatAt(int index) int length()

Classes (bits and bobs) Simple output Java uses class “PrintStream” System.out Normal text output System.err Error output

Classes (bits and bobs) PrintStream main methods print println Overloaded methods For all java types

Classes (bits and bobs) Static Key word Not associated with an object Access without creating an object Avoid! Breaks the object model But is sometimes needed

Classes (bits and bobs) Static attributes Same for all objects of a given class private static int nVar; Constants PI public static final double PI = ;

Classes (bits and bobs) Static method Class method No need to create an object Called using class name Math.sin(double a) Math.toDegrees(double angrad) Object.equals(Object a, Object b) Util.isLocal(Stub stub)

Classes (bits and bobs) Static methods can’t call non static methods or attributes You have no local reference Main public static main(String[] args) Main is where the code starts Creates where you need to run your program

Programming in Java Sequence of steps Control structures if if … else switch while do.. while for

Programming in Java if true or false if (condition) { } if(bVal) if(!bVal) if(nVal == 0)

Programming in Java if … else if … else if … else if(bVal) … else … if(nVal == 0) … else if(nVal == 1) … else …

Programming in Java Switch Multiple if.. Else switch(nVal) { case 0: … case 1: … case 2: … default : … }

Programming in Java while do … while When you don’t know how long you have to loop Condition to get out of the loop while(!bFound) { … bFound = true; } do { … }while(!bFound)

Programming in Java for When you know how many times you want to loop for( ; ; ) for(i=0; i<strText.length(); i++) { }

Programming in Java Enhanced for loop For arrays for( : ) { … } Index is of the type of the array! int[] m_Array = {1, 2, 3}; for(int i : m_Array) { … }

Quiz What are the three ways to create a loop in Java? What are the two ways to make a decision in Java?

Bugs Program boundary Program Input Output check function

Bugs Use if statements to check data on the boundaries File I/O User inputs Memory allocations New What to do? Handel the error Inform user Output an error / debug message Use the debugger to finds out what happened throw (try … catch)

Bugs throws public void myMethod() throws Has to be caught or thrown again

Bugs try { … } catch ( ) { … } finally { … }

Quiz How do you check inputs are correct? What are the parts of a try statement?

Arrays nUsefullBox 25

Arrays nUsefullBoxes

Arrays To create a reference to an array type name[]arrayName; Int[]nArrayOfNumbers; Instantiate nArrayOfNumbers = new int[100];

Arrays nArrayOfNumbers[0] = 1; nArrayOfNumbers[1] = 2; nArrayOfNumbers[2] = 3; nArrayOfNumbers[i] = i + 1; private String[] strText = {“Epsilon Eridani”, “Tau Ceti”, “Alpha Ursae Majoris”};

Arrays Array is a data type type name[] Implemented as objects Multiple dimensions private double[][]Matrix = new double[5][5]; Arrays class Methods for manipulating arrays Search Sort

Arrays Array copy System arraycopy(src, 0, dest, 0, src.length); Else Element by element in a loop Multi-dimensions Call many times Passing arrays to methods private void func(String[] str); Return from a method public String[] aMethod(String[] strText)

Arrays Fail to instantiate an array Null pointer exception If new fails Out of memory exception Access beyond the array bounds Index out of bounds exception

Collections Handling a “group” of objects in one “block” Lists Queues Set

Collections ArrayList Class for dynamically handling arrays Add Remove toArray A type of “collection”

Generics A way to use the same code with differ types A generic algorithm Declare with a type parameter public class name public class Var { private T t; public void set(T t) {this.t = t} } private Var nVar;

Generics public class ArrayList boolean add(E e) E set(int index, E element) List subList(int fromIndex, int toIndex)

Autoboxing Primitive data types to/from classes Integer i = new Integer(1); Integer j = new Integer(2); Integer k = i + j; int x = i + 5; Since java 5

Autoboxing ArrayList myList = new ArrayList(); myList.add(new Integer(103)); ArrayList myList = new ArrayList (); myList.add(103);

Iterator Class for iterating around a loop Vector v = new Vector … Iteratorit = v.iterator(); … while(it.hasNext()) { … it.next(); }

Questions?