More non-primitive types Lesson 06

Similar documents
Lesson 06 Arrays. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

STUDENT LESSON A10 The String Class

A variable is a name for a location in memory A variable must be declared

Lesson:9 Working with Array and String

Introduction to Programming Using Java (98-388)

Programming with Java

We now start exploring some key elements of the Java programming language and ways of performing I/O

OOP-Lecture Java Loop Controls: 1 Lecturer: Hawraa Sh. You can use one of the following three loops: while Loop do...while Loop for Loop

Chapter 6 part 1. Data Types. (updated based on 11th edition) ISBN

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

J.43 The length field of an array object makes the length of the array available. J.44 ARRAYS

Introduction. Primitive Data Types: Integer. Primitive Data Types. ICOM 4036 Programming Languages

Chapter 6. Data Types

Using Java Classes Fall 2018 Margaret Reid-Miller

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

2. All the strings gets collected in a special memory are for Strings called " String constant pool".

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

"Hello" " This " + "is String " + "concatenation"

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

Visual C# Instructor s Manual Table of Contents

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

ARRAYS(II Unit Part II)

Introduction Primitive Data Types Character String Types User-Defined Ordinal Types Array Types. Record Types. Pointer and Reference Types

Chapter 9 Introduction to Arrays. Fundamentals of Java

Eng. Mohammed Abdualal

Introduction to C Final Review Chapters 1-6 & 13

Slide 1 CS 170 Java Programming 1 More on Strings Duration: 00:00:47 Advance mode: Auto

Arrays. Outline 1/7/2011. Arrays. Arrays are objects that help us organize large amounts of information. Chapter 7 focuses on:

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

The Warhol Language Reference Manual

CSC 1051 Algorithms and Data Structures I. Midterm Examination March 1, Name: KEY A

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)

Arrays (Deitel chapter 7)

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

Instructor: Eng.Omar Al-Nahal

Creating Strings. String Length

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

JVM (java) compiler. A Java program is either a library of static methods (functions) or a data type definition

C++ Programming. Arrays and Vectors. Chapter 6. Objectives. Chiou. This chapter introduces the important topic of data structures collections

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Introduction to Java & Fundamental Data Types

Lab 14 & 15: String Handling

Strings in Java String Methods. The only operator that can be applied to String objects is concatenation (+) for combining one or more strings.

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

Enumerated Types. Mr. Dave Clausen La Cañada High School

Lesson 9: Introduction To Arrays (Updated for Java 1.5 Modifications by Mr. Dave Clausen)

COSC252: Programming Languages: Basic Semantics: Data Types. Jeremy Bolton, PhD Asst Teaching Professor

Topics. Chapter 5. Equality Operators

Arrays Data structures Related data items of same type Remain same size once created Fixed-length entries

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

Java How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Full file at

Computational Expression

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

Object Oriented Programming. Java-Lecture 6 - Arrays

CSE1710. Big Picture. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

Data Types, Variables and Arrays. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Chapter 12 Strings and Characters. Dr. Hikmat Jaber

For each of the following variables named x, specify whether they are static, stack-dynamic, or heapdynamic:

Datatypes, Variables, and Operations

Index COPYRIGHTED MATERIAL

Reviewing for the Midterm Covers chapters 1 to 5, 7 to 9. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

SPRING 13 CS 0007 FINAL EXAM V2 (Roberts) Your Name: A pt each. B pt each. C pt each. D or 2 pts each

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Logic & program control part 2: Simple selection structures

Program Fundamentals

Java Arrays (review) Linked Lists (preview)

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

5/23/2015. Core Java Syllabus. VikRam ShaRma

VARIABLES AND TYPES CITS1001

Strings. Strings and their methods. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Data and Variables. Data Types Expressions. String Concatenation Variables Declaration Assignment Shorthand operators. Operators Precedence

Mr. Monroe s Guide to Mastering Java Syntax

Lecture Notes K.Yellaswamy Assistant Professor K L University

Lecture 2 Tao Wang 1

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

Building Strings and Exploring String Class:

Basic Elements of C. Staff Incharge: S.Sasirekha

