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.

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

Recitation 4. 2-D arrays. Exceptions. Animal[] v= new Animal[3]; 2 declaration of array v v null Create array of 3 elements a6 Animal[] null Assign.
Topics Introduction Types of Errors Exceptions Exception Handling
Strings in Java 1. strings in java are handled by two classes String &
Chapter 7 Strings F To process strings using the String class, the StringBuffer class, and the StringTokenizer class. F To use the String class to process.
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Chapter 7 Strings F Processing strings using the String class, the StringBuffer class, and the StringTokenizer class. F Use the String class to process.
Written by: Dr. JJ Shepherd
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
CSM-Java Programming-I Spring,2005 Exceptions Lesson - 7.
CS102--Object Oriented Programming
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 15: Exception Handling.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
Chapter 16: Exception Handling C++ Programming: From Problem Analysis to Program Design, Fifth Edition.
Java Exceptions. Exceptions Often in computing, operations cannot properly execute because some sort of error has occurred. Some examples: Often in computing,
Exception Handling1. 2 Exceptions  Definition  Exception types  Exception Hierarchy  Catching exceptions  Throwing exceptions  Defining exceptions.
Final Review.
Strings and Arrays The objectives of this chapter are:  To discuss the String class and some of its methods  To discuss the creation and use of Arrays.
Programming 2 CS112- Lab 2 Java
Road Map Introduction to object oriented programming. Classes
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Exceptions Three categories of errors: Syntax errors Runtime errors Logic errors Syntax errors: rules of the language have not been followed. Runtime error:
16-Jun-15 Exceptions. Errors and Exceptions An error is a bug in your program dividing by zero going outside the bounds of an array trying to use a null.
Exceptions. Errors and Exceptions An error is a bug in your program –dividing by zero –going outside the bounds of an array –trying to use a null reference.
Java Syntax Primitive data types Operators Control statements.
CSM-Java Programming-I Spring,2005 String Handling Lesson - 6.
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.
Strings, Etc. Part I: Strings. About Strings There is a special syntax for constructing strings: "Hello" Strings, unlike most other objects, have a defined.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
28-Jun-15 String and StringBuilder Part I: String.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Sanjay Goel, School of Business, University at Albany, SUNY 1 MSI 692: Special Topics in Information Technology Lecture 4: Strings & Arrays Sanjay Goel.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Handling Exceptions in java. Exception handling blocks try { body-code } catch (exception-classname variable-name) { handler-code }
5-Aug-2002cse Arrays © 2002 University of Washington1 Arrays CSE 142, Summer 2002 Computer Programming 1
From C++ to Java A whirlwind tour of Java for C++ programmers.
1 © 2002, Cisco Systems, Inc. All rights reserved. Arrays Chapter 7.
Chapter 6Java: an Introduction to Computer Science & Programming - Walter Savitch 1 Chapter 6 l Array Basics l Arrays and Methods l Programming with Arrays.
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.
Introduction to Java Java Translation Program Structure
Vladimir Misic: Characters and Strings1Tuesday, 9:39 AM Characters and Strings.
String Class. Variable Holds a primitive value or a reference to an object. Holds a primitive value or a reference to an object. A reference lets us know.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
CSI 3125, Preliminaries, page 1 String. CSI 3125, Preliminaries, page 2 String Class Java provides the String class to create and manipulate strings.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Chapter 15: Exception Handling C++ Programming: Program Design Including Data Structures, Fifth Edition.
Array Declarations Arrays contain a fixed number of variables of identical type Array declaration and allocation are separate operations Declaration examples:
Java String 1. String String is basically an object that represents sequence of char values. An array of characters works same as java string. For example:
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
An Introduction to Java – Part 1 Erin Hamalainen CS 265 Sec 001 October 20, 2010.
17-Feb-16 String and StringBuilder Part I: String.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
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.
Chapter 8: Loops, Arrays, Strings Loop statements –do –while –for Arrays –declaration, allocation, initialization, access –multi-dimensional –heterogeneous.
Exception and Exception Handling. Exception An abnormal event that is likely to happen during program is execution Computer could run out of memory Calling.
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Object Oriented Programming Lecture 2: BallWorld.
2 Arrays Array is a data structure that represents a collection of the same type of data. A "fixed length list".
EKT 472: Object Oriented Programming
Exceptions 10-Nov-18.
Chapter 7: Strings and Characters
Java Programming Language
The Building Blocks Classes: Java class library, over 1,800 classes:
String methods 26-Apr-19.
Errors and Exceptions Error Errors are the wrongs that can make a program to go wrong. An error may produce an incorrect output or may terminate the execution.
In Java, strings are objects that belong to class java.lang.String .
Presentation transcript:

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 objects, including other arrays.  Arrays can be declared, allocated, and / or initialized all in one compact statement. int[] ai; int[] ia = new int[3]; char ac[] = {’n’, ’o’, ’t’}; The length of an array is fixed at creation and cannot be changed, but a new, longer array instance can be assigned to the Object.

