 It is possible to declare names for object references and not assign object references to them.  Such names literally refer to nothing at all.  It.

Slides:



Advertisements
Similar presentations
Introduction to Eclipse. Start Eclipse Click and then click Eclipse from the menu: Or open a shell and type eclipse after the prompt.
Advertisements

METHOD OVERRIDING 1.Sub class can override the methods defined by the super class. 2.Overridden Methods in the sub classes should have same name, same.
2.4 Creating and Using Objects. Writing the code for classes of your own will come later. At this time it is possible to understand and correctly write.
Static Methods Static methods are those methods that are not called on objects. In other words, they don’t have an implicit parameter. Random number generation.
Designing an ADT The design of an ADT should evolve naturally during the problem-solving process Questions to ask when designing an ADT What data does.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Slides prepared by Rose Williams, Binghamton University ICS201 Exception Handling University of Hail College of Computer Science and Engineering Department.
CIT 590 Intro to Programming Java lecture 3. Hashmaps The equivalent of python dictionaries. With both ArrayLists and Hashmaps, the syntax only allows.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
1 From Yesterday private = accessible only to the class that declares it public = accessible to any class at all protected = accessible to the class and.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Slides prepared by Rose Williams, Binghamton University Chapter 9 More Exception Handling.
Miscellaneous OOP topics Java review continued. Simple data types & wrapper classes Simple data types are the built-in types provided as part of the Java.
Java Exceptions. Intro to Exceptions  What are exceptions? –Events that occur during the execution of a program that interrupt the normal flow of control.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
1 Exception and Event Handling (Based on:Concepts of Programming Languages, 8 th edition, by Robert W. Sebesta, 2007)
Exceptions. Many problems in code are handled when the code is compiled, but not all Some are impossible to catch before the program is run  Must run.
Unit 2: Java Introduction to Programming 2.1 Initial Example.
Java Unit 9: Arrays Declaring and Processing Arrays.
CIS3023: Programming Fundamentals for CIS Majors II Summer 2010 Ganesh Viswanathan Exception Handling in Java Course Lecture Slides 7 th July 2010 “ Admitting.
C++ Programming: Program Design Including Data Structures, Fourth Edition Chapter 13: Pointers, Classes, Virtual Functions, and Abstract Classes.
C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 14: Pointers, Classes, Virtual Functions, and Abstract Classes.
“is a”  Define a new class DerivedClass which extends BaseClass class BaseClass { // class contents } class DerivedClass : BaseClass { // class.
CPSC 252 Exception Handling Page 1 Exceptions and exception handling Client programmers can make errors using a class attempting to dequeue an item from.
Object Oriented Programming
MT311 Java Application Development and Programming Languages Li Tak Sing( 李德成 )
Exception Handling in Java Exception Handling Introduction: After completing this chapter, you will be able to comprehend the nature and kinds.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
220 FINAL TEST REVIEW SESSION Omar Abdelwahab. INHERITANCE AND POLYMORPHISM Suppose you have a class FunClass with public methods show, tell, and smile.
Exceptions 1. Your computer takes exception Exceptions are errors in the logic of a program (run-time errors). Examples: Exception in thread “main” java.io.FileNotFoundException:
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
4.1 Instance Variables, Constructors, and Methods.
 Java has the logical operators and, or, and not, symbolized by &&, ||, and !, respectively.  Logical or means one or the other or both conditions hold.
Constructors CMSC 202. Object Creation Objects are created by using the operator new in statements such as… The following expression invokes a special.
Unit 1: Java and Eclipse The Eclipse Development Environment.
Comments in Java. When you create a New Project in NetBeans, you'll notice that some text is greyed out, with lots of slashes and asterisks:
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Exceptions and Assertions Chapter 15 – CSCI 1302.
CMSC 202 Advanced Section Classes and Objects: Object Creation and Constructors.
CIT 590 Intro to Programming Lecture 13. Some Eclipse shortcuts CTRL + SHIFT + F – format file (proper indentation etc). Please do this before you submit.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
Classes - Intermediate
CSE 501N Fall ’09 07: Iteration 17 September 2009 Nick Leidenfrost.
COMP Inheritance and Polymorphism Yi Hong June 09, 2015.
And other languages…. must remember to check return value OR, must pass label/exception handler to every function Caller Function return status Caller.
Exception. Agenda Exception. Handling Exceptions. The finally Clause.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
Introduction to Exceptions in Java CS201, SW Development Methods.
Section 3.3 Exceptional Situations. 3.3 Exceptional Situations Exceptional situation Associated with an unusual, sometimes unpredictable event, detectable.
Last Revision. Question1 Novice Java programmers often write code similar to, class C { public int x;... }... C[] a = new C[10]; for(int i = 0; i < a.length;
Programming in Java Transitioning from Alice. Becomes not myFirstMethod but …. public static void main (String[] arg) { // code for testing classes goes.
Exceptions Part II. What you need to know Last time –What happens when an exception is thrown –What are your choices for handling exceptions –The different.
Introduction to Java Import Scanner class to use in our program
Java Unit 11: Inheritance I
Exceptions In this lecture:
Logger, Assert and Invariants
Some Eclipse shortcuts
MIT AITI 2003 Lecture14 Exceptions
Classes.
Exceptions 10-Nov-18.
Handling Exceptions.
Class Structure 16-Nov-18.
Class Structure 7-Dec-18.
Class Structure 2-Jan-19.
Class Structure 25-Feb-19.
Java Programming Language
CMSC 202 Exceptions.
CMSC 202 Constructors Version 9/10.
Presentation transcript:

 It is possible to declare names for object references and not assign object references to them.  Such names literally refer to nothing at all.  It is also possible for a reference to be assigned the special value “null”.  Although no object exists, this is not the same as referring to nothing at all.

 A programmer can make such an assignment and in certain situations the system will make such an assignment by default.  Even if you choose not to use null in your code, you need to know about it since the system may make use of it.  Various errors can arise from improper use of null references, and it is important to be able deal with these errors, and distinguish them from errors arising from references to nothing at all.

 Here is a null reference assignment:  Cup3 myCup;  myCup = null;

 This could be used, for example to dispose of a previously constructed object without creating a new one:   Cup3 myCup;  myCup = new Cup3(4);  …  myCup = null;

 What follows is a class definition and a set of examples showing various different things that can happen within programs that use the class.  These things are either the result of an object name referring to nothing at all, or a null reference.  Here is the class:

 public class Shampoo  {  private String kind;  private int rating;   public Shampoo(String kindIn)  {  kind = kindIn;  }   public Shampoo(int ratingIn)  {  rating = ratingIn;  } 

 public void setKind(String kindIn)  {  kind = kindIn;  }   public String getKind()  {  return kind;  }   public void setRating(int ratingIn)  {  rating = ratingIn;  }   public int getRating()  {  return rating;  }

 Here is the first example.  It illustrates that using an object name as a parameter in a method call does not work if the object does not exist.  The compiler can detect a problem like this.   public class Test1  {  public static void main(String[] args)  {  Shampoo myShampoo;  System.out.println(myShampoo);  }

 In the Eclipse development environment the line of code with the error will be marked with a red X box at the left, and there will also be an error message in the Problems tab at the bottom.  If you move the mouse over the red X box by the line of code, the box shown below with the explanatory messages will appear:

 Error messages are occasionally worded in an unhelpful way, or sometimes the compiler can't determine absolutely what might be wrong.  This error message is worded helpfully, but it says "may" just because something else might be wrong.

 But in this case, the fact that myShampoo does not refer to an actual object is the problem, and that is indicated by the error message.  If the compiler ends with such an error, no program is created and it is impossible to run the code.  If you try to run the code anyway, this is what you'll see:

 If you press the proceed button, the system will repeat the compiler error message.

 Here is the second example, which illustrates a similar situation.  An object name is declared, but no object exists, and a method is called on that name.   public class Test2  {  public static void main(String[] args)  {  Shampoo myShampoo;  int someRating = myShampoo.getRating();  System.out.println(someRating);  }

 The second example generates exactly the same kind of compiler error as the first example, and no program results.

 Now consider the third example.  It is similar to the first example, in that it considers the case where an object reference is to be passed as a parameter.  No object exists but in this case the reference has been given the value null.   public class Test3  {  public static void main(String[] args)  {  Shampoo myShampoo = null;  System.out.println(myShampoo);  }

 The program compiles and runs successfully.  It prints out the value of the reference myShampoo with no problem.  Here is the output:   null

 Now consider the fourth example.  It is similar to the second example, in that it considers the case where a method is to be called on an object reference.  No object exists but in this case the reference has been given the value null.   public class Test4  {  public static void main(String[] args)  {  Shampoo myShampoo = null;  int someRating = myShampoo.getRating();  System.out.println(someRating);  }

 This program compiles without a red X box, but the compiler does mark the middle line of code with this warning message:

 The system will still let you run the program even though it is not possible to successfully make a method call on a null reference.  If you run the code, this message will appear in the Console tab at the bottom of the environment.  Notice that this is a runtime error, not a compiler error.  That's why it appears in the Console, where output normally appears, not in the Problems tab.   Exception in thread "main" java.lang.NullPointerException  at TestShampoo.main(TestShampoo.java:5)

 Even though you hope to catch all of your problems up front through compiler warnings, and so on, it is worthwhile to be aware of the NullPointerException message and know that it signifies, in simple terms, that in your code you tried to call a method on an object reference that contained the null value.  As the next example will show, this kind of problem can crop up.

 The first four examples were relatively straightforward.  They illustrate problems that a beginning programmer should be able to manage.  However, there is a more subtle source of null references in programs.  The Shampoo class has an instance variable that is a string.  Since String is a class, this instance variable is an object reference.

 The Shampoo class has a constructor that takes a single int as a parameter.  In the code for that constructor, nothing is done to explicitly initialize the String instance variable.  If any initialization does occur, it is by default.  The key point is that the system will initialize the String instance variable by default, to the value null.

 Now consider the fifth example, which makes use of this constructor.  public class Test5  {  public static void main(String[] args)  {  Shampoo myShampoo;   String someKind;  int someRating = 5;   myShampoo = new Shampoo(someRating);   someKind = myShampoo.getKind();   System.out.println(someKind);  }

 This is the output from the fifth example:   null

 This program runs successfully because it is possible to have a null reference as an explicit parameter.  However, it illustrates that null references can arise in programs from unexpected sources.  The sixth example illustrates how a program may fail due to a null reference that was obtained from elsewhere.

 public class Test6  {  public static void main(String[] args)  {  Shampoo myShampoo;   String someKind;  int someRating = 5;   myShampoo = new Shampoo(someRating);   someKind = myShampoo.getKind();   System.out.println(someKind);   int length = someKind.length();   System.out.println(length);  }

 The program runs correctly through this line of code:   System.out.println(someKind);

 It causes this output in the Console tab at the bottom, with "null" being the result of this last successfully executed line of code:   null  Exception in thread "main" java.lang.NullPointerException  at TestShampoo.main(TestShampoo.java :15)

 The program then encounters a problem in this line of code:   int length = someKind.length();   This is what causes this runtime error message:   Exception in thread "main" java.lang.NullPointerException  at TestShampoo.main(TestShampoo.java :15)

 The error is the same as the one noted before.  It is not possible to call a method on a null reference.  The compiler is not all-knowing.  It can only see one level deep—it can't see what a reference may contain at run time.  Only the programmer can foresee and avoid problems like this, or correct them after they have been discovered.

 References that refer to nothing and null references are possible in Java.  The default initialization of instance variables in objects can cause null references in programs.  This is a subtle source of problems that the programmer needs to be aware of.

 The examples above are not exhaustive, but they show some representative cases and the results that they lead to.  If you encounter an error message similar to one of those shown above, you may be able to figure out what your problem is by looking at the examples again.