MELJUN CORTES Java Lecture Commonly Used Objects


Published on

MELJUN CORTES Java Lecture Commonly Used Objects

Published in: Technology, Education
  • Be the first to comment

  • Be the first to like this

No Downloads
Total Views
On Slideshare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide
  • StringBuffer and StringBuilder have the same methods. More on them later.
  • Instantiation is a relatively expensive operation.
  • This problem often occurs in an often-called method that concatenates Strings based on parameters, or in string manipulation within a loop. Since String instances linger even when no more references point to it, they can cause a memory problem.
  • The “new” operator always instantiates a new object. The Java will create a new String instance instead of reusing one from the string pool. Each instance will linger even when no references point to it.
    See demo code:
  • StringBuffer and StringBuilder have exactly the same methods. Only difference is StringBuffer’s methods are synchronized. This can have an effect on performance when multiple threads want to read data from an instance of StringBuffer. While a thread has a lock on a StringBuffer instance, no other thread can invoke it. This is great for writing but can cause an unnecessary bottleneck if read is the only operation. As of Java 1.5, StringBuilder is preferred over StringBuffer, since the programmer has control over when to synchronize.
    See demo code:
  • *usually – For most of the wrappers, there are many ways to create them, some of which we’ll discuss later. For BigDecimal in particular, directly feeding a primitive value to the constructor is actually considered a bad practice. Again, we’ll discuss why later.
  • In line three, we had to extract the values in order to do arithmetic. In line four, we had to re-wrap the answer in a new Wrapper object.
  • The compiler will rewrite your code before compilation so that the wrapping and extracting code will be written for you.
  • The compiler will rewrite your code before compilation so that the wrapping and extracting code will be written for you.
  • “Utility Classes” – Classes that just hold routines for other classes… to be discussed further later.
  • “Utility Classes” – Classes that just hold routines for other classes… to be discussed further later.
  • Computers cannot accurately store decimal values! – Because computers store values as binary numbers, decimal values are stored only as an approximate value. (How do your represent 0.5 as a binary number?)
    Using floats and doubles are dangerous in financial applications! - Do not assume that there will be proper rounding-off in float and double calculations. Usually, it won’t.
    See Demo code:
  • The constructor that takes in a String allows BigDecimal to remember how many digits you want the precision to be. In the above example, it remembers that you want the value to remain precise to 3 digits.
  • FIFO – First In, First Out
  • Note on System.exit() – Do not use in server applications or any class that might be used in a server application! This might shut down the web container or application container that the class is running on!
    Note on System.gc() – This only suggests to the JVM to run the garbage collector. There is no guarantee that the garbage collector will run. If your app is running out of memory, look for other solutions before considering this method.
  • Note on binarySearch – make sure to call sort before calling binarySearch, or the result may not be meaningful
  • Note on binarySearch – just like with Arrays, make sure to call sort before calling binarySearch, or the result may not be meaningful
  • Add discussion on Runtime vs Checked Exceptions
    Add discussion of Checked vs Unchecked
  • Exception handling will be discussed in a later lecture
  • MELJUN CORTES Java Lecture Commonly Used Objects

    1. 1. Commonly-Used Objects MELJUN CORTES a tour of the standard library of Java MELJUN CORTES
    2. 2. Contents The Object Class The String Classes I. II. I. III. IV. V. VI. String, StringBuilder, etc. Wrapper Classes *todo:update Utility Classes Collections Exceptions
    3. 3. The Object Class “The Mother of All Classes”
    4. 4. The Object Class  All classes are subclasses of Object
    5. 5. The Object Class  All classes inherit these methods:  clone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), toString(), wait()
    6. 6. toString()  public String toString()  returns a String representation of the object  in the Object class, returns a concatenation of the runtime class name and the hashcode  usually overridden to return something more appropriate
    7. 7. equals()  public boolean equals(Object obj)  in the Object class, returns true when the parameter obj is the same instance as the current object   Same as == operator usually overridden to more appropriate implementation   Ex: for String – checks for spelling Ex: for BigDecimal – checks if value and scale are equal
    8. 8. hashCode()  public int hashCode() returns an integer value that is the object’s “hashcode”  used in “hashing” algorithms   such as in HashSet and HashMap rarely called directly  Best Practice: if you override equals, you must override hashcode   otherwise, hashing algorithms fail
    9. 9. The String Classes String and StringBuffer/StringBuilder
    10. 10. String and StringBuffer/StringBuilder Java actually has TWO types of strings!  String  Immutable – once you create it, you can never change its value.  StringBuffer/StringBuilder  Mutable – these are the classes you should use if you need to do a lot of string manipulation.   StringBuffer – before Java 1.5 StringBuilder – preferred option for Java 1.5 and above
    11. 11. String  The JVM maintains a pool of String objects. Each newly created String is stored in the pool. The instance lingers even if no references are pointing to it. String x = "SELECT"; String y = "SELECT"; "SELECT"
    12. 12. String  Great performance if there is no need to modify, since you don’t incur the cost of instantiation. String a = "SELECT"; String b = "SELECT"; String c = "SELECT"; "SELECT"
    13. 13. String  Otherwise, performance is terrible. Each “modification” actually creates a new String. “happy” String greeting = “happy”; greeting += “ ”; greeting += “birth”; greeting += “day”; “ ” “happy ” “birth” “happy birth” “day” “happy birthday”
    14. 14. String  The string pool is also the reason why you should never initialize a string with the “new” operator if the literal will do. String x = new String("SELECT"); String y = new String("SELECT"); String z = new String("SELECT"); "SELECT" "SELECT" "SELECT"
    15. 15. String String a = "SELECT"; String b = "SELECT"; a == b  true! a and b point to the same instance String c = new String("SELECT"); String d = new String("SELECT"); c == b  false! c and d point to different instances
    16. 16. String  Strings are the only objects that can be used with the “+” and “+=” operators. String greeting = “happy ” + “birthday”; greeting += “ to you”;
    17. 17. String  String Methods  @see the API documentation for String  Notice that all methods for “string manipulation” will not modify the String instance. They will only return a new String.  substring, trim, split, replace, replaceFirst, replaceAll, concat, toUpperCase, toLowerCase  Methods for searching for characters or patterns in a String:  charAt, startsWith, endsWith, indexOf, lastIndexOf  Methods for comparing Strings  equals, equalsIgnoreCase, compareTo, compareToIgnoreCase
    18. 18. StringBuffer/StringBuilder  Maintains an internal character array, contents can be modified.  Great performance when modifications are needed.  @see API documentation for StringBuilder  append, delete, insert, replace, setCharAt, length, toString
    19. 19. Primitive Wrappers Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp
    20. 20. Primitive Wrappers  Allow primitive values to participate in the world of objects.  Boolean Byte For example, allows primitives to be stored in “Collections” (Java data structures) Character Short Number Integer Long Float Double BigDecimal
    21. 21. Primitive Wrappers  Each primitive datatype has a corresponding wrapper type. Boolean Byte Character Short Number Integer Long Float Double BigDecimal
    22. 22. Primitive Wrappers  Immutable  Just like String, once value is set, it cannot be changed. Boolean Byte Character Short Number Integer Long Float Double BigDecimal
    23. 23. Primitive Wrappers  Creating a Primitive Wrapper  Primitive wrappers are usually* created simply by calling the constructor and feeding the primitive value as a constructor: Integer i = new Integer(14);  Retrieving Primitive Values  Call one of the methods that end in “___Value”: int x = i.intValue(); byte y = i.byteValue(); long z = i.longValue();
    24. 24. Primitive Wrappers  Before Java 1.5, you can’t use primitive wrappers directly in arithmetic nor comparison operators. You have to extract the primitive values first: Integer i = new Integer(5); Integer j = new Integer(10); int temp = i.intValue() + j.intVAlue(); Integer answer = new Integer(temp);
    25. 25. Primitive Wrappers  Autoboxing and Unboxing in Java 1.5  Java 1.5 automatically converts primitives to wrappers and wrappers to primitives: Integer i = 5; Integer j = 10; Integer answer = i + j;
    26. 26. Primitive Wrappers  equals() method  Returns true if the object passed is of the same type and has the same value: Integer i = new Integer(10); Integer j = new Integer(10); Integer k = new Integer(25); Long l = new Long(10); i.equals(j);  true i.equals(k);  false i.equals(l);  false i.equals(null);  false
    27. 27. Primitive Wrappers  Primitive Wrappers as Utility Classes Primitive Wrappers also serve as “Utility Classes”*.  They contain static methods and static fields that are useful for the type of primitive that each of them wraps. 
    28. 28. Primitive Wrappers  Primitive Wrappers as Utility Classes  @see the API documentation for the ff:    Integer: parseInt, toString. MAX_VALUE, MIN_VALUE Float: parseFloat, NaN, POSITIVE_INFINITY, NEGATIVE_INFINITY, isNaN, isInfinite Character: isDigit, isLetter, isLetterOrDigit, isLowerCase, isUpperCase, isSpace, isWhitespace
    29. 29. BigDecimal  Computers cannot accurately store decimal values!  Using floats and doubles are dangerous in financial applications!
    30. 30. BigDecimal  BigDecimal accurately stores a decimal number to a specified level of precision.  Use the constructor that takes in a String to create precise values: new BigDecimal(“1.25”);
    31. 31. BigDecimal  BigDecimal has methods for arithmetic operations. add, subtract, multiply, divide, min, max, negate, pow, abs, remainder, round  @see API Documentation for BigDecimal 
    32. 32. Collections Java Data Structures
    33. 33. Collections Objects used to hold other objects (data structures).  Lists – like arrays, only size can grow  Sets – like lists, only all elements have to be unique  SortedSets – sets that hold elements in a sorted order  Maps – maintains a set of key-value pairs  Queues (Java 1.5) – used to hold objects prior to processing, usually in a FIFO* manner, sometimes in some sort of “priority” ordering
    34. 34. Collections  Collections will be discussed in more detail in a succeeding lecture.
    35. 35. Utility Classes classes that hold routines for other classes
    36. 36. Utility Classes  Classes that just hold useful routines.  All methods and fields are static.  Never instantiated.  To be discussed: 1. 2. 3. 4. System Math Arrays Collections
    37. 37. Utility Classes  System  Used to get some access the underlying operating system.    Fields: out, err, in Methods: arraycopy, currentTimeMillis, exit, getProperties, getProperty, gc @see API Documentation for System
    38. 38. Utility Classes  Math  Contains methods for mathematical operations   abs, round, min, max, sin, cos, tan, floor, ceil, exp, log, random @see API Documentation for Math
    39. 39. Utility Classes  Arrays  Contains methods for working with arrays   sort, binarySearch, equals, asList, toString @see API Documentation for Arrays
    40. 40. Utility Classes  Collections  Contains methods for working with Collections   sort, binarySearch, addAll, copy, min, max, frequency, unmodifiable____ @see API Documentation for Collections
    41. 41. Exceptions Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp
    42. 42. Exceptions  Special objects used to indicate that an exceptional (usually undesirable) event has occurred.  Will abruptly end execution, unless handled. A “stack trace” will be written to the standard error stream to help you debug your problem.  The stack trace will contain all the methods that were in execution, and the line number of the code being called in each method, at the time the exception occurred. 
    43. 43. The End Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp
    1. A particular slide catching your eye?

      Clipping is a handy way to collect important slides you want to go back to later.