Java for Interfaces and Networks (DT3010, HT10)
|
|
- Sheryl Cunningham
- 5 years ago
- Views:
Transcription
1 Java for Interfaces and Networks (DT3010, HT10) More Basics: Classes, Exceptions, Garbage Collection, Interfaces, Packages Federico Pecora School of Science and Technology Örebro University Federico Pecora Java for Interfaces and Networks Lecture 2 1 / 31
2 Outline 1 Instance vs. Class variables and methods 2 Garbage collection 3 More on inheritance 4 Exceptions 5 Classes and interfaces 6 Packages Federico Pecora Java for Interfaces and Networks Lecture 2 2 / 31
3 Instance vs. Class variables and methods Outline 1 Instance vs. Class variables and methods 2 Garbage collection 3 More on inheritance 4 Exceptions 5 Classes and interfaces 6 Packages Federico Pecora Java for Interfaces and Networks Lecture 2 3 / 31
4 Instance vs. Class variables and methods Instance vs. Class variables Instance variable: not static as many copies as there are instantiated objects represents an attribute which all objects of the class have created when the object is instantiated (with new) Class variable: static one copy, regardless of the number of instantiated objects represents an attribute of the class of objects as a whole, not bound to a specific object created when class is loaded Federico Pecora Java for Interfaces and Networks Lecture 2 4 / 31
5 Instance vs. Class variables and methods Instance vs. Class methods Instance method: not static represents a capability of an instance of the class, all instances have this capaility has an implicit parameter this which is a reference to the object itself can access instance variables can access class variables Class method: static represents a capability associated to the class as a whole cannot access instance variables can access class variables Federico Pecora Java for Interfaces and Networks Lecture 2 5 / 31
6 Instance vs. Class variables and methods Constants: final Variables can be declared final, this makes them constants This also applies to method parameters final int test = 17; test = 4; // Compilation error! void amethod(final Circle circ) { circ = null; //Compilation error! } Similar to C++ s const attribute, but not as versatile class Foo { public: const int k; int fum; void amethod(const int* const p) const { int i; k = 17; //Error due to first const *p = 17; //Error due to second const p = &i; //Error due to third const fum = 17; //Error due to fourth const } }; Federico Pecora Java for Interfaces and Networks Lecture 2 6 / 31
7 Instance vs. Class variables and methods Example of static and final MyInteger.java 1 public class MyInteger { 2 private int number; 3 public void increment() { 4 ++number; 5 } 6 private static int numinstances = 0; 7 public final int instancenumber = numinstances++; 8 public static int convert(string s) { 9 return Integer.parseInt(s); 10 } 11 public static void main(string args) { 12 MyInteger i = new MyInteger(); 13 MyInteger.convert("13"); 14 i.convert("13"); 15 convert("13"); 16 i.increment(); 17 } //main 18 } //class MyInteger Federico Pecora Java for Interfaces and Networks Lecture 2 7 / 31
8 Instance vs. Class variables and methods Example: Complex numbers A class Complex, which describes complex numbers A class variable numinst which counts the number of instances Private instance variables re and im A simple instance method for printing A class method main Federico Pecora Java for Interfaces and Networks Lecture 2 8 / 31
9 Instance vs. Class variables and methods Example: Complex numbers Complex.java 1 public class Complex { 2 public static int numinst = 0; 3 private float re, im; 4 public Complex(float re, float im) { 5 this.re = re; 6 this.im = im; 7 Complex.numInst++; 8 } //Complex 9 public Complex() { this(0, 0); } 10 public void writenumber() { 11 System.out.print(re + " + " + im + "i" ); 12 } //writenumber 13 public static void main(string args) { 14 Complex carray = new Complex3; 15 for (int index = 0; index < 3; index++) { 16 carrayindex = new Complex(); 17 } //while 18 System.out.println(Complex.numInst + 19 " objects allocated."); 20 } //main 21 } //class Complex Federico Pecora Java for Interfaces and Networks Lecture 2 8 / 31
10 Instance vs. Class variables and methods Example: Complex numbers linux> javac Complex.java linux> java Complex 3 objects allocated. linux> Federico Pecora Java for Interfaces and Networks Lecture 2 8 / 31
11 Instance vs. Class variables and methods Example: Complex numbers linux> javac Complex.java linux> java Complex 3 objects allocated. linux> Problem: the instance counter only counts up... how do we make it decrement when an object ceases to exist? Federico Pecora Java for Interfaces and Networks Lecture 2 8 / 31
12 Garbage collection Outline 1 Instance vs. Class variables and methods 2 Garbage collection 3 More on inheritance 4 Exceptions 5 Classes and interfaces 6 Packages Federico Pecora Java for Interfaces and Networks Lecture 2 9 / 31
13 Garbage collection The finalize method Java allows to execute some operations upon object destruction These operations are specified in the finalize method (which overloads Object.finalize()) protected void finalize() throws Throwable { numinst--; super.finalize(); } //finalize Notice that it is not known when the JVM will actually call this method! Federico Pecora Java for Interfaces and Networks Lecture 2 10 / 31
14 Garbage collection The finalize method Java allows to execute some operations upon object destruction These operations are specified in the finalize method (which overloads Object.finalize()) protected void finalize() throws Throwable { try { //Your operations here } finally { super.finalize(); } } //finalize Notice that it is not known when the JVM will actually call this method! Federico Pecora Java for Interfaces and Networks Lecture 2 10 / 31
15 Garbage collection Example: Complex numbers (new main) Complex.java 1 public static void main(string args) { 2 Complex carray = new Complex3; 3 for (int index = 0; index < 3; index++) { 4 carrayindex = new Complex(); 5 } //while 6 { 7 Complex restrictedscope = new Complex(); 8 System.out.println(numInst + " in two scopes."); 9 } 10 System.out.println(numInst + " in one scope."); 11 } //main linux> javac Complex.java linux> java Complex 4 in two scopes. 4 in one scope. linux>... what is happening here? Federico Pecora Java for Interfaces and Networks Lecture 2 11 / 31
16 Garbage collection Example: Complex numbers (new main) Data from a loop of allocations of a Complex variable Federico Pecora Java for Interfaces and Networks Lecture 2 12 / 31
17 Garbage collection Garbage collection The finalize() method is called when deemed appropriate by the JVM this can occur at any time, also in the middle of a print statement Garbage collection is done manually in C/C++ (with free()/delete()) this is a notoriously difficult task Fully automatic in Java, no need to worry about memory leaks BUT, remember that you have no control on when garbage collection occurs Federico Pecora Java for Interfaces and Networks Lecture 2 13 / 31
18 More on inheritance Outline 1 Instance vs. Class variables and methods 2 Garbage collection 3 More on inheritance 4 Exceptions 5 Classes and interfaces 6 Packages Federico Pecora Java for Interfaces and Networks Lecture 2 14 / 31
19 More on inheritance Inheritance in Java A class can inherit only a single class in java multiple inheritance is not supported However, interfaces offer a way to do multiple inheritance It is also possible to block inheritance a class designer can choose to specify his/her class as final Federico Pecora Java for Interfaces and Networks Lecture 2 15 / 31
20 More on inheritance Final classes A class declared final cannot be extended java.lang.string is such a class No one can subclass String and introduce anomalous behavior If a class is final, all its methods are implicitly final the method is guaranteed not to be overridden This is useful to enforce immutability If you must use final classes (and methods), document why Federico Pecora Java for Interfaces and Networks Lecture 2 16 / 31
21 More on inheritance The Object class All classes implicitly extend the Object class Object is the root of the class hierarchy All objects, including arrays, implement the methods of this class Federico Pecora Java for Interfaces and Networks Lecture 2 17 / 31
22 More on inheritance Access level modifiers Determine where a particular field or method are accessible Modifier Class Package Subclass World public Y Y Y Y protected Y Y Y N Y Y N N private Y N N N Use the most restrictive access level that makes sense for a particular member Use private unless you have a good reason not to; avoid public variables except for constants NB: the absence of a modifier is not equivalent to public! Federico Pecora Java for Interfaces and Networks Lecture 2 18 / 31
23 Exceptions Outline 1 Instance vs. Class variables and methods 2 Garbage collection 3 More on inheritance 4 Exceptions 5 Classes and interfaces 6 Packages Federico Pecora Java for Interfaces and Networks Lecture 2 19 / 31
24 Exceptions Error handling in C/C++ Error handling in C/C++ mostly dependends on programmer e.g., writing code to check return values unsafe.c 1 #include <stdio.h> 2 int main(int argc, char* argv) { 3 printf("hello, world!\n"); 4 return 0; 5 } /* main */ Federico Pecora Java for Interfaces and Networks Lecture 2 20 / 31
25 Exceptions Error handling in C/C++ Error handling in C/C++ mostly dependends on programmer e.g., writing code to check return values safer.c 1 #include <stdio.h> 2 #include <stdlib.h> 3 int main(int argc, char* argv) { 4 if (printf("hello, world!\n")!= 14) { 5 fprintf(stderr, "Failure writing text!\n"); 6 return EXIT_FAILURE; 7 } 8 if (fclose(stdout)!= 0) { 9 fprintf(stderr, "Failure writing file!\n"); 10 return EXIT_FAILURE; 11 } 12 return 0; 13 } /* main */ Federico Pecora Java for Interfaces and Networks Lecture 2 20 / 31
26 Exceptions Exceptions in Java Java throws an exception when something is wrong Exceptions can be caught, potentially in a completely different part of the code from where they are thrown Some exceptions must be caught, others don t have to (unchecked exceptions) most exceptions you will ever write should not be unchecked An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions Designing your own exceptions consists in deciding how to react to the disruption Federico Pecora Java for Interfaces and Networks Lecture 2 21 / 31
27 Exceptions Exceptions in Java: example 1 private void drinkcoffee() { 2 //Sluuuurp... 3 } 4 private void eatdinner() { 5 eatappetizer(); 6 eatmaincourse(); 7 eatdessert(); 8 drinkcoffee(); 9 } 10 public static void main(string args) { 11 Dinner d = new Dinner(); 12 d.eatdinner(); 13 System.out.println("Eating done"); 14 System.out.println("(hopefully...)"); 15 } //main What if something goes wrong in the methods called by eatdinner()? Federico Pecora Java for Interfaces and Networks Lecture 2 22 / 31
28 Exceptions Exceptions in Java: example 1 private boolean drinkcoffee() { 2 if (coffeepot == null) return false; 3 else { /* Sluuurp... */ return true; } 4 } 5 private boolean eatdinner() { 6 if (!eatappetizer()) return false; 7 if (!eatmaincourse()) return false; 8 if (!eatdessert()) return false; 9 if (!drinkcoffee()) return false; 10 return true; 11 } 12 public static void main(string args) { 13 Dinner d = new Dinner(); 14 if (!d.eatdinner()) System.out.println("Error!"); 15 } //main Notice that error handling code is obfuscating the orignial implementation! Federico Pecora Java for Interfaces and Networks Lecture 2 22 / 31
29 Exceptions Exceptions in Java: example 1 private void drinkcoffee() throws NoCoffeePotException { 2 if (coffeepot == null) throw new NoCoffeePotException(); 3 else { /* Sluuurp... */ } 4 } 5 private void eatdinner() throws NoCoffeePotException { 6 eatappetizer(); 7 eatmaincourse(); 8 eatdessert(); 9 drinkcoffee(); 10 } 11 public static void main(string args) { 12 Dinner d = new Dinner(); 13 try { d.eatdinner(); } 14 catch (NoCoffeePotException e) { 15 System.out.println("No coffee pot!"); 16 } 17 catch (Exception e) { System.out.println("Error!"); } 18 } //main Federico Pecora Java for Interfaces and Networks Lecture 2 22 / 31
30 Exceptions Exceptions in Java: example 1 private void drinkcoffee() throws NoCoffeePotException { 2 if (coffeepot == null) throw new NoCoffeePotException(); 3 else { /* Sluuurp... */ } 4 } 5 private void eatdinner() throws NoCoffeePotException { 6 eatappetizer(); 7 eatmaincourse(); 8 eatdessert(); 9 drinkcoffee(); 10 } 11 public static void main(string args) { 12 Dinner d = new Dinner(); 13 try { d.eatdinner(); } 14 catch (NoCoffeePotException e) { 15 System.out.println("No coffee pot!"); 16 } 17 catch (Exception e) { System.out.println("Error!"); } 18 } //main Federico Pecora Java for Interfaces and Networks Lecture 2 22 / 31
31 Exceptions Throwable objects NoCoffeePotException.java class NoCoffeePotException extends Exception { //Body can be empty... } Federico Pecora Java for Interfaces and Networks Lecture 2 23 / 31
32 Exceptions Throwable objects Unchecked exceptions Error: thrown by the JVM when a dynamic linking failure or other hard failure occurs (e.g., ClassFormatError, OutOfMemoryError) RunTimeException: reserved for exceptions that indicate incorrect use of an API (e.g., ArithmeticException, NullPointerException) Checked exceptions Exception: normal problems, not serious system failures (e.g., your own exceptions, IllegalAccessException, NegativeArraySizeException) Federico Pecora Java for Interfaces and Networks Lecture 2 23 / 31
33 Exceptions Extending the Exception class: example Maintain an object num of type Number Loop over keyboard input At each iteration read an integer If odd: add to num If even: divide num by read integer handle case when given number is zero with exception thrown by Number If input = 99: exit Federico Pecora Java for Interfaces and Networks Lecture 2 24 / 31
34 Exceptions Extending the Exception class: example Number.java 1 import java.io.bufferedreader; 2 import java.io.inputstreamreader; 3 class Number { 4 private int num = 0; 5 public Number(int n) { 6 this.num = n; 7 } //Number 8 public void add(int n) { 9 this.num += n; 10 } //add 11 public void divide(int n) throws DivZeroException { 12 if (n == 0) throw new DivZeroException(); 13 this.num = this.num / n; 14 } // divide 15 public int value() { return this.num; } 16 //Continues... Federico Pecora Java for Interfaces and Networks Lecture 2 24 / 31
35 Exceptions Extending the Exception class: example Number.java (cont) 17 public static void main(string args) { 18 BufferedReader kbd_reader = /*... */ 19 int n = 1; String buf; Number num = new Number(14); 20 System.out.println("Starting with: " + num.value()); 21 try { while (n!= 99) { 22 System.out.print("Input a number (99 to quit): "); 23 buf = kbd_reader.readline(); 24 n = Integer.parseInt(buf); 25 if (n % 2 == 1) num.add(n); 26 else try { num.divide(n); } 27 catch (DivZeroException e) { 28 System.out.println("Division by 0 skipped."); 29 } 30 System.out.println("Number is: " + num.value()); 31 } } //while - try 32 catch (Exception e) { System.out.println("Error!"); } 33 } //main 34 } //class Number Federico Pecora Java for Interfaces and Networks Lecture 2 24 / 31
36 Exceptions Extending the Exception class: example Number.java (cont) 17 public static void main(string args) { 18 BufferedReader kbd_reader = /*... */ 19 int n = 1; String buf; Number num = new Number(14); 20 System.out.println("Starting with: " + num.value()); 21 try { while (n!= 99) { 22 System.out.print("Input a number (99 to quit): "); 23 buf = kbd_reader.readline(); 24 n = Integer.parseInt(buf); 25 if (n % 2 == 1) num.add(n); 26 else try { num.divide(n); } 27 catch (DivZeroException e) { 28 System.out.println("Division by 0 skipped."); 29 } 30 System.out.println("Number is: " + num.value()); 31 } } //while - try 32 catch (Exception e) { System.out.println("Error!"); } 33 } //main 34 } //class Number Federico Pecora Java for Interfaces and Networks Lecture 2 24 / 31
37 Exceptions Extending the Exception class: example DivZeroException.java 1 class DivZeroException extends Exception { 2 /* 3 Can embed information into 4 exception object... 5 See Java API for methods to override 6 */ 7 } Your exception object can have information mebedded into it The Exception class allows you to specify a String detail message Message can be retrieved by invoking getmessage() on the exception object Federico Pecora Java for Interfaces and Networks Lecture 2 24 / 31
38 Exceptions Extending the Exception class: example You can give programmers that use the exception object the possibility to specify the detail message MyException.java 1 class MyExecption extends Exception { 2 MyExecption() { } 3 MyExecption(String msg) { super(msg); } 4 } Federico Pecora Java for Interfaces and Networks Lecture 2 24 / 31
39 Classes and interfaces Outline 1 Instance vs. Class variables and methods 2 Garbage collection 3 More on inheritance 4 Exceptions 5 Classes and interfaces 6 Packages Federico Pecora Java for Interfaces and Networks Lecture 2 25 / 31
40 Classes and interfaces Interfaces in Java An interface is a specification, it does not implement anything Example: an object that implements this interface should have a function foo (defined by its signature) A class can implement an interface A class can implement multiple interfaces! Interface an abstract class that does not implement anything Rationale: an interface should be use to implement many, potentially very different classes Federico Pecora Java for Interfaces and Networks Lecture 2 26 / 31
41 Classes and interfaces Interfaces: example An interface called Function which specifies how to write math functions... namely, the need to specify the function, its derivative and its integral function... and supports the development of an integral solver Federico Pecora Java for Interfaces and Networks Lecture 2 27 / 31
42 Classes and interfaces Interfaces: example Function.java 1 public interface Function { 2 public float f(float x); 3 public float derivative(float x); 4 public float integralfunction(float x); 5 } // interface Function Federico Pecora Java for Interfaces and Networks Lecture 2 27 / 31
43 Classes and interfaces Interfaces: example Now, let s implement the function f (x) = sin(x) Sine.java 1 public class Sine implements Function { 2 public float f(float x) { 3 return (float)math.sin(x); 4 } 5 public float derivative(float x) { 6 return (float)math.cos(x); 7 } 8 public float integralfunction(float x) { 9 return -(float)math.cos(x); 10 } 11 } //class Sine Federico Pecora Java for Interfaces and Networks Lecture 2 27 / 31
44 Classes and interfaces Interfaces: example Now, let s implement the function f (x) = x x Polynomial.java 1 public class Polynomial implements Function { 2 public float f(float x) { 3 return x*x - x + 3.0f; 4 } 5 public float derivative(float x) { 6 return 2.0f*x - 1.0f; 7 } 8 public float integralfunction(float x) { 9 return x*x*x/3.0f - x*x/2.0f + 3.0f*x; 10 } 11 } //Polynomial Federico Pecora Java for Interfaces and Networks Lecture 2 27 / 31
45 Classes and interfaces Interfaces: example Now, let s implement the integral solver, i.e., b a f (x)dx = f (x)dx b f (x)dx a and a test class Integral.java 1 public class Integral { 2 public float integrate(function fn, float a, float b) { 3 return fn.integralfunction(b) - 4 fn.integralfunction(a); 5 } 6 } // Integral NB: interfaces are similar to function pointers in C! Federico Pecora Java for Interfaces and Networks Lecture 2 27 / 31
46 Classes and interfaces Interfaces: example Finally, a test class IntegralTest.java 1 import java.io.*; 2 public class IntegralTest { 3 public static void main(string args) { 4 Sine sin = new Sine(); 5 Polynomial poly = new Polynomial(); 6 Integral solver = new Integral(); 7 System.out.println("Integral of sin(x): " + 8 solver.integral(sin, 1.0f, 3.0f)); 9 System.out.println("Integral of x - x^2 + 3: " + 10 solver.integral(poly, 1.0f, 3.0f)); 11 } // main 12 } //IntegralTest Federico Pecora Java for Interfaces and Networks Lecture 2 27 / 31
47 Classes and interfaces Interfaces vs. abstract classes An interface implementation may be added to any existing third party class a third party class must be rewritten to extend only from the abstract class Interfaces are used to describe the peripheral abilities of a class, not its central identity a Book which implements the Stackable interface (which is not the central goal of a book) An abstract class defines the core identity of its descendants a Dog which defines the basic aspects of Dalmations, Poodles, GermanShepherds, etc. Federico Pecora Java for Interfaces and Networks Lecture 2 28 / 31
48 Packages Outline 1 Instance vs. Class variables and methods 2 Garbage collection 3 More on inheritance 4 Exceptions 5 Classes and interfaces 6 Packages Federico Pecora Java for Interfaces and Networks Lecture 2 29 / 31
49 Packages Packages in Java Provide a means to modularize applications using directory structure Group classes, variables, properties, etc. Built-in examples java.io input/output e.g., java.io.bufferedreader java.lang basic elements of the java language e.g., java.lang.object (imported automatically) java.awt graphical user interfaces (old, not very good) javax.swing graphical user interfaces (new, good) If you import apackage.*; then you can access apackage.aclass just by writing AClass Federico Pecora Java for Interfaces and Networks Lecture 2 30 / 31
50 Packages More Basics: Classes, Exceptions, Garbage Collection, Interfaces, Packages Thank you! Federico Pecora Java for Interfaces and Networks Lecture 2 31 / 31
BBM 102 Introduction to Programming II Spring Exceptions
BBM 102 Introduction to Programming II Spring 2018 Exceptions 1 Today What is an exception? What is exception handling? Keywords of exception handling try catch finally Throwing exceptions throw Custom
More information1 Shyam sir JAVA Notes
1 Shyam sir JAVA Notes 1. What is the most important feature of Java? Java is a platform independent language. 2. What do you mean by platform independence? Platform independence means that we can write
More informationFull file at Chapter 2 - Inheritance and Exception Handling
Chapter 2 - Inheritance and Exception Handling TRUE/FALSE 1. The superclass inherits all its properties from the subclass. ANS: F PTS: 1 REF: 76 2. Private members of a superclass can be accessed by a
More informationExceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages
References Exceptions "Handling Errors with Exceptions", Java tutorial http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html CSE 413, Autumn 2005 Programming Languages http://www.cs.washington.edu/education/courses/413/05au/
More informationJava Primer. CITS2200 Data Structures and Algorithms. Topic 2
CITS2200 Data Structures and Algorithms Topic 2 Java Primer Review of Java basics Primitive vs Reference Types Classes and Objects Class Hierarchies Interfaces Exceptions Reading: Lambert and Osborne,
More informationA Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1
A Third Look At Java Chapter Seventeen Modern Programming Languages, 2nd ed. 1 A Little Demo public class Test { public static void main(string[] args) { int i = Integer.parseInt(args[0]); int j = Integer.parseInt(args[1]);
More informationAP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS
AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS PAUL L. BAILEY Abstract. This documents amalgamates various descriptions found on the internet, mostly from Oracle or Wikipedia. Very little of this
More informationExceptions. CSE 142, Summer 2002 Computer Programming 1.
Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ 12-Aug-2002 cse142-19-exceptions 2002 University of Washington 1 Reading Readings and References»
More informationExceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.
Readings and References Exceptions CSE 142, Summer 2002 Computer Programming 1 http://www.cs.washington.edu/education/courses/142/02su/ Reading» Chapter 18, An Introduction to Programming and Object Oriented
More informationJava for Interfaces and Networks (DT3010, HT11)
Java for Interfaces and Networks (DT3010, HT11) Introduction Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks Lecture
More informationBBM 102 Introduction to Programming II Spring 2017
BBM 102 Introduction to Programming II Spring 2017 Exceptions Instructors: Ayça Tarhan, Fuat Akal, Gönenç Ercan, Vahid Garousi Today What is an exception? What is exception handling? Keywords of exception
More informationOutline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring
Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,
More informationDOWNLOAD PDF CORE JAVA APTITUDE QUESTIONS AND ANSWERS
Chapter 1 : Chapter-wise Java Multiple Choice Questions and Answers Interview MCQs Java Programming questions and answers with explanation for interview, competitive examination and entrance test. Fully
More informationObject oriented programming. Instructor: Masoud Asghari Web page: Ch: 7
Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 7 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Essential
More informationChapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University
Chapter 8 Exception Handling CS 180 Sunil Prabhakar Department of Computer Science Purdue University Clarifications Auto cast from char to String does not happen. Cast between int and char happens automatically.
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationCOE318 Lecture Notes Week 10 (Nov 7, 2011)
COE318 Software Systems Lecture Notes: Week 10 1 of 5 COE318 Lecture Notes Week 10 (Nov 7, 2011) Topics More about exceptions References Head First Java: Chapter 11 (Risky Behavior) The Java Tutorial:
More informationLecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166
Lecture 20 Java Exceptional Event Handling Dr. Martin O Connor CA166 www.computing.dcu.ie/~moconnor Topics What is an Exception? Exception Handler Catch or Specify Requirement Three Kinds of Exceptions
More informationFundamentals of Object Oriented Programming
INDIAN INSTITUTE OF TECHNOLOGY ROORKEE Fundamentals of Object Oriented Programming CSN- 103 Dr. R. Balasubramanian Associate Professor Department of Computer Science and Engineering Indian Institute of
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationChapter 12 Exception Handling
Chapter 12 Exception Handling 1 Motivations Goal: Robust code. When a program runs into a runtime error, the program terminates abnormally. How can you handle the runtime error so that the program can
More information엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED
엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED Outline - Interfaces - An Instrument interface - Multiple Inheritance
More informationData Structures. 02 Exception Handling
David Drohan Data Structures 02 Exception Handling JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN 0132162709 2012 Pearson Education, Inc., Upper Saddle River, NJ.
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Fall 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions and
More informationException Handling CSCI 201 Principles of Software Development
Exception Handling CSCI 201 Principles of Software Development Jeffrey Miller, Ph.D. jeffrey.miller@usc.edu Outline Program USC CSCI 201L 2/19 Exception Handling An exception is an indication of a problem
More informationCSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige
CSC 308 2.0 System Development with Java Exception Handling Department of Statistics and Computer Science 1 2 Errors Errors can be categorized as several ways; Syntax Errors Logical Errors Runtime Errors
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationECE Fall 20l2, Second Exam
ECE 30862 Fall 20l2, Second Exam DO NOT START WORKING ON THIS UNTIL TOLD TO DO SO. LEAVE IT ON THE DESK. You have until 12:20 to take this exam. Your exam should have 16 pages total (including this cover
More informationException-Handling Overview
م.عبد الغني أبوجبل Exception Handling No matter how good a programmer you are, you cannot control everything. Things can go wrong. Very wrong. When you write a risky method, you need code to handle the
More informationCOMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed
1 1 COMP200 EXCEPTIONS OOP using Java, based on slides by Shayan Javed Exception Handling 2 3 Errors Syntax Errors Logic Errors Runtime Errors 4 Syntax Errors Arise because language rules weren t followed.
More informationJava for Interfaces and Networks (DT3029)
Java for Interfaces and Networks (DT3029) Lecture 1 Introduction and Basics Federico Pecora federico.pecora@oru.se Center for Applied Autonomous Sensor Systems (AASS) Örebro University, Sweden Image source:
More informationITI Introduction to Computing II
ITI 1121. Introduction to Computing II Marcel Turcotte School of Electrical Engineering and Computer Science Version of February 23, 2013 Abstract Handling errors Declaring, creating and handling exceptions
More informationException Handling. Sometimes when the computer tries to execute a statement something goes wrong:
Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception Ariel Shamir 1 Run-time Errors Sometimes when the computer
More informationException Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:
Exception Handling Run-time errors The exception concept Throwing exceptions Handling exceptions Declaring exceptions Creating your own exception 22 November 2007 Ariel Shamir 1 Run-time Errors Sometimes
More informationExceptions. What exceptional things might our programs run in to?
Exceptions What exceptional things might our programs run in to? Exceptions do occur Whenever we deal with programs, we deal with computers and users. Whenever we deal with computers, we know things don
More informationCS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)
CS/B.TECH/CSE(New)/SEM-5/CS-504D/2013-14 2013 OBJECT ORIENTED PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give their answers
More informationTypes, Values and Variables (Chapter 4, JLS)
Lecture Notes CS 141 Winter 2005 Craig A. Rich Types, Values and Variables (Chapter 4, JLS) Primitive Types Values Representation boolean {false, true} 1-bit (possibly padded to 1 byte) Numeric Types Integral
More informationECE 462 Fall 2011, Third Exam
ECE 462 Fall 2011, Third Exam DO NOT START WORKING ON THIS UNTIL TOLD TO DO SO. You have until 9:20 to take this exam. Your exam should have 12 pages total (including this cover sheet). Please let Prof.
More informationProgramming II (CS300)
1 Programming II (CS300) Chapter 04: Exception Handling MOUNA KACEM mouna@cs.wisc.edu Spring 2018 Creating Classes 2 Introduction Exception Handling Common Exceptions Exceptions with Methods Assertions
More informationAn overview of Java, Data types and variables
An overview of Java, Data types and variables Lecture 2 from (UNIT IV) Prepared by Mrs. K.M. Sanghavi 1 2 Hello World // HelloWorld.java: Hello World program import java.lang.*; class HelloWorld { public
More informationSelected Java Topics
Selected Java Topics Introduction Basic Types, Objects and Pointers Modifiers Abstract Classes and Interfaces Exceptions and Runtime Exceptions Static Variables and Static Methods Type Safe Constants Swings
More informationF1 A Java program. Ch 1 in PPIJ. Introduction to the course. The computer and its workings The algorithm concept
F1 A Java program Ch 1 in PPIJ Introduction to the course The computer and its workings The algorithm concept The structure of a Java program Classes and methods Variables Program statements Comments Naming
More informationLecture 19 Programming Exceptions CSE11 Fall 2013
Lecture 19 Programming Exceptions CSE11 Fall 2013 When Things go Wrong We've seen a number of run time errors Array Index out of Bounds e.g., Exception in thread "main" java.lang.arrayindexoutofboundsexception:
More information20 Most Important Java Programming Interview Questions. Powered by
20 Most Important Java Programming Interview Questions Powered by 1. What's the difference between an interface and an abstract class? An abstract class is a class that is only partially implemented by
More informationDeclarations and Access Control SCJP tips
Declarations and Access Control www.techfaq360.com SCJP tips Write code that declares, constructs, and initializes arrays of any base type using any of the permitted forms both for declaration and for
More informationInheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship
Inheritance 1..n Unidirectional association Inheritance ("extends") Use relationship Implementation ("implements") What is inherited public, protected methods public, proteced attributes What is not inherited
More informationAbout This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions
Exceptions Revised 24-Jan-05 CMPUT 115 - Lecture 4 Department of Computing Science University of Alberta About This Lecture In this lecture we will learn how to use Java Exceptions to handle unusual program
More informationMore on Exception Handling
Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationC16b: Exception Handling
CISC 3120 C16b: Exception Handling Hui Chen Department of Computer & Information Science CUNY Brooklyn College 3/28/2018 CUNY Brooklyn College 1 Outline Exceptions Catch and handle exceptions (try/catch)
More informationProgram Correctness and Efficiency. Chapter 2
Program Correctness and Efficiency Chapter 2 Chapter Objectives To understand the differences between the three categories of program errors To understand the effect of an uncaught exception and why you
More informationHomework 4. Any questions?
CSE333 SECTION 8 Homework 4 Any questions? STL Standard Template Library Has many pre-build container classes STL containers store by value, not by reference Should try to use this as much as possible
More informationthis keyword (1). this with constructor (2). cisc3120 design and implementation of software applications I spring 2015 lecture # I.
topics: introduction to java, part 4 this references exception handling comparing objects vectors utility classes cisc3120 design and implementation of software applications I spring 2015 lecture # I.4
More informationCS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling
CS115 Pi Principles i of fcomputer Science Chapter 17 Exception Handling Prof. Joe X. Zhou Department of Computer Science CS115 ExceptionHandling.1 Objectives in Exception Handling To know what is exception
More informationJava in 21 minutes. Hello world. hello world. exceptions. basic data types. constructors. classes & objects I/O. program structure.
Java in 21 minutes hello world basic data types classes & objects program structure constructors garbage collection I/O exceptions Strings Hello world import java.io.*; public class hello { public static
More informationCS 11 java track: lecture 3
CS 11 java track: lecture 3 This week: documentation (javadoc) exception handling more on object-oriented programming (OOP) inheritance and polymorphism abstract classes and interfaces graphical user interfaces
More informationIndex COPYRIGHTED MATERIAL
Index COPYRIGHTED MATERIAL Note to the Reader: Throughout this index boldfaced page numbers indicate primary discussions of a topic. Italicized page numbers indicate illustrations. A abstract classes
More informationCSC Java Programming, Fall Java Data Types and Control Constructs
CSC 243 - Java Programming, Fall 2016 Java Data Types and Control Constructs Java Types In general, a type is collection of possible values Main categories of Java types: Primitive/built-in Object/Reference
More informationLecture 2, September 4
Lecture 2, September 4 Intro to C/C++ Instructor: Prashant Shenoy, TA: Shashi Singh 1 Introduction C++ is an object-oriented language and is one of the most frequently used languages for development due
More informationJava Errors and Exceptions. Because Murphy s Law never fails
Java Errors and Exceptions Because Murphy s Law never fails 1 Java is the most distressing thing to hit computing since MS-DOS. Alan Kay 2 Corresponding Book Sections Pearson Custom Computer Science: Chapter
More informationCS 11 java track: lecture 1
CS 11 java track: lecture 1 Administrivia need a CS cluster account http://www.cs.caltech.edu/ cgi-bin/sysadmin/account_request.cgi need to know UNIX www.its.caltech.edu/its/facilities/labsclusters/ unix/unixtutorial.shtml
More informationF I N A L E X A M I N A T I O N
Faculty Of Computer Studies M257 Putting Java to Work F I N A L E X A M I N A T I O N Number of Exam Pages: (including this cover sheet( Spring 2011 April 4, 2011 ( 5 ) Time Allowed: ( 1.5 ) Hours Student
More informationCS260 Intro to Java & Android 03.Java Language Basics
03.Java Language Basics http://www.tutorialspoint.com/java/index.htm CS260 - Intro to Java & Android 1 What is the distinction between fields and variables? Java has the following kinds of variables: Instance
More informationCSCI 261 Computer Science II
CSCI 261 Computer Science II Department of Mathematics and Computer Science Lecture 2 Exception Handling New Topic: Exceptions in Java You should now be familiar with: Advanced object-oriented design -
More informationPractice Questions for Final Exam: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course
: Advanced Java Concepts + Additional Questions from Earlier Parts of the Course 1. Given the following hierarchy: class Alpha {... class Beta extends Alpha {... class Gamma extends Beta {... In what order
More informationCOMP1008 Exceptions. Runtime Error
Runtime Error COMP1008 Exceptions Unexpected error that terminates a program. Undesirable Not detectable by compiler. Caused by: Errors in the program logic. Unexpected failure of services E.g., file server
More informationExceptions and I/O: sections Introductory Programming. Errors in programs. Exceptions
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationIntroductory Programming Exceptions and I/O: sections
Introductory Programming Exceptions and I/O: sections 80 83 Anne Haxthausen a IMM, DTU 1 Exceptions (section 80) 2 Input and output (I/O) (sections 81-83) a Parts of this material are inspired by/originate
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationJava Basic Syntax. Java vs C++ Wojciech Frohmberg / OOP Laboratory. Poznan University of Technology
Java vs C++ 1 1 Department of Computer Science Poznan University of Technology 2012.10.07 / OOP Laboratory Outline 1 2 3 Outline 1 2 3 Outline 1 2 3 Tabular comparizon C++ Java Paradigm Procedural/Object-oriented
More informationInput-Output and Exception Handling
Software and Programming I Input-Output and Exception Handling Roman Kontchakov / Carsten Fuhs Birkbeck, University of London Outline Reading and writing text files Exceptions The try block catch and finally
More informationCrash Course in Java. Why Java? Java notes for C++ programmers. Network Programming in Java is very different than in C/C++
Crash Course in Java Netprog: Java Intro 1 Why Java? Network Programming in Java is very different than in C/C++ much more language support error handling no pointers! (garbage collection) Threads are
More informationG52CPP C++ Programming Lecture 3. Dr Jason Atkin
G52CPP C++ Programming Lecture 3 Dr Jason Atkin E-Mail: jaa@cs.nott.ac.uk 1 Revision so far C/C++ designed for speed, Java for catching errors Java hides a lot of the details (so can C++) Much of C, C++
More informationIntroduction to Java
Introduction to Java Module 1: Getting started, Java Basics 22/01/2010 Prepared by Chris Panayiotou for EPL 233 1 Lab Objectives o Objective: Learn how to write, compile and execute HelloWorld.java Learn
More informationExceptions Handling Errors using Exceptions
Java Programming in Java Exceptions Handling Errors using Exceptions Exceptions Exception = Exceptional Event Exceptions are: objects, derived from java.lang.throwable. Throwable Objects: Errors (Java
More informationCOT 3530: Data Structures. Giri Narasimhan. ECS 389; Phone: x3748
COT 3530: Data Structures Giri Narasimhan ECS 389; Phone: x3748 giri@cs.fiu.edu www.cs.fiu.edu/~giri/teach/3530spring04.html Evaluation Midterm & Final Exams Programming Assignments Class Participation
More informationMore on Exception Handling
Chapter 18 More on Exception Handling Lecture slides for: Java Actually: A Comprehensive Primer in Programming Khalid Azim Mughal, Torill Hamre, Rolf W. Rasmussen Cengage Learning, 2008. ISBN: 978-1-844480-933-2
More informationCSC207H: Software Design. Exceptions. CSC207 Winter 2018
Exceptions CSC207 Winter 2018 1 What are exceptions? Exceptions represent exceptional conditions: unusual, strange, disturbing. These conditions deserve exceptional treatment: not the usual go-tothe-next-step,
More informationOutline. Overview. Control statements. Classes and methods. history and advantage how to: program, compile and execute 8 data types 3 types of errors
Outline Overview history and advantage how to: program, compile and execute 8 data types 3 types of errors Control statements Selection and repetition statements Classes and methods methods... 2 Oak A
More informationInternal Classes and Exceptions
Internal Classes and Exceptions Object Orientated Programming in Java Benjamin Kenwright Outline Exceptions and Internal Classes Why exception handling makes your code more manageable and reliable Today
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationChapter 14. Exception Handling and Event Handling ISBN
Chapter 14 Exception Handling and Event Handling ISBN 0-321-49362-1 Chapter 14 Topics Introduction to Exception Handling Exception Handling in Ada Exception Handling in C++ Exception Handling in Java Introduction
More informationGraphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub
Lebanese University Faculty of Science Computer Science BS Degree Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub 2 Crash Course in JAVA Classes A Java
More informationInheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.
Inheritance Inheritance is the act of deriving a new class from an existing one. Inheritance allows us to extend the functionality of the object. The new class automatically contains some or all methods
More informationThe Java Series. Java Essentials Advanced Language Constructs. Java Essentials II. Advanced Language Constructs Slide 1
The Java Series Java Essentials Advanced Language Constructs Slide 1 Java Packages In OO, libraries contain mainly class definitions A class hierarchy Typically, to use a class library we: Instantiate
More informationLecture Set 4: More About Methods and More About Operators
Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static
More informationProgramming overview
Programming overview Basic Java A Java program consists of: One or more classes A class contains one or more methods A method contains program statements Each class in a separate file MyClass defined in
More informationCS321 Languages and Compiler Design I. Winter 2012 Lecture 2
CS321 Languages and Compiler Design I Winter 2012 Lecture 2 1 A (RE-)INTRODUCTION TO JAVA FOR C++/C PROGRAMMERS Why Java? Developed by Sun Microsystems (now Oracle) beginning in 1995. Conceived as a better,
More informationSelected Questions from by Nageshwara Rao
Selected Questions from http://way2java.com by Nageshwara Rao Swaminathan J Amrita University swaminathanj@am.amrita.edu November 24, 2016 Swaminathan J (Amrita University) way2java.com (Nageshwara Rao)
More informationAssoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.
Assoc. Prof. Marenglen Biba Exception handling Exception an indication of a problem that occurs during a program s execution. The name exception implies that the problem occurs infrequently. With exception
More informationPIC 20A The Basics of Java
PIC 20A The Basics of Java Ernest Ryu UCLA Mathematics Last edited: November 1, 2017 Outline Variables Control structures classes Compilation final and static modifiers Arrays Examples: String, Math, and
More informationExceptions, try - catch - finally, throws keyword. JAVA Standard Edition
Exceptions, try - catch - finally, throws keyword JAVA Standard Edition Java - Exceptions An exception (or exceptional event) is a problem that arises during the execution of a program. When an Exception
More informationExceptions. Produced by. Introduction to the Java Programming Language. Eamonn de Leastar
Exceptions Introduction to the Java Programming Language Produced by Eamonn de Leastar edeleastar@wit.ie Department of Computing, Maths & Physics Waterford Institute of Technology http://www.wit.ie http://elearning.wit.ie
More informationLecture Set 4: More About Methods and More About Operators
Lecture Set 4: More About Methods and More About Operators Methods Definitions Invocations More arithmetic operators Operator Side effects Operator Precedence Short-circuiting main method public static
More informationCOMP 250 Winter 2011 Reading: Java background January 5, 2011
Almost all of you have taken COMP 202 or equivalent, so I am assuming that you are familiar with the basic techniques and definitions of Java covered in that course. Those of you who have not taken a COMP
More informationJava for Interfaces and Networks (DT3010, HT10)
Java for Interfaces and Networks (DT3010, HT10) Inner Classes Federico Pecora School of Science and Technology Örebro University federico.pecora@oru.se Federico Pecora Java for Interfaces and Networks
More informationWhat can go wrong in a Java program while running?
Exception Handling See https://docs.oracle.com/javase/tutorial/ essential/exceptions/runtime.html See also other resources available on the module webpage This lecture Summary on polymorphism, multiple
More informationToday. Homework. Lecture Notes CPSC 224 (Spring 2012) Quiz 5. interfaces. exceptions. best practices. start on swing (if time) hw3 due
Today Quiz 5 interfaces exceptions best practices start on swing (if time) Homework hw3 due hw4 out (next thurs) S. Bowers 1 of 8 Implicit vs. Explicit Parameters Methods define their explicit parameters
More informationCHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA
1. JIT meaning a. java in time b. just in time c. join in time d. none of above CHETTINAD COLLEGE OF ENGINEERING & TECHNOLOGY JAVA 2. After the compilation of the java source code, which file is created
More informationObject Oriented Programming Exception Handling
Object Oriented Programming Exception Handling Budditha Hettige Department of Computer Science Programming Errors Types Syntax Errors Logical Errors Runtime Errors Syntax Errors Error in the syntax of
More informationBrief Summary of Java
Brief Summary of Java Java programs are compiled into an intermediate format, known as bytecode, and then run through an interpreter that executes in a Java Virtual Machine (JVM). The basic syntax of Java
More information