MELJUN CORTES Java Lecture Commonly Used Objects
Upcoming SlideShare
Loading in...5
×
 

MELJUN CORTES Java Lecture Commonly Used Objects

on

  • 336 views

MELJUN CORTES Java Lecture Commonly Used Objects

MELJUN CORTES Java Lecture Commonly Used Objects

Statistics

Views

Total Views
336
Views on SlideShare
336
Embed Views
0

Actions

Likes
0
Downloads
7
Comments
0

0 Embeds 0

No embeds

Accessibility

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • StringBuffer and StringBuilder have the same methods. More on them later. <br />
  • Instantiation is a relatively expensive operation. <br />
  • 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. <br />
  • 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. <br /> See demo code: StringInstantiation.java <br />
  • 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. <br /> See demo code: StringConcatenation.java <br />
  • *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. <br />
  • 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. <br />
  • The compiler will rewrite your code before compilation so that the wrapping and extracting code will be written for you. <br />
  • The compiler will rewrite your code before compilation so that the wrapping and extracting code will be written for you. <br />
  • “Utility Classes” – Classes that just hold routines for other classes… to be discussed further later. <br />
  • “Utility Classes” – Classes that just hold routines for other classes… to be discussed further later. <br />
  • 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?) <br /> 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. <br /> See Demo code: DoubleVsBigDecimal.java <br />
  • 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. <br />
  • FIFO – First In, First Out <br />
  • 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! <br /> 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. <br />
  • Note on binarySearch – make sure to call sort before calling binarySearch, or the result may not be meaningful <br />
  • Note on binarySearch – just like with Arrays, make sure to call sort before calling binarySearch, or the result may not be meaningful <br />
  • Add discussion on Runtime vs Checked Exceptions <br /> Add discussion of Checked vs Unchecked <br />
  • Exception handling will be discussed in a later lecture <br />

MELJUN CORTES Java Lecture Commonly Used Objects MELJUN CORTES Java Lecture Commonly Used Objects Presentation Transcript

  • Commonly-Used Objects MELJUN CORTES a tour of the standard library of Java MELJUN CORTES
  • 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
  • The Object Class “The Mother of All Classes”
  • The Object Class  All classes are subclasses of Object
  • The Object Class  All classes inherit these methods:  clone(), equals(), finalize(), getClass(), hashCode(), notify(), notifyAll(), toString(), wait()
  • 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
  • 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
  • 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
  • The String Classes String and StringBuffer/StringBuilder
  • 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
  • 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"
  • 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"
  • 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”
  • 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"
  • 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
  • String  Strings are the only objects that can be used with the “+” and “+=” operators. String greeting = “happy ” + “birthday”; greeting += “ to you”;
  • 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
  • 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
  • Primitive Wrappers Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp
  • 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
  • Primitive Wrappers  Each primitive datatype has a corresponding wrapper type. Boolean Byte Character Short Number Integer Long Float Double BigDecimal
  • Primitive Wrappers  Immutable  Just like String, once value is set, it cannot be changed. Boolean Byte Character Short Number Integer Long Float Double BigDecimal
  • 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();
  • 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);
  • 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;
  • 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
  • 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. 
  • 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
  • BigDecimal  Computers cannot accurately store decimal values!  Using floats and doubles are dangerous in financial applications!
  • 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”);
  • BigDecimal  BigDecimal has methods for arithmetic operations. add, subtract, multiply, divide, min, max, negate, pow, abs, remainder, round  @see API Documentation for BigDecimal 
  • Collections Java Data Structures
  • 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
  • Collections  Collections will be discussed in more detail in a succeeding lecture.
  • Utility Classes classes that hold routines for other classes
  • 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
  • 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
  • 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
  • Utility Classes  Arrays  Contains methods for working with arrays   sort, binarySearch, equals, asList, toString @see API Documentation for Arrays
  • Utility Classes  Collections  Contains methods for working with Collections   sort, binarySearch, addAll, copy, min, max, frequency, unmodifiable____ @see API Documentation for Collections
  • Exceptions Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp
  • 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. 
  • The End Java Fundamentals and Object-Oriented Programming The Complete Java Boot Camp