J.44 The length field of an array object makes the length of the array available. Java supports arrays of arrays, rather than 2D or multi-dimensional arrays. Example: public class myArray { public static void main (String[] args) { double[] [] mat = {{1., 2., 3., 4.}, {5., 6., 7., 8.}, {9., 10., 11., 12.}, {13., 14., 15., 16.}}; for (int y = 0; y < mat.length; y++) { for (int x = 0; x < mat[y].length; x++) System.out.print(mat[y][x] + " "); System.out.println(); }}} What does it print? Is the array stored in row-major or column-major order?

J.45 STRINGS  The String class provides read-only strings and supports operations on them  A String can be created implicitly either by using a quoted string (e.g. "grass") or by the concatenation of two String objects, using the + operator.  A String can also be created using new and a String constructor. String aString = new String(); String bString = new String("grass”);

J.46 String Methods  length() returns the number of characters  charAt(i) returns the character at position i. for (int i = 0; i < str.length(); i++) System.out.println(charAt(i));  indexOf(char ch) returns the first position of character ch in a String.  lastIndexOf(char ch) returns the last position of character ch in a String.

J.47 String Comparisons  The method equals returns true if it is passed a reference to a String object with the same contents as a given String.  The method equalsIgnoreCase works like equals, but ignores upper/lower case distinctions.  The method compareTo returns an int that is less than, equal to, or greater than zero for comparisons and sorting. Example: Part of a Binary Search while (lo <= hi) { int mid = lo + (hi - lo) / 2; int cmp = key.compareTo(table[mid]); if (cmp == 0) return mid; else if (cmp < 0) hi = mid - 1; else lo = mid + 1; }

J.48 Since you cannot modify existing strings, there are methods to create new strings from existing ones.  public String substring(int beginIndex, int endIndex)  public String replace(char oldChar, char newChar)  public String concat(String str)  public String toLowerCase()  public String toUpperCase()  public String trim()

J.49 EXCEPTIONS  An exception is a condition that arises during execution.  An exception is thrown when an error condition is encountered.  It is then caught by code that receives it and deals with it.  Java exceptions are objects that extend the class Throwable or one of its subclasses, usually the subclass Exception.  Class Throwable and its subclasses have two constructors, one with no arguments and one with a String argument for an error message.

J.50 Defining Exceptions Programmers can define their own exception types and write code to throw them and catch them. Example with Attributes and Values: public class NoSuchAttributeException extends Exception { public String attrName; public Object newValue; NoSuchAttributeException(String name, Object value) { super("No attribute named \"" + name + "\" found"); attrName = name; newValue = value; }

J.51 Throwing Exceptions Methods that will check for errors and throw exceptions use  the throws clause to tell the compiler what kind of exceptions they may throw  the throw statement to perform the throwing Example: public void replaceValue(String name, Object newValue) throws NoSuchAttributeException { Attr attr = find(name); if (attr == null) throw new NoSuchAttributeException(name newValue); attr.valueOf(newValue); }

J.52 If your method invokes a method that lists a checked exception it its throwable clause, it can do one of three things  Catch the exception and handle it.  Catch the exception and map it into one of your own exceptions by throwing an exception of a type declared in your own throws clause  Declare the exception in your throws clause and let it pass through your method, possibly adding a finally clause that cleans up first.

J.53 Catching Exceptions Syntax: try catch ( ) catch( )... finally Example: try{ attributedObj.replaceValue(“Age”, new Integer(8)); } catch(NoSuchAttributeException e) { Attr attr = new Attr(e.attrName, e.newValue); attributedObj.add(attr); }

J.54 Finally  The finally clause of a try statement provides a mechanism for executing a section of code whether or not an exception is thrown.  This example closes a file when its work is done, even if an error occurs: public boolean searchFor(String file, String word) throws StreamException { Stream input = null; try { input = new Stream(file);* while (!input.eof()) if (input.next() == word) return* true; return* false; } *finally { if (input != null) input.close(); } * This can fail. * Finally is executed before any return.