Java Strings Java, winter semester

Similar documents
Java Exceptions Java, winter semester

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

2.6 Error, exception and event handling

Introduction to Programming Using Java (98-388)

DOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS

Weiss Chapter 1 terminology (parenthesized numbers are page numbers)

Overloaded Methods. Sending Messages. Overloaded Constructors. Sending Parameters

A problem?... Exceptions. A problem?... A problem?... Suggested Reading: Bruce Eckel, Thinking in Java (Fourth Edition) Error Handling with Exceptions

Java. Error, Exception, and Event Handling. Error, exception and event handling. Error and exception handling in Java

SOFTWARE DEVELOPMENT 1. Strings and Enumerations 2018W A. Ferscha (Institute of Pervasive Computing, JKU Linz)

OOPs Concepts. 1. Data Hiding 2. Encapsulation 3. Abstraction 4. Is-A Relationship 5. Method Signature 6. Polymorphism 7. Constructors 8.

Index COPYRIGHTED MATERIAL

CS Internet programming Unit- I Part - A 1 Define Java. 2. What is a Class? 3. What is an Object? 4. What is an Instance?

CSC Java Programming, Fall Java Data Types and Control Constructs

ITI Introduction to Computing II

ITI Introduction to Computing II

1 Shyam sir JAVA Notes

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

CS260 Intro to Java & Android 03.Java Language Basics

CMSC 132: Object-Oriented Programming II

Exception-Handling Overview

THE CONCEPT OF OBJECT

National University. Faculty of Computer Since and Technology Object Oriented Programming

Brief Summary of Java

EXCEPTION HANDLING. Summer 2018

Exceptions. CSC207 Winter 2017

13: Error Handling with Exceptions. The basic philosophy of Java is that "badly formed code will not be run."

Fundamentals of Object Oriented Programming

COE318 Lecture Notes Week 10 (Nov 7, 2011)

Java Loose Ends. 11 December 2017 OSU CSE 1

CS-202 Introduction to Object Oriented Programming

CMSC 331 Second Midterm Exam

The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT

From C++ to Java. Duke CPS

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

15CS45 : OBJECT ORIENTED CONCEPTS

Programming II (CS300)

String is a Class; Quoted Text is an Object

Declarations and Access Control SCJP tips

חומר עזר לבחינה במבוא למדעי המחשב // Indicates whether some other object is "equal to" // this one. boolean equals(object other)

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

IS502052: Enterprise Systems Development Concepts Lab 1: Java Review

Contents. Figures. Tables. Examples. Foreword. Preface. 1 Basics of Java Programming 1. xix. xxi. xxiii. xxvii. xxix

CS 455 Midterm Exam 2 Fall 2016 [Bono] November 8, 2016

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

COMP1008 Exceptions. Runtime Error

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

Another IS-A Relationship

Java Identifiers, Data Types & Variables

F1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Type Hierarchy. Comp-303 : Programming Techniques Lecture 9. Alexandre Denault Computer Science McGill University Winter 2004

Array. Prepared By - Rifat Shahriyar

Types, Values and Variables (Chapter 4, JLS)

TeenCoder : Java Programming (ISBN )

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

Chapter 4 Defining Classes I

Pace University. Fundamental Concepts of CS121 1

Object-Oriented Programming

Objective Questions. BCA Part III Paper XIX (Java Programming) page 1 of 5

Exceptions - Example. Exceptions - Example

Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Java: introduction to object-oriented features

Exceptions and Libraries

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

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

6.Introducing Classes 9. Exceptions

Exceptions. Examples of code which shows the syntax and all that

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Class, Variable, Constructor, Object, Method Questions

BBM 102 Introduction to Programming II Spring Exceptions

More on Exception Handling

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

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

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

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

More on Exception Handling

CS 61B Discussion 5: Inheritance II Fall 2014

חומר עזר לבחינה מבוא למדעי המחשב

Final Exam Practice Questions

