Java characters Lecture 8

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

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

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

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

An Interesting Article. How Revolutionary Tools Cracked a 1700s Code.

B.V. Patel Institute of BMC & IT, UTU 2014

Chapter 2: Using Data

Variables, Constants, and Data Types

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Java Basic Datatypees

JAVA OPERATORS GENERAL

Number Systems, Scalar Types, and Input and Output

Zheng-Liang Lu Java Programming 45 / 79

CMPT 125: Lecture 3 Data and Expressions

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

Visual C# Instructor s Manual Table of Contents

Full file at

Programming Lecture 9

Getting started with Java

Java Programming Lecture 10

Full file at

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

Princeton University. Computer Science 217: Introduction to Programming Systems. Data Types in C

Chapter 2: Using Data

ECE 122 Engineering Problem Solving with Java

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

Strings, characters and character literals

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

Chapter 2 Elementary Programming

Basics of Java Programming

Programming with Java

Chapter. Let's explore some other fundamental programming concepts

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Chapter 6 Primitive types

Program Elements -- Introduction

Operators and Expressions

An overview of Java, Data types and variables

Introduction to Programming Using Java (98-388)

Java Notes. 10th ICSE. Saravanan Ganesh

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

Example: Tax year 2000

STUDENT LESSON A10 The String Class

Lecture Set 2: Starting Java

JAVA Programming Fundamentals

Characters, Strings and Text Processing in Java

Strings, Strings and characters, String class methods. JAVA Standard Edition

COMP6700/2140 Data and Types

Lecture Set 2: Starting Java

Chapter 2: Data and Expressions

Chapter 2 ELEMENTARY PROGRAMMING

Computer Programming, I. Laboratory Manual. Experiment #4. Mathematical Functions & Characters

CS 106 Introduction to Computer Science I

CS-201 Introduction to Programming with Java

Chapter 10: Text Processing and More about Wrapper Classes

2 nd Week Lecture Notes

Welcome to the Using Objects lab!

Lexical Considerations

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

AP Computer Science A

TCL - STRINGS. Boolean value can be represented as 1, yes or true for true and 0, no, or false for false.

CS260 Intro to Java & Android 03.Java Language Basics

Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

2/12/17. Goals of this Lecture. Historical context Princeton University Computer Science 217: Introduction to Programming Systems

More on variables and methods

4 Programming Fundamentals. Introduction to Programming 1 1

1.1. INTRODUCTION 1.2. NUMBER SYSTEMS

Object-Oriented Programming

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Lexical Considerations

CS Programming I: Using Objects

Primitive Data Types: Intro

Computers Programming Course 5. Iulian Năstac

CS1150 Principles of Computer Science Math Functions, Characters and Strings (Part II)

COMP Primitive and Class Types. Yi Hong May 14, 2015

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

UNIT - I. Introduction to C Programming. BY A. Vijay Bharath

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

The Warhol Language Reference Manual

Using Java Classes Fall 2018 Margaret Reid-Miller

Object interactions Lecture 6

CS Programming I: Using Objects

Standard 11. Lesson 9. Introduction to C++( Up to Operators) 2. List any two benefits of learning C++?(Any two points)

COMPUTER APPLICATIONS (86)

Prof. Navrati Saxena TA: Rochak Sachan

Section 2: Introduction to Java. Historical note

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Java Simple Data Types

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

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

LESSON 4. The DATA TYPE char

Chapter 02: Using Data

Program Fundamentals

Programming in C++ 4. The lexical basis of C++

