1 / 30

Miscellaneous Concepts Review

Learn how to effectively comment and document your Java code using Javadoc notation and standard tags recognized by javadoc. Understand the 5 common exceptions you need to remember for the AP Exam.

Download Presentation

Miscellaneous Concepts Review

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Miscellaneous Concepts Review Individual Items You Need to Remember for the AP Exam!

  2. javadoc Documentation You are familiar with using multiline comments in the form of: /* and */ to comment out multiple lines in a source code file. However, you can also comment a program correctly using /** and */ and the standard tags recognized by javadoc @param @return Using these tags and others you can easily create online web documentation for your own Java classes. You will see this notation on the AP Exam primarily on Free Response Questions.

  3. @param and @return • @param documents a method’s parameter, in other words, it explains the intent of the parameter and anything special about it, like: @param t an array of test scores • @return documents a method’s return value, in other words, it explains the type of return value by describing what is intended like: @returnthe student’s highest score.

  4. Exceptions • There are 5 Exceptions that you need to be familiar with when taking the AP Exam. You could be asked a question that wants to know what kind of Exception will be thrown by a segment of code. The five you need to know are: • NullPointerException • ArrayIndexOutOfBoundsException • ArithmeticException • ClassCastException • IllegalArgumentException

  5. NullPointerException A NullPointerException occurs when you try to access or send a message to an objectthat has not been instantiated or in the case of Strings, one that is not initialized. Here is code that throws that exception: String str; System.out.println(“The length is ” + str.length() ); This version will NOT throw an exception: String str = “Java”; System.out.println(“The length is ” + str.length() );

  6. ArrayIndexOutOfBoundsException An ArrayIndexOutOfBoundsException occurs when you try to access an array memory location that is outside the possible range of index values for the array that has been instantiated. Here is code that throws that exception: int [ ] nums = new int [10]; nums only has valid indices from 0 to 9. int x = nums[10]; // index 10 is out of bounds for nums!

  7. ArithmeticException An ArithmeticException occurs when you try to perform an illegal arithmetic operation like division by zero when using int values. Here is code that throws that exception when the user enters 0 for the number of tests: int testTotal = // code to get the total of test scores System.out.print(“Enter the number of tests: ”); int numOfTests = reader.nextInt(); int ave = testTotal / numOfTests; // The last line of code only throws an exception for 0.

  8. ClassCastException • Typically, a ClassCastException occurs when you pass the wrong kind of object to a method and the method is unable to use that object. Here is code that throws that exception: • Shape cc1 = new ConcentricCircle (…….); • Shape c2 = new Circle (…….); • if (cc1.equals(c2)) // throws ClassCastException • System.out.println("cc1 and cc2 are equal"); • When I try to check these two shapes for equality with the above line of code, then a ClassCastException is thrown with the message: • ch10.ShapeVersion4.Circle cannot be cast to ch10.ShapeVersion4.ConcentricCircle • The programmer should be passing equals another ConcentricCircle object … NOT a Circle object.

  9. IllegalArgumentException A IllegalArgumentException occurs when you try to pass a value to a methodthat is out side of the range of use or is in some way inappropriate for making a calculation or processing information. Here is code from the TestScores program that throws the exception: In the Student class, you have the method: public void setScore (int i, int score) ….. and you can only pass it 1, 2 or 3, because each student only has 3 tests. If you construct a student and then ask the program to set score #4, Java will throw this exception. Student s = new Student (“Mary”, 90, 80, 85); s.setScore(4, 83); will throw an IllegalArgumentException.

  10. Theoretical Concepts • There are a number of key concepts that you need to understand and be able to identify. We haven’t discussed them a lot but not put names on them. They include: • Inheritance • Polymorphism • Information Hiding • Encapsulation

  11. Inheritance & Polymorphism Inheritance - creating classes and interfaces in a hierarchy to reduce duplication of code and promote polymorphism. Polymorphism - different types of objects can understand the same message. However, an object’s response depends on the class to which it belongs. You wrote code in the Circle, Rectangle, Triangle, and ConcentricCircle classes for the draw() method. The method signature was always the same and defined in the Shape interface. This is an example, of polymorphism.

  12. Inheritance & Polymorphism Then we used code like this: Shape s1 = new Circle (…..); Shape s2 = new Rectangle (…..); Shape s3 = new Triangle (…..); Shape s4 = new ConcentricCircle (…..); s1.draw(g); s2.draw(g); s3.draw(g); s4.draw(g); Polymorphism allows programmers to remember more easily the names of methods they need to call for different objects.

  13. Inheritance & Polymorphism When we added the AbstractShape class, then we placed the methods: getXPos() getYPos() getColor() in that class and stripped them out of Circle, Rectangle, and Triangle to promote unnecessary duplication of code. Those methods became final methods to indicate they shouldn’t be written in the subclasses, but a method like draw() was an abstract method because different code needed to be written in Circle, Rectangle, and Triangle to draw those objects. However, you will not see abstract or final used in abstract classes on the AP Exam. The reason is they are not necessary to accomplish basic inheritance, which is all that will be tested on the AP Exam.

  14. Information Hiding & Encapsulation Information Hiding refers to a class being able to receive services from another class without having access to all of its data resources. For example, a driver program that constructs a Circle object has access to constructing a Circle object and calling any public methods of the Circle class, but it does not have access directly to the private instance variables or private helper methods. If it needs the radius of the Circle, then it calls the public getRadius() method to get its value. Encapsulation is the combining numerous data types and methods into one software entity. A good example is the Student class, that had 4 instance variables: name, test1, test2, & test3. The student class had numerous methods, like getHighsScore(), associated with it so driver programs could get various kinds of information.

  15. Casting Casting istemporarily converting one data type to another. You can cast a single variable or an entire expression. To do this place the desired data type within parentheses before the variable or expression that will be cast to another data type. Examples: int i = (int) 3.14; // i gets 3 double d = (double) 5 / 4; is equivalent to 5.0 / 4 and d holds 1.25. This is because 5 / 4 is not inside its own parentheses so only the 5 is cast to a double. If the expression had been double d = (double) (5 / 4); Java would have performed int division first on 5 / 4 to get 1 and then 1 would have been cast to 1.0 and d would have held 1.0.

  16. Rounding You are expected to know that casting a double value to an int truncates it towards 0. This is why in the previous example that 3.14 becomes 3 (closer to 0). int i = (int) 3.14; // i gets 3 You also need to know that a positive floating-point (double) number x can be rounded to the nearest integer using: int result = (int) (x + 0.5); and that a negative floating-point (double) number y can be rounded to the nearest integer using: int result = (int) (y - 0.5);

  17. Positive Double Rounding Example 1 The cast operator is useful for rounding floating-point numbers to the nearest integer: int p, n; double x, y; x = 45.7; p = (int) (x + 0.5); // adding 0.5 and then casting which truncates // achieves the correct result. 45.7 + 0.5 = 46.2 (int) 46.2 ------> 46

  18. Positive Double Rounding Example 2 The cast operator is useful for rounding floating-point numbers to the nearest integer: int p, n; double x, y; x = 45.2; p = (int) (x + 0.5); // adding 0.5 and then casting which truncates // achieves the correct result. 45.2 + 0.5 = 45.7 (int) 45.7 ------> 45

  19. Negative Double Rounding Example 1 The cast operator is useful for rounding floating-point numbers to the nearest integer: int p, n; double x, y; y = -22.4; n = (int) (y - 0.5); // subtracting 0.5 and then casting which // achieves the correct result. -22.4 - 0.5 = -22.9 (int) (-22.9) ------> -22

  20. Negative Double Rounding Example 2 The cast operator is useful for rounding floating-point numbers to the nearest integer: int p, n; double x, y; y = -22.8; n = (int) (y - 0.5); // subtracting 0.5 and then casting which // achieves the correct result. -22.8 - 0.5 = -23.3 (int) (-23.3) ------> -23

  21. Escape Sequences • The escape character, is a backslash (\). • You are expected to know three escape sequences for the AP Exam: • \” - places quotes around something in output • \n - produces new line in output • \\ - prints a \ in output when needed, like in a path name. • String literals are delimited by quotation marks (“…”), which presents a dilemma when quotation marks are supposed to appear inside a string in output. Placing a \ before the quotation mark, indicates that the quotation mark is to be taken literally. • Example 1: • System.out.println(“As the train left the station, ” + • “the conductor yelled, \”All aboard.\””); • All aboard will appear in double quotes.

  22. Escape Sequences Continued You are expected to know three escape sequences for the AP Exam: \” - places quotes around something in output \n - produces new line in output \\ - prints a \ in output when needed, like in a path name. Example 2: System.out.print(“Hello World!” + “\n\n”); Here Java executes two new line commands after “Hello World”. Example 3: System.out.print(“C:\\Java\\Ch3.doc”); This prints the path name C:\Java\Ch3.doc

  23. 10 40 60 30 40 [0] [1] [2] [3] [4] 1D Array Initializer Lists You must be able to understand how one-dimensional and two-dimensional arrays are being created with initializer lists. For example … int [ ] x = {10, 40, 60, 30, 40}; creates an array that looks like this …

  24. 2D Array Initializer Lists You must be able to understand how one-dimensional and two-dimensional arrays are being created with initializer lists. For example … int[][] table = { { 0, 1, 2, 3, 4}, // row 0 {10, 11, 12, 13, 14}, // row 1 {20, 21, 22, 23, 24}, // row 2 {30, 31, 32, 33, 34} // row 3 }; creates a two dimensional array of ints. Initializer lists can place any kind of values in an array.

  25. this and other If we have two circles that have been created …. Circle c1 = new Circle(………); Circle c2 = new Circle(………); and we test for equality using the equals method of the Circle class, publicboolean equals (Object other) { if (this == other) returntrue; if ( ! (other instanceof Circle)) thrownew IllegalArgumentException("Your parameter is not a Student!"); Circle c = (Circle ) other; returnthis.radius.equals(c.radius); } then back in the program code that calls equals ….

  26. this and other using the expression … if( c1.equals(c2) ) ………… c1 refers to this and c2 refers to other. Note that c1 (this) executes the method equals and c2 is the parameter other. Note: This is the only thing about this that you need to know for the AP Exam, even though I have taught you other things.

  27. Implementing Classes & Constants When writing the code for a class on a free response question, you are expected to implement constructors that initializeall instance variables. Make all instance variables private! If you have to declare a class constant in the class you are writing, then make sure you initialize it to some value. Don’t just declare it! All variables are declared asstatic. public static final int MAX_SCORE = 100; public static final double AVE_PERCENTAGE = 75.3; public static final String DEFAULT_NAME = “John Doe”;

  28. Implementing Classes and Interfaces On the AP Exam, you are expected to extend classes and implement interfaces. You are also expected to have a knowledge of inheritance that includes understanding the concepts of method overriding and polymorphism. You are expected to implement their own subclasses. You are expected to read the definitions of interfaces and abstract classes and understand that the abstract methods need to be implemented in a subclass. You are expected to write interfaces or class declarations when given a general description of the interface or class. Review the following code you wrote: Shape interface, and the AbstractShape, Rectangle, Triangle, Circle, and ConcentricCircle classes.

  29. equals and identity You are expected to understand the difference between objectequality (equals) and identity (==). For objects, equals checks to see if the “contents” of the objects are equal based on some characteristic of the object, and == compares the references (memory addresses) of the two objects. So you want to always use equals. For the AP Exam, you do not need to know how to implement (write the code) for an equals method. (We did it so you could more fully understand the concept.) However, for variables that containprimitive data types like int, double, and boolean, we do use == to check for equality. This may seem confusing, but that’s how it works in Java.

  30. Import Statements You are expected to have a basic understanding of packages and a reading knowledge of import statements of the form: import packageName.subpackageName.ClassName;

More Related