Introduction to Java 2 Programming Lecture 3 More Syntax; Working with Objects.

Slides:



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

Introduction to Java 2 Programming
Introduction to Java 2 Programming Lecture 5 Array and Collections.
Introduction to Java 2 Programming Lecture 2 Java Syntax, Robocode.
Introduction to Java 2 Programming Lecture 3 Writing Java Applications, Java Development Tools.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 3: Flow Control I: For Loops.
Introduction to Programming
JAVA Revision Lecture Electronic Voting System Marina De Vos.
8/7: Ch. 7: Arrays What is an array? Declaring & allocating arrays Program of the day.
Object Oriented Programming with Java
Chapter 8: Arrays.
Copyright 2008 by Pearson Education 1 Nested loops reading: 2.3 self-check: exercises: videos: Ch. 2 #4.
1.A computer game is an example of A.system software; B.a compiler; C.application software; D.hardware; E.none of the above. 2.JVM stands for: A.Java Virtual.
Purpose : To convert this string to a new character array. Return Type : char[ ] Parameters : none Declaration : public char[ ] toCharArray() Returns.
Introduction to Arrays Chapter What is an array? An array is an ordered collection that stores many elements of the same type within one variable.
Two-Dimensional Arrays Chapter What is a two-dimensional array? A two-dimensional array has “rows” and “columns,” and can be thought of as a series.
Introduction to Programming Lecture 15. In Today’s Lecture Pointers and Arrays Manipulations Pointers and Arrays Manipulations Pointers Expression Pointers.
Introduction to Assembly language
ITEC 320 Lecture 3 In-class coding / Arrays. Arrays Review Strings –Advantages / Disadvantages Input –What two methods are used? Conditionals Looping.
Copyright 2010 by Pearson Education Building Java Programs Chapter 7 Lecture 7-2: Arrays as Parameters reading: , 3.3 self-checks: Ch. 7 #5, 8,
INTERFACES IN JAVA 1.Java Does not support Multiple Inheritance directly. Multiple inheritance can be achieved in java by the use of interfaces. 2.We need.
Introduction to Java Objects CSIS 3701: Advanced Object Oriented Programming.
Constructors & An Introduction to Methods. Defining Constructor – Car Example Public class car { String Model; double speed; String colour; { Public Car.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
 2003 Prentice Hall, Inc. All rights reserved. 7.1 Introduction Arrays –Data structures which reference one or more value –All items must have same data.
Arrays  Writing a program that uses a large amount of information.  Such as a list of 100 elements.  It is not practical to declare.
Introduction to Computers and Programming Lecture 17: Arrays (cont) Professor: Evan Korth New York University.
Loops – While, Do, For Repetition Statements Introduction to Arrays
1 Lecture Today’s topic Arrays Reading for this Lecture: –Chaper 11.
What is a class? a class definition is a blueprint to build objects its like you use the blueprint for a house to build many houses in the same way you.
Multiple-Subscripted Array
 2003 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to Arrays Introduction to Computers and Programming in.
CS102--Object Oriented Programming Review 1: Chapter 1 – Chapter 7 Copyright © 2008 Xiaoyan Li.
1 CSCE 1030 Computer Science 1 Arrays Chapter 7 in Small Java.
TODAY’S LECTURE Review Chapter 2 Go over exercises.
Programming Languages -1 (Introduction to C) arrays Instructor: M.Fatih AMASYALI
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Programming with C# Iteration LECTURE 3. Summary of last lecture SequenceSelectionif and switch statementsCastingRandom.
Arrays Chapter 7. 2 "All students to receive arrays!" reports Dr. Austin. Declaring arrays scores : Inspecting.
 2005 Pearson Education, Inc. All rights reserved. 1 Arrays Part 4.
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
 Pearson Education, Inc. All rights reserved Arrays.
Array Cs212: DataStructures Lab 2. Array Group of contiguous memory locations Each memory location has same name Each memory location has same type a.
1 BUILDING JAVA PROGRAMS CHAPTER 7.1 ARRAY BASICS.
Arrays Array – Group of contiguous memory locations Each memory location has same name Each memory location has same type.
Dale Roberts Object Oriented Programming using Java - Enumerations Dale Roberts, Lecturer Computer Science, IUPUI Department.
Programming in Java Dr. M. Ahmadzadeh. Course Outline (subject to tiny changes) I will cover the following but not necessarily in this order. –Strings.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
CPSC1301 Computer Science 1 Chapter 8 Introduction to Processing Digital Sounds part 3.
CPSC1301 Computer Science 1 Chapter 4 Manipulating Pictures, Arrays, and Loops part 5.
1 BUILDING JAVA PROGRAMS CHAPTER 7.2 ARRAY TRAVERSAL ALGORITHMS.
Arrays Chapter 7. 2 Declaring and Creating Arrays Recall that an array is a collection of elements all of the _____________ Array objects in Java must.
AP Java Ch. 4 Review Question 1  Java methods can return only primitive types (int, double, boolean, etc).
Intro-Sound-Mod10-part31 Introduction to Processing Digital Sounds part 3 while loop, tracing, for loop, parameters Barb Ericson Georgia Institute of Technology.
 Introducing Arrays  Declaring Array Variables, Creating Arrays, and Initializing Arrays  Copying Arrays  Multidimensional Arrays  Search and Sorting.
1 Lecture 4: Part1 Arrays Introduction Arrays  Structures of related data items  Static entity (same size throughout program)
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 9: Arrays; Revision Session.
 2005 Pearson Education, Inc. All rights reserved Arrays.
ITEC 320 Lecture 6 More on arrays / Strings. Arrays Review Scope Exceptions Arrays –Dynamic arrays How? Typed and anonymous.
Introduction to programming in java Lecture 23 Two dimensional (2D) Arrays – Part 3.
Introduction to programming in java Lecture 21 Arrays – Part 1.
Arrays Chapter 7.
Control structures Chapter 3.
An Introduction to Java – Part II
Conditional Statements
More On Enumeration Types
Exercise 1 Declare a constant of type int called SIZE and initialize it to value 10 Declare two int arrays of size “SIZE” Assume that those int arrays.
Arrays Chapter 7.
Unit-1 Introduction to Java
Arrays Introduction to Arrays Reading for this Lecture:
Presentation transcript:

Introduction to Java 2 Programming Lecture 3 More Syntax; Working with Objects

Overview More new syntax –Arrays –String/StringBuffer objects –Parameter passing Working with objects –Constructors –Constants Exercises

Java Arrays – The Basics Declaring an array int[] myArray; int[] myArray = new int[5]; String[] stringArray = new String[10]; String[] strings = new String[] {one, two}; Checking an arrays length int arrayLength = myArray.length; Looping over an array for(int i=0; i<myArray.length; i++) { String s = myArray[i]; }

Java Arrays – Bounds Checking Bounds checking –Java does this automatically. Impossible to go beyond the end of an array (unlike C/C++) –Automatically generates an ArrayIndexOutOfBoundsException

Java Arrays – Copying Dont copy arrays by hand (e.g. by looping over the array) The System class has an arrayCopy method to do this efficiently int array1[] = new int[10]; int array2[] = new int[10]; //assume we add items to array1 //copy array1 into array2 System.arrayCopy(array1, 0, array2, 0, 10); //copy last 5 elements in array1 into first 5 of array2 System.arrayCopy(array1, 5, array2, 0, 5);

Java Arrays – Sorting Again no need to do this by hand. The java.util.Arrays class has methods to sort different kinds of arrays int myArray[] = new int[] {5, 4, 3, 2, 1}; java.util.Arrays.sort(myArray); //myArray now holds 1, 2, 3, 4, 5 Sorting arrays of objects is involves some extra work, as well see in a later lesson

Strings Strings are objects The compiler automatically replaces any string literal with an equivalent String object –E.g. my String becomes new String(my string); Strings are immutable –Cant be changed once created… –..but can be concatenated (using +) to create new strings String newString = abc + def;

Strings Strings have methods to manipulate their contents: int length = someString.length(); String firstTwoLetters = someString.substring(0,2); String upper = someString.toUpperCase(); boolean startsWithLetterA = someString.startsWith(A); boolean containsOther = (someString.indexOf(otherString) != -1)

StringBuffer StringBuffer object allows a string value to be manipulated –I.e. they are not immutable StringBuffer has useful methods like: –Append, insert, delete, replace, etc Compiler automatically replaces String concatenation with a StringBuffer object –E.g. my String + other String becomes… new StringBuffer(my String).append(other String).toString();

StringBuffer Take care with String concatenation –Explicitly using a StringBuffer is often more efficient –Can reuse buffer rather than discarding it StringBuffer.setLength(0)

Passing Parameters Java has two ways of passing parameters –Pass by Reference –Pass by Value Pass by Value applies to primitive types –int, float, etc Pass by Reference applies to reference types –objects and arrays

Passing Parameters public class PassByValueTest { public void increment(int x) { x = x + 1; } public void test() { int x = 0; increment(x); //whats the value of x here? }

Passing Parameters public class PassByReferenceTest { public void reverse(StringBuffer buffer) { buffer.reverse(); } public void test() { StringBuffer buffer = new StringBuffer(Hello); reverse(buffer); //what does buffer contain now? }

Overview More new syntax –Arrays –Constants –String/StringBuffer objects –Parameter passing Working with objects –Constructors –Constants Exercises

Initialising Objects Variables of a reference type have a special value before they are initialised –A nothing value called null Attempting to manipulate an object before its initialised will cause an error –A NullPointerException To properly initialise a reference type, we need to assign it a value by creating an object –Objects are created with the new operator String someString = new String(my String);

Constructors new causes a constructor to be invoked –Constructor is a special method, used to initialise an object –Class often specifies several constructors (for flexibility) –new operator chooses right constructor based on parameters (overloading) Constructors can only be invoked by the new operator

Constructors – Example 1 public class MyClass { private int x; public MyClass(int a) { x = a; } We can then create an instance of MyClass as follows: MyClass object = new MyClass(5); //constructor is called

What are constructors for? Why do we use them? –Give us chance to ensure our objects are properly initialised –Can supply default values to member variables –Can accept parameters to allow an object to be customised –Can validate this data to ensure that the object is created correctly. A class always has at least one constructor –…even if you dont define it, the compiler will –This is the default constructor

Constructors – Example 2 public class Address { public Address(String address) { if == -1) { //not a valid address, signal an error? } //must be valid… } //methods }

Destroying Objects No way to explicitly destroy an object Objects destroyed by the Garbage Collector –Once they go out of scope (I.e. no longer referenced by any variable) No way to reclaim memory, entirely under control of JVM –There is a finalize method, but its not guaranteed to be called (so pretty useless!) –Can request that the Garbage Collector can run, buts its free to ignore you

Modifiers Public/private are visibility modifiers –Used to indicate visibility of methods and attributes Java has a range of other modifiers –Control ownership of a method or attribute –Control when and how variable can be initialised –Control inheritance of methods (and whether they can be overridden by a sub-class)

Static static – indicates a class variable or class method. Its not owned by an individual object –This means we dont have to create an object to use it –Arrays.sort and System.arrayCopy are static methods

Static -- Example public class MyClass { public static void utilityMethod() { … } public void otherMethod() { … } } //using the above: MyClass.utilityMethod(); MyClass objectOfMyClass = new MyClass(); objectOfMyClass.otherMethod(); objectOfMyClass.utilityMethod(); //this is illegal: MyClass.otherMethod();

Final final – to make a variable that can have a single value –Can be assigned to once and once only –Useful to ensure a variable isnt changed once its assigned. final int count; count = 10; //the following will cause an error count = 20;

Defining Constants Unlike other languages, Java has no const keyword Must use a combination of modifiers to make a constant –static – to indicate its owned by the class –final – to make sure it cant be changed (and initialise it when its declared) Naming convention for constants is to use all capitals Example…

Constants – An Example public class MyClass { public static final int COUNT = 0; public static final boolean SWITCHED_ON = false; } //example usage: if (MyClass.COUNT > 0) { … } if (MyClass.SWITCHED_ON) {…}

Exercises The MovementFollower robot –Follows a series of movement instructions The DamageReporter robot –Compiles a damage report

Movement Follower

Damage Reporter