Skip to content

Latest commit

 

History

History
186 lines (127 loc) · 6.77 KB

File metadata and controls

186 lines (127 loc) · 6.77 KB

Maps, primitives, File I/O

Primitives vs. Objects

  • Java Type System

    Java has a two-fold type system consisting of primitives such as int, boolean and reference types such as Integer, Boolean. Every primitive type corresponds to a reference type.

    The wrapper classes are immutable (so that their state can't change once the object is constructed) and are final ( so that we can't inherit from them).

    Under the hood, Java performs a conversion between the primitive and reference types if an actual type is different from the declared one:

    Integer j=1;          // autoboxing
            int i=new Integer(1); // unboxing

    The process of converting a primitive type to a reference one is called autoboxing, the opposite process is called unboxing.

  • Pros and Cons

    The decision what object is to be used is based on what application performance we try to achieve, how much available memory we have, the amount of available memory and what default values we should handle.

    If we face none of those, we may ignore these considerations though it's worth knowing them.

  • Single Item Memory Footprint

    the primitive type variables have the following impact on the memory:

    • boolean – 1 bit
    • byte – 8 bits
    • short, char – 16 bits
    • int, float – 32 bits
    • long, double – 64 bits

    Primitive Types live in the stack and hence are accessed fast.

    The reference types are objects, they live on the heap and are relatively slow to access. They have a certain overhead concerning their primitive counterparts.

    It turns out that a single instance of a reference type on this JVM occupies 128 bits except for Long and Double which occupy 192 bits:

    • Boolean – 128 bits
    • Byte – 128 bits
    • Short, Character – 128 bits
    • Integer, Float – 128 bits
    • Long, Double – 192 bits
  • Memory Footprint for Arrays

    We can see either that single-element arrays of primitive types are almost always more expensive (except for long and double) than the corresponding reference type.

  • Performance

    The performance of a Java code is quite a subtle issue, it depends very much on the hardware on which the code runs.

    The access time for primitive types are much lower than the reference types

  • Default Values

    Default values of the primitive types are 0 (in the corresponding representation, i.e. 0, 0.0d etc) for numeric types, false for the boolean type, \u0000 for the char type. For the wrapper classes, the default value is null.

  • Usage

    As we've seen, the primitive types are much faster and require much less memory. Therefore, we might want to prefer using them.

    On the other hand, current Java language specification doesn't allow usage of primitive types in the parametrized types (generics), in the Java collections or the Reflection API.

    When our application needs collections with a big number of elements, we should consider using arrays with as more “economical” type as possible.

Exceptions in Java

  • What Is an Exception?

    An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. When an error occurs within a method, the method creates an object and hands it off to the runtime system. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred.

  • The Catch or Specify Requirement

    Valid Java programming language code must honor the Catch or Specify Requirement. This means that code that might throw certain exceptions must be enclosed by either of the following:

    • A try statement that catches the exception. The try must provide a handler for the exception, as described in Catching and Handling Exceptions.
    • A method that specifies that it can throw the exception. The method must provide a throws clause that lists the exception, as described in Specifying the Exceptions Thrown by a Method.

    Code that fails to honor the Catch or Specify Requirement will not compile.

  • Catching and Handling Exceptions

    We use the try, catch, and finally blocks or try-with-resources statement, introduced in Java SE 7 to handle potential exceptions.

    The try-with-resources statement is particularly suited to situations that use Closeable resources, such as streams.

    i.g:

    // Note: This class will not compile yet.
    import java.io.*;
    import java.util.List;
    import java.util.ArrayList;
    
    public class ListOfNumbers {
    
        private List<Integer> list;
        private static final int SIZE = 10;
    
        public ListOfNumbers () {
            list = new ArrayList<Integer>(SIZE);
            for (int i = 0; i < SIZE; i++) {
                list.add(new Integer(i));
            }
        }
    
        public void writeList() {
        // The FileWriter constructor throws IOException, which must be caught.
            PrintWriter out = new PrintWriter(new FileWriter("OutFile.txt"));
    
            for (int i = 0; i < SIZE; i++) {
                // The get(int) method throws IndexOutOfBoundsException, which must be caught.
                out.println("Value at: " + i + " = " + list.get(i));
            }
            out.close();
        }
    }

Using Scanner to read in a file in Java

  • Scanning

Objects of type Scanner are useful for breaking down formatted input into tokens and translating individual tokens according to their data type.

  • Breaking Input into Tokens

    By default, a scanner uses white space to separate tokens. (White space characters include blanks, tabs, and line terminators. For the full list, refer to the documentation for Character.isWhitespace.) To see how scanning works, let's look at ScanXan, a program that reads the individual words in xanadu.txt and prints them out, one per line.

    import java.io.*;
    import java.util.Scanner;
    
    public class ScanXan {
    public static void main(String[] args) throws IOException {
    
            Scanner s = null;
    
            try {
                s = new Scanner(new BufferedReader(new FileReader("xanadu.txt")));
    
                while (s.hasNext()) {
                    System.out.println(s.next());
                }
            } finally {
                if (s != null) {
                    s.close();
                }
            }
        }
    }

    To use a different token separator, invoke useDelimiter(), specifying a regular expression. For example, suppose you wanted the token separator to be a comma, optionally followed by white space. You would invoke,

    s.useDelimiter(",\\s*");