CO Java SE 8: Fundamentals

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Exception Handling. Chapter 11. Java By Abstraction Chapter 11. Outline What Are Exceptions?

Object Oriented Programming

Motivations. Chapter 12 Exceptions and File Input/Output

Points To Remember for SCJP

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING

CS313D: ADVANCED PROGRAMMING LANGUAGE

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

Sri Vidya College of Engineering & Technology Question Bank


Wrapper Classes double pi = new Double(3.14); 3 double pi = new Double("3.14"); 4... Zheng-Liang Lu Java Programming 290 / 321

Unit 3 INFORMATION HIDING & REUSABILITY. Interface:-Multiple Inheritance in Java-Extending interface, Wrapper Class, Auto Boxing

Agenda. Objects and classes Encapsulation and information hiding Documentation Packages

Chapter 9. Exception Handling. Copyright 2016 Pearson Inc. All rights reserved.

CSCI 261 Computer Science II

Transcription:

Java Strings 1

String instances of java.lang.string compiler works with them almost with primitive types String constants = instances of the String class immutable!!! for changes clases StringBuffer, StringBuilder operator + String concatenation if there is at least a single String in an expression -> all is converted to Strings and concatenated method tostring() defined in the class Object commonly overridden creates a new String 2

java.lang.string constructors String(); String(char[] value); String(byte[] bytes); String(byte[] bytes, String charsetname); String(String value); String(StringBuffer value); String(StringBuilder value); 3

java.lang.string methods int length(); char charat(int index); IndexOutOfBoundException boolean equals(object o); compares Strings == compares references String a = new String("hello"); String b = new String("hello"); System.out.println(a==b); // false System.out.println(a.equals(b)); //true 4

java.lang.string methods int compareto(string s); lexicographical comparison int comparetoignorecase(string s); int indexof(char c); int indexof(string s); return -1, if there is no such char or substring String substring(int beginindex); String substring(int beginindex, int endindex); String replacefirst(string regexp, String repl); String replaceall(string regexp, String repl); 5