Chapter 8 Arrays and Strings. Objectives. Objectives (cont d.) Introduction. Arrays 12/23/2016. In this chapter, you will:

CMPT 125: Lecture 3 Data and Expressions

ASSIGNMENT 4 Classes and Objects

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

SECTION II: LANGUAGE BASICS

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

CSC 1214: Object-Oriented Programming

Duhok Polytechnic University Amedi Technical Institute/ IT Dept. Halkawt Rajab Hussain

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Abstract Data Type (ADT) & ARRAYS ALGORITHMS & DATA STRUCTURES I COMP 221

String. Other languages that implement strings as character arrays

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

More on variables and methods

Spring 2010 Java Programming

Sprite an animation manipulation language Language Reference Manual

Language Reference Manual

Lexical Considerations

Programming for Engineers Arrays

Transcription:

CSC110 2.0 Object Oriented Programming Ms. Gnanakanthi Makalanda Dept. of Computer Science University of Sri Jayewardenepura More non-primitive types Lesson 06 1 2 Outline 1. Two-dimensional arrays 2. The String class 3. Enumeration 4. Summary Two-dimensional arrays Arrays with two dimensions are often used to represent tables of values consisting of information arranged in rows and columns. Two-dimensional arrays We must use two indexes to refer to a value in a two-dimensional array, one specifying the row and another the column. In Java, you can create n-dimensional arrays for any integer n. 3 4 Declaring A multidimensional array with the same number of columns in every row can be created with an arraycreation expression or type [][] arrayname; type arrayname [][]; // This style is Example: int [][] grades; // correct, but not preferred Creating Create a 2D array with numrows and numcols arrayname = new type[numrows][numcols]; Example: grades = new int[3][2]; Shortcut to declare and create a 2D array: int [][]grades = new int[3][2]; 5 6 1

Initialization Elements (1/2) Can be initialized with array initializers in declarations. int b[][] = {{1, 2}, {3, 4}, {5, 6}}; Each element in the 2D array must be the same type, either a primitive type or object type. Subscripted variables can be used just like a variable: grade[0][3] = 70; 7 8 Elements (2/2) Array indices must be of type int and can be a literal, variable, or expression. grade[3][j] = 56; If an array element does not exists, the Java runtime system will give you an ArrayIndexOutOfBoundsException Arrays of One-Dimensional Arrays Java does not actually have two-dimensional arrays. In a true 2D array, all the elements of the array occupy a continuous block of memory, but that's not true in Java. Two-dimensional arrays are maintained as arrays of separate one-dimensional arrays. Array in preceding declaration is composed of three separate one-dimensional arrays {1, 2 }, {3, 4} and {5, 6} 9 10 Ragged arrays (1/2) The lengths of the rows are not required to be the same. Creating: // create 2 rows int b[][] = new int[2][]; // create 5 columns for row 0 int b[0] = new int[5]; // create 3 columns for row 1 int b[1] = new int[3]; Ragged arrays (2/2) Initializing: int b[][]= {{1, 2}, {3, 4, 5}}; The int array for row 0 is a one-dimensional array with two elements. The int array for row 1 is a one-dimensional array with three elements. 11 12 2

Lengths Int [][] grades = new int[3][5]; grades.length is 3 grades[0].length is 5 grades[1].length is 5 grades[2].length is 5 grades[3].length is 5 2D Arrays and methods Can have 2D arrays as parameters int calculatesum(int[][] parray) To pass a 2D array argument to a method, specify the name without any brackets. sum = calculatesum(sample); 13 14 The String class A string is an object of class String Constructing a String: String message = "Welcome to Java"; String message = new String( "Welcome to Java"); String s = new String(); Always initialize using the assignment operator = and text in quotation marks. Strings Are Immutable Immutable Contents cannot be changed after they are created. Class String does not provide any methods that allow the contents of a String objects to be modified. Does the following code change the contents of the string? String s = "Hello"; s = "Java"; 16 17 Strings Are Immutable String s = "Hello"; s = "Java"; Interned Strings String literals are stored as String objects and interned. For strings with matching characters, they all point to the same String object. After executing String s = "Hello"; s String object for "Hello" s After executing s = "Java"; String object for "Hello" This string object is now unreferenced String s1 = "Welcome to Java"; String s2 = new String("Welcome to Java"); String s3 = "Welcome to Java"; s1 s3 Interned string object for "Welcome to Java" Contents cannot be changed String object for "Java" System.out.println("s1 == s2 is " + (s1 == s2)); s2 System.out.println("s1 == s3 is " + (s1 == s3)); A string object for "Welcome to Java" 18 19 3