1 class Lecture2 { 2 3 "Elementray Programming" / References 8 [1] Ch. 2 in YDL 9 [2] Ch. 2 and 3 in Sharan 10 [3] Ch.

Variables and Values

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. A Guide to this Instructor s Manual:

Java Basic Programming Constructs

CSC 1107: Structured Programming

Transcription:

Java characters Lecture 8 Waterford Institute of Technology January 31, 2016 John Fitzgerald Waterford Institute of Technology, Java characters Lecture 8 1/33

Presentation outline Estimated duration presentation Questions at end presentation Topics discussed: Method and constructor parameters Boxing & Autoboxing String class Character class Randomness Conditional operator (?:) Precedence Waterford Institute of Technology, Java characters Lecture 8 2/33

Primitives Passed as parameters Primitive object passed as parameter: Copy passed to method Change copy in method Variable outside method unchanged public class ArrayParameters { public static void testprimitiveparam (){ int val = 0; System.out.println.(val);//prints 0 modifyprimitive(val); System.out.println(val);//prints 0 public static void modifyprimitive(int v) { v = 100; Waterford Institute of Technology, Java characters Lecture 8 3/33

Arrays Passed as parameters Array reference passed as parameter: Argument references same object before and after call Changes to array in method persist outside method public class ArrayParameterPassing { public static void testarrayparam() { int[] ar = {1,2,3; System.out.println(ar[2]);//prints 3 modifyarray(ar); System.out.println(ar[2]);//prints 100 public static void modifyarray(int[] a) { a[2] = 100; Waterford Institute of Technology, Java characters Lecture 8 4/33

Wrapper class AutoBoxing (Boxing & Unboxing) Applies to wrapper classes such as Integer, Byte and so on Eight wrapper classes Java 7 Example: automatic conversion from primitive int to Integer Known as boxing Useful as keys in collections, e.g. ArrayList where primitives disallowed //Boxing //ArrayList<int> values: < not allowed // Below i is autoboxed through method invocation. ArrayList<Integer> values = new ArrayList<>(); for (int i = 0; i < 10; i += 1) { values.add(i); Waterford Institute of Technology, Java characters Lecture 8 5/33

Wrapper class Unboxing Example: automatic conversion from Integer object to int Referred to as unboxing ArrayList<Integer> values = new ArrayList<>(); for (int i = 0; i < 10; i += 1) { values.add(i); int[] ar = new int[values.size()]; for (int i = 0; i < ar.length; i += 1) { ar[i] = values.get(i); System.out.println(ar[i]); Waterford Institute of Technology, Java characters Lecture 8 6/33

Wrapper class Unboxing ArrayList<Double> ar = new ArrayList<>(); ar.add(3.1416); // PI is autoboxed through method invocation. //Unboxing through assignment double pi = ar.get(0); System.out.println("pi = " + pi); Waterford Institute of Technology, Java characters Lecture 8 7/33

Java String class Has several constructors and methods compareto(string anotherstring) touppercase() equalsignorecase(string anotherstring length() valueof(int i) //int to String //string literal String str = new String("textwidth"); int length = str.length(); //converts textwidth to TEXTWIDTH str.touppercase(); //creates string "100" referenced by str String str = String.valueOf(100); String str2 = "online"; //compares str and str2, returning false unless both strings equivalent str.equalsignorecase(str2); Waterford Institute of Technology, Java characters Lecture 8 8/33

Java String class Manipulate characters in String object String an ordered collection characters Zero-indexed array charat(int pos) accesses character at position pos Concatenate string objects concat(string str) concatenates str to existing string Overloaded + operator achieves same effect String str = "TEXT" str.charat(0) is "T" str.charat(1) is "E" str.charat(2) is "X" str.charat(3) is "T" String s3 = "why "; String s4 = "not?"; String s5 = s3 + s4; System.out.println("s3 + s4 " + s5); System.out.println("s3 + s4 "+s3.concat(s4)); //both statements output: s3 + s4 why not? Waterford Institute of Technology, Java characters Lecture 8 9/33

String objects immutable Health warning: String objects once created cannot be modified References below list other similar cases such as wrapper classes, example: Integer Byte Long String str = new String("java"); //str is reference pointing to string object "java" str.touppercase();//has no effect. Produces no warning. System.out.println(str);//outputs java, not JAVA str = "JAVA";//reference str points to different object System.out.println(str);//outputs JAVA Waterford Institute of Technology, Java characters Lecture 8 10/33

String objects immutable Easy to think otherwise String s1 = new String("java"); System.out.println(s1); // Output: java s1.touppercase(); System.out.println(s1); // Output: java System.out.println(s1.toUpperCase()); // Output: JAVA Waterford Institute of Technology, Java characters Lecture 8 11/33

String String literal v String object State and explain the outputs from following snippets. // String literals (interned) String a = "abcd"; String b = "abcd"; System.out.println("a equals b : " + (a == b)); // true System.out.println("c equals b : " + b.equals(c)); // true // String objects String c = new String("abcd"); String d = new String("abcd"); System.out.println("c equals d : " + (c == d)); // false System.out.println("c equals d : " + c.equals(d)); // true Waterford Institute of Technology, Java characters Lecture 8 12/33

Character Java primitive char is a primitive Java type char ch = 'a'; System.out.println(ch); outputs a Expose underlying integer representation int chint = (int)ch; System.out.println(chInt); outputs 97 Waterford Institute of Technology, Java characters Lecture 8 13/33

Character Java wrapper class Facilitates use of char where object required / This code snippet outputs: a A / Character c = new Character('a'); ArrayList<Character> characters = new ArrayList<>(); characters.add(c); characters.add('a'); for (Character character : characters) { System.out.print(character + " "); Waterford Institute of Technology, Java characters Lecture 8 14/33

Character class Some useful methods Determines if character ch is a digit static boolean isdigit(char ch) Determines if character ch is a letter static boolean isletter(char ch) Determines if character ch is letter or digit static boolean isletterordigit(char ch) Determines if character ch is a lowercase static boolean islowercase(char ch) Determines if character ch is upper case static boolean isuppercase(char ch) Determines if character ch is whitespace (space or tab) static boolean iswhitespace(char ch) Converts character ch to lower case static char tolowercase(char ch) Converts character ch to upper case static char touppercase(char ch) Waterford Institute of Technology, Java characters Lecture 8 15/33

Character class Example isdigit method public static void testisdigit() { Character ch = 'a'; boolean b = Character.isDigit(ch); if (b) { System.out.println("The character " + ch + " is a digit"); else { System.out.println("The character " + ch + " is not a digit"); Waterford Institute of Technology, Java characters Lecture 8 16/33

Java primitive char Arithmetic Because char has underlying integer representation May be used in arithmetic expressions Example: A convertible to 65 Example: B convertible to 66 Character arithmetic used in method isvalid static boolean isvalid2(string pin) { for (int i = 1; i < pin.length(); i++) { if ((pin.charat(i) pin.charat(i 1))!= 1) { return true; return false; Waterford Institute of Technology, Java characters Lecture 8 17/33

Number systems Used in computing Binary (base 2) 0,1 26 in binary: int binval = 0b11010; Decimal (base 10) 0,1,2,3,4,5,6,7,8,9 26 in decimal: int decval = 26; Hexadecimal (base 16) 0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F 26 in hex: int hexval = 0x1a Octal (base 8) sometimes used. Waterford Institute of Technology, Java characters Lecture 8 18/33

Character encoding Americal Standard Code for Information Exchange (ASCII) Represents text in devices such as computers & printers Character encoding scheme based on English alphabet Encodes 128 specified characters, 33 non-printable, 95 printable 0 to 9 a to z A to Z Some punctuation Control codes: example non-printable line feed, carriage return Blank space Waterford Institute of Technology, Java characters Lecture 8 19/33

Character encoding Unicode standard A superset of ASCII Presently represents more than 110,000 characters In excess of 100 scripts, for example: Left to right: Latin (English) Cyrillic (Russian) scripts Right to left: Arabic, Hebrew scripts Various symbols Implemented in: Many operating systems XML Java Several Unicode encodings exist In excess 80% www uses UTF-8 1 byte (8 bits) used for ASCII chars Waterford Institute of Technology, Java characters Lecture 8 20/33

Character encoding Examples char c1 = 0x41; char c2 = 65; //Both output the letter A System.out.println("char1 : " + char1); System.out.println("char2 : " + char2); Waterford Institute of Technology, Java characters Lecture 8 21/33

Randomness Generating random numbers Many libraries available to generate (pseudo) random numbers //Using Math.random() //Returns a double value with a positive sign, //greater than or equal to 0.0 and less than 1.0 : range [0 1). StdOut.print("Pseudo random number range [2,8] using Math library: "); double rval = Math.random(); int rval1 = (int)(rval 7 + 2); StdOut.print(rval1); //Typical output: Pseudo random number range [2,8] using Math library: 5 //Using java.util.random //Random nextint(int n) generates random number in range [0 n) StdOut.print("\nPseudo random number range [2,8] using java.util library: "); Random random = new Random(); int rval2 = random.nextint(7) + 2; StdOut.print(rval2); //Typical output: Pseudo random number range [2,8] using java.util library: 3 Waterford Institute of Technology, Java characters Lecture 8 22/33

Java primitive char Arithmetic Generate a random character public static char randomcharacter() { return (char) ('A' + (int) (Math.random() 26)); Test range public static boolean isdigit(char ch) { return (ch >= '0' && ch <= '9'); Waterford Institute of Technology, Java characters Lecture 8 23/33

Unicode Special Characters Table of Escape sequences An escape sequence comprises a character preceded by backslash. \n Newline (moves to the next line) \b Backspace \f Form feed (starts a new page) \r Return to the beginning of the current line \t Tab (moves horizontally to the next tab stop) \\ The backslash character itself \ The character (required only in character constants) \" The character " (required only in string constants) \ddd Character whose Unicode value octal number ddd Waterford Institute of Technology, Java characters Lecture 8 24/33

Java Operator Ternary Conditional operator?: Also known as ternary operator Can be thought of as if-then-else operator If condition true assign value1 else value2 int value1 = 1; int value2 = 2; int result; boolean somecondition = true; result = somecondition? value1 : value2; Waterford Institute of Technology, Java characters Lecture 8 25/33

Java Operator Ternary A method to return the absolute value of an integer: public static int absolutevalue(int a) { if (a < 0) { return a; return a; Alternative versions using ternary or conditional operator public static int absolutevalue(int a) { return a < 0? a : a; Waterford Institute of Technology, Java characters Lecture 8 26/33

Java Operator Ternary Waterford Institute of Technology, Java characters Lecture 8 27/33

Operator Precedence See the complete table listed in references Order of evaluation rules Highest precedence include parentheses and array access Multiplication & division before addition & subtraction Logical operators lower than multiplication Lowest precedences ternary followed by assignment If in doubt use parens Waterford Institute of Technology, Java characters Lecture 8 28/33

Summary String class comprises character array String objects immutable Character class primitive type can represent keyboard characters has underlying integer representation examined some of its methods Number systems decimal binary hexadcimal octal Character encoding ASCII Unicode, example UTF-8 Waterford Institute of Technology, Java characters Lecture 8 29/33

Summary String class One of most widely used classes Randomness Math and java.util packages how to generate random character Unicode special characters Conditional operator (?:) also known as ternary operator Precedence rules for order of evaluation Arrays zero index based comparison with ArrayList Boxing & Autoboxing Waterford Institute of Technology, Java characters Lecture 8 30/33

Referenced Material 1. Operator Precedence http://docs.oracle.com/javase/tutorial/java/ nutsandbolts/operators.html [Accessed 2014-05-17] 2. Characters http://docs.oracle.com/javase/tutorial/java/data/ characters.html [Accessed 2014-05-17] 3. ASCII http://en.wikipedia.org/wiki/ascii [Accessed 2015-02-19] Waterford Institute of Technology, Java characters Lecture 8 31/33

Referenced Material 4. Unicode http://en.wikipedia.org/wiki/utf-8 [Accessed 2015-02-19] 5. Binary to Decimal to Hexadecimal Converter http://www.mathsisfun.com/ binary-decimal-hexadecimal-converter.html [Accessed 2015-02-19] Waterford Institute of Technology, Java characters Lecture 8 32/33

Referenced Material 6. ASCII Table http://ascii.cl/ [Accessed 2015-02-19] 7. Immutable classes http://stackoverflow.com/questions/5124012/ examples-of-immutable-classes [Accessed 2015-02-23] Waterford Institute of Technology, Java characters Lecture 8 33/33