Strings methods (cnt.) String join(charsequence delimiter, CharSequence... elements); since Java 8 methods can be called on String constants also String s;... if ("ahoj".equals(s)) {... 6

Java Wrapper types 7

Wrappers immutable Integer constructors deprecated since Java 9 Integer(int value) Integer(String s) methods int intvalue() static Integer valueof(int i) static int parseint(string s)... other wrapper types similarly 8

Java More about methods 9

Local variables definition anywhere in body visible in a block see the first lecture no initialization can be defined as final constants no other modifier can be used effectively final defined without final but the value is never changed after it is initialized 10

Method overloading several methods with the same name but different parameters different number and/or type public void draw(string s) {... public void draw(int i) {... public void draw(int i, double f) {... cannot overload just by a different return type 11

Recursive calls recursion a method calls itself public static long factorial(int n) { if (n == 1) return 1; return n * factorial(n-1); be aware about termination non terminated -> stack overrun a size of the stack can be set 12

Java Exceptions 13

Exceptions errors reporting and handling an exception represents an error state of a program exception = an instance of java.lang.throwable two subclasses java.lang.error and java.lang.exception specific exceptions children of the above two classes java.lang.error "unrecoverable" errors should not be caught e.g. OutOfMemoryError java.lang.exception recoverable errors should (has to) be caught e.g. ArrayIndexOutOfBounds 14

Exception handling statement try/catch/finally try {... // a block of code where an exception // can happen and we want to handle it catch (Exception1 e) { // handling of exceptions with the // Exception1 type and its subtypes catch (Exception2 e) { // handling of exceptions with the // Exception2 type and its subtypes finally { // executes always 15

Exception handling if the exception is not caught in a block where it occurs, it propagates to the upper block if the exception is not caught in a method, it propagates to the calling method it the exception reaches main() and it not caught, it terminates the virtual machine information about the exception is printed 16

try/catch/finally catch or finally can be omitted but both cannot be omitted 17

Extended try (since Java 7) interface AutoClosable and extended try example: class Foo implements AutoClosable {... public void close() { try ( Foo f1 = new Foo(); Foo f2 = new Foo() ) {... catch (...) {... finaly {... at the end of try (normally or by an exception), close() is always called on all the objects in the try declaration called in the reverse order than declared 18

Extended try both catch and finally can be omitted together try (Resource r = new Resource()) {... since Java 9, (effectively) final variables can be used in extended try final Resource resource1 = new Resource("res1"); Resource resource2 = new Resource("res2"); try (resource1; resource2) {... 19

multi catch (since Java 7) class Exception1 extends Exception { class Exception2 extends Exception { try { boolean test = true; if (test) { throw new Exception1(); else { throw new Exception2(); catch (Exception1 Exception2 e) {... 20

Exception declaration a method that can throw an exception must either catch the exception, or declare the exception via throws public void openfile() throws IOException {... it is not necessary to declare following exceptions children of java.lang.error children of java.lang.runtimeexception it extends java.lang.exception ex. NullPointerException, ArrayIndexOutOfBoundException 21

Throwing exceptions statement throw throws (generates) an exception "argument" a reference to Throwable throw new MojeVyjimka(); existing exceptions can be thrown but, commonly, own ones are used exceptions can be re-thrown try {... catch (Exception e) {... throw e; 22

Re-throwing (in Java 7) class Exception1 extends Exception { class Exception2 extends Exception { public static void main(string[] args) throws Exception1, Exception2 { try { boolean test = true; if (test) { throw new Exception1(); else { throw new Exception2(); catch (Exception e) { throw e; since Java 7 exceptions remember their types with Java 6, this cannot be compiled it would require throws Exception 23

java.lang.throwable has the field (private) typed String contains a detailed description of the exception method String getmessage() constructors Throwable() Throwable(String mesg) Throwable(String mesg, Throwable cause) // since 1.4 Throwable(Throwable cause) // since 1.4 methods void printstacktrace() 24

Own exceptions public class MyException extends Exception { public MyException() { super(); public MyException(String s) { super(s); public MyException(String s, Throwable t) { super(s, t); public MyException(Throwable t) { super(t); 25

Chains of exceptions... try {...... catch (Exception1 e) {... throw new Exception2(e);... throwing an exception as a reaction to another exception it is common reacting to a system exception by an own one 26

Suppressing exception in several cases an exception can suppress another one it is not chaining of exceptions! typically it can happen if an exception occurs in the finally block in the extended try block (Java 7) Throwable[] getsuppressed() method in Throwable returns an array of suppressed exceptions 27

JAVA Inner classes 28

Inner classes defined in the body of another class public class MyClass { class InnerClass { int i = 0; public int value() { return i; public void add() { InnerClass a = new InnerClass(); 29

Inner classes the inner class can return a reference to the outer class public class MyClass { class InnerClass { int i = 0; public int value() { return i; public InnerClass add() { return new InnerClass(); public static void main(string[] args){ MyClass p = new MyClass(); MyClass.InnerClass a = p.add(); 30

Hiding inner class inner class can be private or protected access to it via an interface public interface MyIface { int value(); public class MyClass { private class InnerClass implements MyIface { private i = 0; public int value() {return i; public MyIface add() {return new InnerClass();... public static void main(string[] args) { MyClass p = new MyClass(); MyIface a = p.add(); // error - MyClass.InnerClass a = p.add(); 31

Inner classes in methods an inner class can be defined in method or just a block of code visible just in the method (block) public class MyClass { public MyIface add() { class InnerClass implements MyIface { private i = 0; public int value() {return i; return new InnerClass(); public static void main(string[] args) { MyClass p = new MyClass(); MyIface a = p.add(); // error - MyClass.InnerClass a = p.add(); 32

Anonymous inner classes public class MyClass { public MyIface add() { return new MyIface() { private i = 0; public int value() {return i; ; public static void main(string[] args) { MyClass p = new MyClass(); MyIface a = p.add(); 33

Anonymous inner classes public class Wrap { private int v; public Wrap(int value) { v = value; public int value() { return v; public class MyClass { public Wrap wrap(int v) { return new Wrap(v) { public int value() { return super.value() * 10; ; public static void main(string[] args) { MyClass p = new MyClass(); Wrap a = p.wrap(5); 34

Anon. inner classes: initialization elements outside an anon. in. class necessary in the anon. in. class final without final compile-time error since Java 8 - effectively final is enough i.e. declared without the final modifier, but there are no changes to the particular element public class MyClass { public MyIface add(final int val) { return new MyIface() { private int i = val; till Java 7 final is public int value() {return i; necessary here ; since Java 8 final can be omitted as there are no changes to val 35

Anon. inner classes: initialization anon. inner classes cannot have a constructor because they are anonymous object initializer public class MyClass { public MyIface add(final int val) { return new MyIface() { private i; { if (val < 0) i = 0; else i = val; public int value() {return i; ; 36

Relation of inner and outer class the instance of an inner class can access all elements of the instance of the outer class interface Iterator { boolean hasnext(); Object next(); public class Array { private Object[] o; private int next = 0; public Array(int size) { o = new Object [size]; public void add(object x) { if (next < o.length) { o[next] = x; next++; // cont... 37

Relation of inner and outer class // cont... private class AIterator implements Iterator { int i = 0; public boolean hasnext() { return i < o.length; public Object next() { if (i < o.length) return o[i++]; else throw new NoNextElement(); public Iterator getiterator() { return new AIterator(); 38

Relation of inner and outer class a reference to the instance of the outer class OuterClassName.this previous example classes Array and AIterator the reference to the instance of Array from Array.AIterator Array.this 39

Relation of inner and outer class creation of the instance of an inner class outside of its outer class public class MyClass { class InnerClass { public static void main(string[] args) { MyClass p = new MyClass(); MyClass.InnerClass i = p.new InnerClass(); an instance of an inner class cannot be created without an instance of its outer class instances of an inner class always have a (hidden) reference to an instance of its outer class 40

Inner classes in inner classes from an inner class, an outer class on any level of nesting can be accessed class A { private void f() { class B { private void g() { class C { void h() { g(); f(); public class X { public static void main(string[] args) { A a = new A(); A.B b = a.new B(); A.B.C c = b.new C(); c.h(); 41

Inheriting from inner classes a reference to an instance of the outer class has to be explicitly passed class WithInner { class Inner { class InheritInner extends WithInner.Inner { InheritInner(WithInner wi) { wi.super(); // InheritInner() { // compile-time error public static void main(string[] argv) { WithInner wi = new WithInner(); InheritInner ii = new InheritInner(wi); 42

Nested classes defined with the keyword static do not have a reference to an instance of its outer class can have static elements inner classes cannot have static elements do not need an instance of the outer class they do not have the reference to it in fact, they are regular classes just placed in the namespace of the outer class public class MyClass { public static class NestedClass { public static void main(string[] args) { MyClass.NestedClass nc = new MyClass.InnerClass(); 43

Nested classes can be defined in an interface inner classes cannot be interface MyInterface { static class Nested { int a, b; public Nested() { void m(); 44

Inner classes and.class files inner (or nested) class own.class file OuterName$InnerName.class MyClass$InnerClass.class anonymous inner classes OuterName$SequentialNumber.class MyClass$1.class a nested class can have the main method launching: java OuterName$NestedName 45

Reasons for using inner classes hiding an implementation access to all elements of the outer class callbacks... 46

Java, winter Slides semester version 2017 J03.en.2017.01 This slides are licensed under a Creative Commons Attribution-NonCommercial 4.0 International License. 47