String Concatenation Use + String concatenation Every primitive value and object in Java has a String representation When one of the + operator s operands is a string, the other is converted to a String, and then the two are concatenated. "Maximum is: " + result If any trailing zeros in a double value, these will be discarded when the number is converted to a string. String Indexes It is occasionally helpful to refer to a particular character within a string This can be done by specifying the character's numeric index The indexes begin at zero in each string In the string "Hello", the character 'H' is at index 0 and the 'o' is at index 4 20 21 Simple String methods (1/3) Several methods of the String class return new String objects that are modified versions of the original Simple String methods (2/3) int length() Returns the number of characters in this string char charat(int index) Returns character at the specified index String concat(string str) Returns a new string consisting of this string concatenated with str. 22 23 Simple String methods (3/3) String replace (char oldchar, char newchar) Returns a new string that is identical with this string except that every occurrence of oldchar is replaced by newchar. String substring (int offset, int endindex) Returns a new string that is a subset of this string starting at index offset and extending through endindex-1. Changing the case of characters String tolowercase() returns a String object that contains lowercase equivalent this string. String touppercase() returns a String object that contains uppercase equivalent of this string. Nonalphabetic characters, such as digits, are unaffected. 24 25 4

String comparison (1/2) boolean equals(string str) Returns true if this string contains the same characters as str (including case) and false otherwise. boolean equalsignorecase( String str) Returns true if this string contains the same characters as str (without regard to case) and false otherwise. String comparison (2/2) int compareto (String str) Returns an integer indicating if this string is lexically before (a negative return value), equal to (a zero return value), or lexically after (a positive return value), the string str. 26 27 Strings in switch Statements (1/2) Strings in switch Statements (2/2) switch (day) { case "Mon": case "Fri": case "Sun": day = day + "day"; case "Tue": day = day + "sday"; case "Wed": day = day + "nesday"; case "Thu": day =day +"rsday"; case "Sat": day = day +"urday": default: day = "Sunday"; } 28 29 Enumeration (1/3) A special kind of class that is introduced by the keyword enum and a type name. keyword to indicate this is enumerated type public enum Status { CONTINUE, WON, LOST}; typically public, so can access outside this class name of the enum Similar to class, this is a new data type! Inside the braces is a comma separated list of constants, each representing a unique value- in ALL_CAPS. Enumeration (2/3) To declare a variable of this type: Status gamestatus; Variables of an enum type can be assigned only constants declared in the enumeration Otherwise a compilation error will occur. To specify a value, must include the name of the enumerated type gamestatus = Status.WON; 31 32 5

Enumeration (2/3) Can use in another class, if specify class name in which enum is declared: if (status == Game.Status.WON) An enumerated type variable can be null Ordinal Values Internally, each value of an enumerated type is stored as an integer, called its ordinal value The first value in an enumerated type has an ordinal value of 0, the second 1, and so on However, you cannot assign a numeric value to an enumerated type, even if it corresponds to a valid ordinal value 33 34 enum methods The declaration of an enumerated type is a special type of class, and each variable of that type is an object int ordinal() Returns the ordinal value of the object String name() Equivalent to tostring() Returns the name of the identifier corresponding to the object's value Summary (1/2) A two-dimensional array is really nothing more than an array of arrays Using an array with more than two dimensions is rare in an object-oriented system. The Java platform provides the String class to create and manipulate strings. The String class has over 60 methods and 13 constructors. 35 37 Summary (2/2) enum in Java is a keyword, a feature which is used to represent fixed number of well known values in Java enum can be used to create a set of valid values for a field or a method. Enumerated types are type-safe, ensuring that invalid values will not be used. We can add attributes and methods to the definition of an enumerated type. 38 6