Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Tuesday, December 6, 2016

Java Interface and Exception.

Understanding Interfaces and Abstract Methods
  • To define what a class must do but not how to do it until later in specific application.
    • An abstract class define its signature and return types, namely, its interface for multiple processes or methods without implementations.
  • How? Specify methods with no body ({}).
  • Actions are defined in a class that implements the interface.
  • One interface, multiple methods is the essence of polymorphism.
  • Prior to JDK 8, interfaces could not define any implementation whatsoever. JDK 8 changes the rule so that default implementation to an interface method is allowed.
  • The original intent behind interface/abstract class remains. and default implementation in essence is a special use feature.
  • JDK 8 also added the ability to define static methods in interfaces.
    • Same as static methods in a class, static methods in interfaces can be called independently of any object created from it.
    • Yes, no implementation or instance of the interface is required to call a static method.
    • To call, specify the interface name, a period and the method name.
    • Static interface methods are not inherited by implementing class or a sub-interface extended from the parent interface.

Using Interface References
  • You can create an interface reference variable and use it to refer to any object that implements its interface. 
  • When you call a method on an object through an interface reference, you are calling the version of the method implemented by the object that is executed at runtime. 
  • This is similar as using a superclass reference to access a child class's methods on its objects. 

Using Interface to Share Constants
  • Though controversial, one usage of interface is to share constants among multiple classes.
  • Variables in interfaces are implicitly public, static and final and these are the characteristics of constants.
  • Examples of applications includes array size, various limits, special values and the like.

Extending Interface
  • An interface can inherit another interface by extending. 
  • When a class implements the derived interface, it must implement all methods in the inheritance chain.
interface X {
   void method1 ();
   void method2 ();
}

interface Y extends X {
   void method3 ();
}

class Z implements Y {
   public void method1 () {
      // do something...
   }
   public void method2 () {
      // do something...
   }
   public void method3 () {
      // do something...
   }
}

class Z2 implements Y {
   // implements all three methods
}

// Using Interface References
class Demo {
   public static void main (String args[]) {
   Z  obz  = new Z();
   Z2 obz2 = new Z2();
   X  obx  = new X();
   obx = obz;
   System.out.println ("Class z attribute is " + obx.getAttribute());
   obx = obz2;
   System.out.println ("Class z2 attribute is " + obx.getAttribute());
}


Exceptions
  • All exceptions are represented by classes.
  • All exceptions are derived from "Throwable" class.
  • When an exception occurs, an object of some exception class is generated.
  • Two direct subclasses of Throwable: Exception and Error.
    • Class Error exceptions are those occur in JVM, not in the program.
    • Class Error exceptions are usually beyond programmer's control.
    • Class Exception exceptions are those from program activity, such as divide-by-zero, array out-of-boundary and file-not-found errors. These are called standard exceptions.
    • Class Exception exceptions should be handled in the program.
      • RuntimeException is an important subclass of Exception class and is used to represent various common types of runt-time errors.
  • Another type of exceptions are those thrown manually by using throw statement.

Exceptions Handling
  • try
    • If an exception occurs within the try block, it is thrown.
  • catch
    • If an exception is thrown by try block, it will be handled here in a predictable way.
  • throw
    • Use throw to manually throw an exception.
  • throws
    • Use throws clause in the declaration of a method to specify an exception could be thrown out of a method.
  • finally
    • Use finally block to specify any activity that must be executed upon exiting from a try block.


Monday, December 5, 2016

JAVA Tips and Gotchas.


  • Overloading - if the number of parameters are different, the return type can be different. But the return type cannot be used to differentiate the methods.
  • Static blocks is executed when the class is first loaded before the class can be used anywhere else, and thus can be used to initialize members before the class is constructed.
  • Recursive versions of many routines may execute a bit more slowly than their iterative equivalents because of the additional overhead of the additional method calls.
  • Inner class - a class inside a class but outside of any method.
  • Nested class - a class inside a method.
  • Autoboxing - occurs when a primitive type must be converted into an object. Vice versa, auto-unboxing happens whenever an object must be converted into a primitive type. (Say, between int and Integer)
  • Use 'import static' - called static import - to refer to static members of a class directly by their names, without  having to qualify them with the class name.
  • @Annotation (Metadata) - used by frameworks in development and deployment.
    • @Retention
    • @Target
    • @Inherited
    • @Override
    • @Deprecated
    • @SafeVarargs
    • @SuppressWarnings
    • @FunctionalInterface
  • In Java 8, you can specify a variable-length argument (varargs) by three periods (...)
Example
// If mixing normal and varargs parameters, the variable-length
// parameter must be the only and the last one.
static void myVarMethod (int a, double b, String c, int ... v) {
   for ( int i=0; i < v.length; i++ ) {
      system.out.println ("index-" + i + " = " + v[i]);
   }
}

public void main (String args[]) {
   myVarMethod (5, 1, 3);
   myVarMethod (2);
   myVarMethod ();
}


import static java.lang.Math.sqrt;
import static java.lang.Math.pow;
// Not a good practice as out.println is now ambiguous
import static java.lang.System.out;

// Now you can call these methods directly
double x = sqrt (pow(a, 4) - b*c);
double x = (-b + sqrt (pow(b, 2) - 4*a*c)) / (2*a);
out.println ("The solution is ", + x);


Java Generics
class ClassGeneric  {
   T obj;

   ClassGeneric (T o) {
      this.obj = o;
   }

   T getObj() {
      return obj;
   }

   void printType () {
      System.out.println ("Type of this object is " + 
         obj.getclass().getName() );
   }
}

// To use ClassGeneric
class Demo {
   public static void main (String args[]) {
      ClassGeneric  instanceOfT;
      instanceOfT = new ClassGeneric  (23);
      instanceOfT.printType();

      ClassGeneric  instanceOfStr = new ClassGeneric ("My String");
      instanceOfT.printType();
   }
}



Friday, December 2, 2016

JDBC demystified.


JDBC (Java DabaBase Connectivity) is an API interface for relational databases connections, such as Oracle RDBMS, SQL Server, MySQL, and Microsoft SQL DB.

In Java 7 includes JDBC 4.1 reduces the amounts of code required to work with databases. It is most commonly used as in web-based applications hosted in J2EE servers, including JBOSS, Tomcat, WebSphere.

Android has its own API SQLite to work with local database. Calls can be made from Android application to access larger databases through web services hosted by middleware servers.

The Spring application framework includes something called JDBC Template. It simplifies the amount of code using JDBC to talk to the database. Hibernate is the most popular data mapping APIs using an object-relational mapping mechanism. It represents the database structure with Java classes and objects. In the background it's still using JDBC to communicate with the database.

Applications that use the JDBC API require drivers. A JDBC driver is a software library that encapsulates the logic required to communicate between the application and the database management system. JDBC driver rules are defined in Java Standard Edition.

A driver library package will contain specific implementations of these Java interfaces.
  • Connection - which lets you connect to the database, 
  • ResultSet - which encapsulates data returned from the database, 
  • Statement - requests to the database
  • PreparedStatement - represent requests to the database
  • CallableStatement - represent requests to the database

Typically, a driver package can be downloaded from the database vendors themselves, a MySQL driver from MySQL an Oracle driver for Oracle, et cetera. Most of JDBC drivers will support these five interfaces.

There are four distinct types of drivers, distinguished by their architecture.

Type 1 JDBC Driver
  • JDBC-ODBC bridge driver + ODBC driver
    • it is the oldest type. 
    • Installed on the client system.
    • Started in the mid to late '90s when JDBC got started, ODBC or the Open Database Connectivity protocol was the dominant model for communicating with the database. 
    • At runtime, requests go from the application through the JDBC API to the Bridge driver from there to the ODBC driver and then to the database. 
  • Not fast, but it is dependable, 
  • Can work with any database for which an ODBC driver existed (pretty much every RDBMS) 
  • Cons: 
    • the ODBC Bridge driver is not 100% Java and therefore not portable between operating systems. 
    • working with two drivers and both have to be on the same computer as the application, so you have increased maintenance.
    • the ODBC driver has to match the database version, and so if database on the server, is updated, all the client applications have to be updated as well. 

Type 2 JDBC Driver
  • Native protocol API driver + Java driver
    • Both are installed on the client system just like the Bridge driver and ODBC driver.
  • Fast - because primarily working with native APIs, you get the best performance.

  • Not 100% Java so it's not portable between operating systems.
  • The native API driver has to be installed on the application client and maintained, and once again, if the database is updated, the client software has to be updated as well.

Type 3 JDBC Driver
  • Net protocol + Java driver
    • installed in multiple locations
    • 100% Java driver that's installed in the client along with the application
    • a middleware server which hosts its own application
  • requests go at runtime from the application to the Type 3 driver that's installed on the client, to the network to the middleware server and then to the database.
  • The middleware driver can be native, and so the communication between the middleware and the database can be very fast.
    • but at the cost of the maintenance challenges with more than one driver to maintain. 

Type 4 JDBC Driver
  • All 100% Java thin driver + 100% Java driver
    • the most common.
    • Only one driver package with Java application itself.
    • Can be on a client computer, in a web environment on J2EE server.
  • Requests go from the application to the driver that's on the client and then through JDBC through the thin driver to the database server if it's out on the web, or to the database file if it's on the local hard disk. 
  • With the Java thin driver, you're communicating directly from the application to the database. No additional layers to install or maintain so maintenance is greatly simplified. 
  • Cons: a different driver package is needed for each database to work with.

Working with Multiple Database Types in Single Application
  • Most applications will only use a single database type, but if you're working with more than one database management system, you'll need to provide multiple drivers. 
  • For example, you may have one MySQL database server hosted in the Cloud that is accessible over the web and an Apache Derby SQL Database that is initialized with local files and runs in the same Java process of the application.
  • Use Type 4 pure Java drivers to make the code as portable as possible. That's the idea of encapsulated applications.

Simple Type 4 Java driver example
private Connection getConnection (String dbName) {
    Connection connection = null;
    try {
        String dbDirectory = "./Resources";
        System.setProperty("derby.system.home", dbDirectory);
        String dbUrl = "jdbc:derby:" + dbName + ";create=true";

        connection = DriverManager.getConnection (dbUrl);
        return connection;
    }
    catch (SQLException e) {
        for (Throwable t : e) t.printStackTrace();
        System.err.println(e);
        return null;
    }
}

private void getResultSet (Connection cn) {
    String sql  = "SELECT * FROM Runners ";
        try ( PreparedStatement ps = cn.prepareStatement(sql);
              ResultSet rs = ps.executeQuery();
        ) {
              readRS(rs);
              disconnect();
        }
        catch (SQLException e) {
              System.err.println(e);
        }
}

private void readRS (ResultSet rs) {
    try {
        while (rs.next()) {
            ThreadRunner t = new ThreadRunner 
                (rs.getString(1), rs.getInt(2), rs.getInt(3));
            t.setName(rs.getString(1));
            runners.add( t );
         }
     }
     catch (SQLException e) {
         System.err.println(e);
     }
}

private boolean disconnect () {
    try {
        String shutdownURL = "jdbc:derby:;shutdown=true";
        DriverManager.getConnection(shutdownURL);
    }
    catch (SQLException e) {
        if (e.getMessage().equals(
             "Derby system shutdown."))
        return true;
    }
    return false;
}


Wednesday, November 30, 2016

Java Thread of an Applet.

Threading an Applet
public class RenewApplet extends java.applet.Applet
    implements Runnable
{
    Thread thread;
    boolean running;
    int renewInterval = 500;

    public void run() {
        while ( running ) {
            redoAction ();
            try {
                Thread.sleep( renewInterval );
            }
            catch ( InterruptedException e) {
                System.out.println( "Interrupted..." );
                return;
            }
        }
    }

    public void start() {
        if ( !running ) {
            running = true;
            thread = new Thread (this);
            thread.start();
        }
    }

    public void stop() {
        thread.interrupt();
        running = false;
    }
}



Sunday, November 13, 2016

JAVA IO and NIO.

java.io.file
  • path interface
    • get(String, String)
    • getFileName()
    • getName(int)
    • getNameCount()
    • getParent(), getRoot()
    • toAbsolutePath()
    • toFile()
  • paths class
    • exists(path)
    • notExists(path)
    • isReadable(path)
    • isWritable(path)
    • isDirectory(path)
    • isRegularFile(path)
    • size(path)
    • newDirectoryStream(path)
    • createFile(path)
    • createDirectory(path)
    • createDirectories(path)
  • files class
  • Exceptions
    • IOException
      • EOFException
      • FileNotFoundException
    • FileAlreadyExistsException
    • DirectoryNotEmptyException
import java.io.*;
import java.nio.file.*;

Path myp = Paths.get("./mydir");

String dir = "./src/db/files";
String filename = "db.txt";
Path dirPath = Paths.get(dir);
Path fPath = Paths.get(dir, filename);
File fName = fPath.toFile();

if (Files.notExists(fPath)) {
    Files.createDirectories(fPath);
}

// fPath.getFileName() -> return String
// fPath.toAbsolutePath() -> return String
// Files.isWritable(fPath) -> return boolean
// Files.exists(dirPath) -> return boolean
// Files.isDirectory (dirPath) -> return boolean

DirectoryStream dirs = Files.newDirectoryStream(dirPath);
for (Path p: dirs) {
    if (Files.isRegularFile (p) {
        System.out.println (" " + 
            p.getFileName());
    }
}

// Write data to file
// layered approach to get an object using constructor
try (PrintWriter out = new PrintWriter (
                       new BufferedWriter (
                       new FileWriter (productsFile))))
{
    out.println ("printout line");
}
catch (IOException e)
{
    System.out.println(e);
}

//Read data from the file
try (BufferedReader in = new BufferedReader(
                         new FileReader(myFile)))
{
    String line = in.readLine();
    while (line != null)
    {
        System.out.println(line);
        line = in.readLine();
        String[] columns = line.split("\t");
        String name = columns[0];
        String value = columns[1];
        int type = Integer.parseInteger(columns[2]);
        System.out.println(type);
    }
}
catch (IOException e)
{
    System.out.println(e);
}
// flush the buffer and close the input stream
in.close();

// Code that handles I/O exceptions
Path productsPath = Paths.get("products.txt");
if (Files.exists(productsPath)){  //defensive prog.
    //prevent the FileNotFoundeException
    File productsFile = productsPath.toFile();
    try (BufferedReader in = new BufferedReader(
                             new FileReader(productsFile)))
    {
        String line = in.readLine();
        //prevent EOFException
        while(line != null){
            System.out.println(line);
            line = in.readLine();
        }
    }
    catch (IOException e){
        System.out.println(e);
    }
} else{
    System.out.println(
              productsPath.toAbsolutePath() + " doesn't exist");
}

// ProductDAO interface
public interface ProductDAO
          extends ProductReader, ProductWriter,
          ProductConstants {}

import java.util.ArrayList;
public interface ProductReader
{
    Product getProduct(String code);
    ArrayList getProducts();
}

//The ProductWriter interface
public interface ProductWriter
{
    boolean addProduct(Product p);
    boolean updateProduct(Product p);
    boolean deleteProduct(Product p);
}
//The ProductConstants interface
public interface ProductConstants
{
    int CODE_SIZE = 4;
    int DESCRIPTION_SIZE = 40;
}


java.nio.file (JDK 1.7+)

Wednesday, November 9, 2016

JAVA Threads.

Basics
  • Threading in JAVA is built-in.
    • Java supports threading natively and at a high level.
    • Java concurrency utilities address common patterns and practices in multithreaded applications and raise them to the level of tangible Java APIs.
    • Not all applications need explicit use of threads or concurrency but most will use some features that is impacted by multithreading.
  • Threads are integral to client side Java APIs
    • GUI, sound.
      • Ex. using separate thread within JVM for drawing.
    • APIs with lots of I/O activities which are slow in nature.
  • Threads are not common and are discouraged on the server side in the context of application servers and web applications.
    • Server environment should control the allocation of CPU time/resources.
  • java.util.concurrent
  • You don't want to put the run() method directly in the object often time.
    • Make an adapter class that serves as the Runnable Object with the run() method and use that to call any method it wants to after the thread is started.
Concept
  • All execution in Java is associated with a Thread object, beginning with "main" thread.
  • New thread is create by java.lang.Thread class.
  • Thread Methods:
    • start
    • run
    • wait
    • sleep
    • notify
    • notifyAll
    • stop is deprecated and don't use it anymore.
  • Since Java has no pointer system to the method to tell it to run, we can't specify one directly. Instead, we use java.lang.Runnable interface to create or mark an object that contains a "runnable" method, which is run().
  • Thread begin its life by executing the run() method in a Runnable object (the target object) that was passed to the thread's constructor.
  • run() must be public, return void, takes no arguments and throws no checked exceptions.
  • Any class that contains an run() method can declare that it implements the Runnable interface.
    • An instance of this class is a runnable object that can serve as the target of a new thread.
Thread States
  • New
  • Runnable
  • Blocked
  • Waiting
  • Terminated

Example
class MyClass implements Runnable {
   boolean choice = ture;

   public void run() {
      while (choice) {
         // do what myClass has to...
      }
   }
}

MyClass item = new MyClass ("message");
thread myThread = new Thread (item);
myThread.start(); // This will cause run() in MyClass to execute

// To make an object to create and handle its own threads so to fit
// OOP concept, the following shows to have the actions in its
// constructor

class MyClass implements Runnable {
   boolean choice = ture;

   Thread myThread;
   public void MyClass (String name) {
      myThread = new Thread(this);
      myThread.start();
   }

   public void run() {
      while (choice) {
         // do what myClass has to...
      }
   }
}


Natual Born Thread Example
class Runner extends Thread {
    boolean running = true;

    public void run() {
        while (! isInterrupted()) {
            // by default, the Thread executes its own run() method when
            // we call the start() method
        }
    }
}

// to call Runner
Runner horse = new Runner ("horse");
horse.start();

// alternatively,
class Runner extends Thread {
    Runner (String name) {
        start();
    }
}

// Use adapter
class Runner {
    public void startRunner() {
        Thread myThread = new Thread (new Runnable () {
            public void run() { doAction(); }
        } );
        myThread.start();
    }

    private void doAction () {
        // do something...
    }
}

// Another way to write the code
new Thread () {
    public void run() { doAction(); }
}.start();


Thread Methods
  • Thread.sleep() -> require try/catch (InterruptedException e)
  • myThread.wait()
  • myThread.join()
  • myThread.interrupt()
  • stop(), suspend() and resume()

More about interrupt() method
Any thread that is not running (hard loop) must be in one of three states - sleep(), wait() or lengthy I/O operation - where it can be flagged to stop by interrupt() method. When a thread is interrupted, its interrupt status flag is set and this can happen at any time. Use isInterrupted() method to test this status like in the example above. You can also use isInterrupted(boolean toClear) as a flag and a signal to clear the interrupt status.

That said, this is historically a weak spot and it may not work correctly in all cases in early JVM, and more often with interrupting I/O calls blocked in a read() or write() method, moving bytes from a file or network. To address this in Java 1.4, a new I/O framework (java.nio) was introduced with one of its goals to address these problems. When the thread associated with an NIO operation is interrupted, the thread wakes up and the I/O stream (called a "channel") is automatically closed. (Check about the NIO package for more information.)


JAVA GUI 101.


  • import javax.swing.JFrame;
  • import javax.swing.ImageIcon;
  • import javax.swing.JLabel;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JLabel;

class showPicture {
   public static void main (String args[]) {
      JFrame frame = new JFrame();
      ImageIcon icon = new ImageIcon ("some.jpg");
      JLabel label = new JLabel (icon);
      frame.add(label);
      frame.setDefaultCloseOperation 
         (JFrame.EXIT_ON_CLOSE);
      frame.pack();
      frame.setVisible(true);
   }
}
import java.awt.Font;
import java.awt.GridLayout;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class myGui {
   public static void myGui {
      JFrame frame = new JFrame();
      JLabel label = new JLabel (icon);

      JLabel labels[] = {
         new JLabel ("Name"), new JLabel("Phone"),
         new JLabel ("Alice"), new JLabel("555-1234"),
         new JLabel ("Bob"), new JLabel("222-9876") 
      };

      frame.add(label[0]);
      frame.add(label[1]);

      JLabel boldLabel = new JLabel("Name");
      Font boldFont = boldLabel.getFont();
      Font plainFont = new Font(boldFont.getName(),
         Font.PLAIN, boldFont.getSize() );

      for (int i=2; i<8; i++) {
         labels[i].setFont(plainFont);
         frame.add(labels[i]);
      }
      frame.pack();
      frame.setvisible(true);
   }
}

package application;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class myJFXApp extends Application {
   @Override
   public void start (Stage primaryStage) {
      try {
         // BorderPane root = new Borderpane();
         Parent root = FXMLLoader.load (getClass().
                        getResource ("Root.fxml"));
         Scene scene = new Scene (root, 400, 400);
         scene.getStylesheets().
            add(getClass().getResource("application.css").
                             toExternalForm());
         primaryStage.setScene(scene);
         primaryStage.show();
      }
      catch (Exception e) {
         e.printStackTrace();
      }
   }

   public static void main (String[] args) {
      launch (args);
   }
}

import javafx.fxml.FXML;
import javafx.event.ActionEvent;
import javafx.scene.control.Textfield;

public class myJFXApp2...
{
   @FXML
   private TextField textfield;

   @FXML
   protected void onClick (ActionEvent event) {
      textField.setText (textField.getText().
         toUpperCase());
   }
}

Sunday, October 23, 2016

Java Data Structure - Collections.

Collections

  • Autoboxing
  • Array List vs Linked List vs Queue
  • Hash map vs Tree map
  • untyped collections and wrapper class with untyped collections
  • Wrapper classes for primitive types
    • Byte (byte)
    • Short (short)
    • Integer (int)
    • Long (long)
    • Float (float)
    • Double (double)
    • Character (char)
    • Boolean (boolean)
  • Java Collection Framework (Collections is the basic methods):
    • Lists (ordered) - ArrayList and LinkedList
    • Sets  (no dupicate) - HashSet
    • Mapes (key value pair) - HashMap and TreeMap
  • How it's different from Arrays
    • Collections are classes in Java API, array is a Java Language feature.
    • Collection classes have methods.
    • Collections are varied in size.
    • Collections are containers for objects, not for primitive types.
    • Collections can process without indices while indices are usually required to process arrays.
  • Generic collections
    • ex. ArrayList<String> al = new ArrayList<String>();

Example
// This is an untyped array list
ArrayList al = new ArrayList();
al.add("item1");
al.add("item2");
for (Object o : al)
    { ... }

ArrayList p = new ArrayList();
p.add (new className (...));

for (int i = 0; i < p.size(); i++) {
    className c = (className)p.get(i);
    ...
}

// untyped array list will result in compiler warning
// Note: file.java uses unchecked or unsafe operations.
// Note: Recompile with -Xlint:unchecked for details.


ArrayList Numbers = new ArrayList();
numbers.add(new Interger(1));
numbers.add("Mary");

//
// and gives run time errors:
// Exception in thread "main" java.lang.ClassCastException: java.lang.String 
// cannot be cast to java.lang.Integer at Demo.main(file.java:37)

        ArrayList numbers = new ArrayList();
           numbers.add(new Integer(1));
           numbers.add(new Integer(2));
           numbers.add("Mary");
           numbers.add("Helen");

        for (int i = 0; i < numbers.size(); i++)
           {
               int number = (Integer)numbers.get(i);
               System.out.println(number);
           }



// Use collection in a generic array

ArrayList<String> codes = new ArrayList<String>();
codes.add("Mary");
codes.add("Helen");
codes.add("Raymond");
codes.add(100); //compiler error, wrong type, has to be String
System.out.println(codes);


// Using wrappers for primitives
ArrayList Numbers = new ArrayList();
numbers.add(new Integer(1));


Classes and Packages

  • java.util.Arrays
  • java.util.ArrayList
    • Constructors
      • ArrayList<E>()
      • ArrayList<E>(intCapacity)
      • ArrayList<E>(Collection)
    • Methods:
      • add(object)
      • add(index, object)
      • clear()
      • contains(object)
      • get(index)
      • indexOf(object)
      • isEmpty()
      • remove(index)
      • remove(object)
      • set(index, object)
      • size()
      • toArray()


Java Data Structure - Arrays.

Arrays
  • Array is aggregate data types that contains elements of the items in an array.
  • Built-in in Java for primitives or references.
  • Jagged array vs Retangular array
  • Enhanced for loop
  • Array Class: java.util.Arrays
    • fill (arrayName, value) // Fill out all elements to "value"
    • fill (arrayName, fromIndex, toIndes_plus_1, value)
    • equals (array1, array2)
    • copyOf (arrayFrom,  length) // JDK 1.6+ shallow copy for ref type
    • copyOfRange (arrayFrom,  fromIndes, toIndex_plus_one) // JDK 1.6+
    • sort (arrayName) // MUST implememts Comparable Interface
    • sort (arrayName, fromIndex, toIndex)
    • binarySearch (arrayName, value) // Must have compareTo, sort or binarySearch method defined and must do Arrays.sort first for binarySearch

Example
String [] sArray;
String sArray[];
sArray = new String[];
sArray = new String[10];
sArray = new String[10][];

String [] SArray = new String[];
String sArray [] = {"Mary", "Susan", "Raymond"};
double [] dArray = new double[10];
double [] prices = {12.95, 11.95, 10.95};

final int TOTAL_STUDENTS = 50;
Scanner sc = new Scanner(System.in);
int totalStudents = sc.nextInt();
String [] StudentsA = new String[TOTAL_STUDENTS];
String [] StudentsB = new String[totalStudents];

StudentsA[0] = "Mary";

String[] name1 = {"Forrest Gump", "A Beautiful Mind"};
String[] name2 = {"Forrest Gump", "A Beautiful Mind"};
// if (name1 == name2) ==> gives "false"
// if (Arrays.equals(name1, name2) ==> gives "true"

Public interface Comparable {
    int compareTo (Object obj);
}

class Item implements Comparable {
    private int number;
    private String name;
    public Item (int n, String s) {
        this.number = n;
        this.name = s;
    }

    public int getNumber () {
        return number;
    }

    // This overriding compareTo compares the first field
    //     which is the item.number in this case
    //     can be altered by supplementing with another
    //     class implementing "Comparator" interface
    //     to compare by name
    //
    @Ovrride
    public int compareTo(Object o) {
        if (o instanceof Item) {
            Item i = (Item) o;
            if (this.getNumber() < i.getNumber()) {
                return -1;
            } else if (this.getNumber() > i.getNumber()) {
                return 1;
            }
            return 0; 
        }
    }
}

public class ItemOtherCompare implements Comparator {
    public int compare (Object o1, Objece o2) {
        int i1 = ((Item) o1).getOtherField();
        int i2 = ((Item) o2).getOtherField();
        if (i1 > i2) return 1;
        if (i2 > i2) return -1;
        return 0;
    }

    public boolean equals (Object o1, Object o2) {
        int i1 = ((Item) o1).getOtherField();
        int i2 = ((Item) o2).getOtherField();
        return (i1 == i2);
        return false;
    }
}

// Arrays.sort(items); // this will sort by first field data
// Arrays.sort(items, new ItemOtherCompare()); // this will sort by other field


Saturday, October 22, 2016

Java - Test Yourself.

 • Which of the following is an invalid list of elements in an array?
 "Joe", "Doug", "Anne"
 "Joe", 3, 25.5
 3, 17, 12
 12.3, 32.6, 21.7

 • What happens when the code that follows is executed?
 
   int[] nums = new int[4];
   for (int i = 0; i <= nums.length; i++)
   {
       nums[i] = i;
   }
   System.out.println(nums[2]);

 It prints “1” to the console.
 It prints “2” to the console.
 It prints “3” to the console.
It throws an ArrayIndexOutOfBoundsException.


 • What is printed to the console when the code that follows is executed?
 
   int[] years = new int[5];
   years[1] = 1992;
   for (int i = 0; i < years.length; i++)
   {
       years[i]++;
   }
   System.out.println(years[3]);

 “3”
 “4”
 “1”
 “1994”

 • Before you can sort an array of objects created from a class that you 
   defined, the class must implement the ____________ interface.

   (Comparable)

 • Which of the following, if any, is an invalid array declaration?

 String[] names = new String[5];
 String names[] = new String[5];
 String[] names = new String[0];
 String[] names = {"one", "two"};
 all are valid


 • How many rows are in the array that follows?
 
   Rental[][] transactions = new Rental[7][3];

 7
 6
 3
 2

 • What is the value of temps[2][1] after the code that follows is executed?
 
   double[][] temps = new double[10][5];
   for (int i = 0; i < temps.length; i++)
   {
       for (int j = 0; j < temps[i].length; j++)
       {
           temps[i][j] = j + i;
       }
   }
 1.0
 2.0
 3.0
 4.0


 • A two-dimensional array whose rows can have different numbers of 
   columns is called a ____________ array. 

   (jagged)


 • What is the value of the variable named len after the code that follows is executed?
 
   int[][] nums = { {1, 2, 3}, {3, 4, 5, 6, 8}, {1}, {8, 8} };
   int len = nums.length;

 1
 2
 3
 4
 5


 • What is the value of the third element in the array that follows?
 
   double[] percents = new double[4];
   percents[1] = 85.66;
   percents[2] = 56.98;
   percents[3] = 25.66;

 25.66
 56.98
 85.66
 a third element doesn’t exist


 • What is printed to the console when the code that follows is executed?
 
   int[][] points = { {8,3}, {4,3}, {7,2} };
   String s = "";
   for (int i = 0; i < points.length; i++)
   {
       Arrays.sort(points[i]);
       for (int j = 0; j < points[i].length; j++)
       {
           s += points[i][j];
       }
   }
   System.out.println(s);

 383427
 437283
 342738
 233478


 • What is the value of the string named lowest when the code that follows is executed?
 
   String[] types = {"lux", "eco", "comp", "mid"};
   Arrays.sort(types);
   String lowest = types[0];

 lux
 eco
 comp
 mid


 • What is the highest index value associated with the array that follows?
 
   byte[] values = new byte[x];

 0
 x
 x + 1
 x – 1
 can’t tell from information given


 • Consider the following code:
 
   double[] times = {3.56, 3.9, 2.6, 4.5, 2.4, 5.2};
   double[] bestTimes = new double[4];
   Arrays.sort(times);
   bestTimes = Arrays.copyOfRange(times, 1, 4);
 
 • What values are in the bestTimes array?

 2.4, 2.6, 3.56
 2.6, 3.56, 3.9
 2.4, 2.6, 3.56, 3.9
 2.6, 3.56, 3.9, 4.5


 • What does the x represent in the following declaration?
 
   BigDecimal[][] sales = new BigDecimal[x][y];

 the number of elements in each array
 the number of arrays in the sales array
 the number of tables in the sales array


 • What is the value of the variable named lists after the statements that follow are executed?
 
   String[][] names = new String[200][10];
   int lists = names.length;

 9
 10
 199
 200
 code doesn’t compile

 • A two-dimensional array whose rows all have the same number of 
   columns is called a ____________ array.  

   (rectangular)


 • What is printed to the console when the code that follows is executed?
 
   int[] values = {2, 1, 6, 5, 3};
   Arrays.sort(values);
   int index = Arrays.binarySearch(values, 5);
   System.out.println(values[index] - 1);

 “2”
 “3”
 “4”
 “5”
 “6”


 • Which of the following statements performs the same task as the 
   for loop in the code that follows?
 
   double[] times = new double[3];
   for (int i = 0; i < times.length; i++)
   {
       times[i] = 2.0;
   }

 Arrays.fill(times, 0, 3, 2.0);
 Arrays.fill(times, 1, 3, 2.0);
 Arrays.fill(times, 1, 4, 2.0);
 Arrays.fill(times, 0, 2, 2.0);


 • What is printed to the console after the code that follows is executed?
 
   int[][] types = new int[4][];
   for (int i = 0; i < types.length; i++)
   {
       types[i] = new int[i+1];
   }
   System.out.println(types[1].length);

 “2”
 “4”
 “1”
 “3”
 code doesn’t compile


 • Which of the following is an invalid two-dimensional array definition?

 double[][] values = new double[2][8];
 double values[][] = new double[8][2];
 double[][] values = new double[8][];
 double[][] values = new double[][8];What is printed to the console when the code that follows is executed?
 
   int[] nums = new int[2];
   int[] vals = new int[2];
   if (Arrays.equals(nums, vals))
       System.out.println("One");
   vals[1] = 2;
   nums = vals;
   if (Arrays.equals(nums, vals))
       System.out.println("Two");

 “One”
 “Two”
 “One” and “Two”
 nothing is printed to the console


 • What is the value of names[4] in the following array?
 
   String[] names = {"Jeff", "Dan", "Sally", "Jill", "Allie"};

 Sally
 Jill
 Allie
 name[4] doesn’t exist


 • An enhanced for loop can only be used

 to work with arrays that contain integers
 to work with one-dimensional arrays
 to work with all the elements of an array
 to work with jagged arrays


 • To use the binarySearch method of the Arrays class on an array of ints, 
   you must first

 create an Arrays object
 sort the array
 implement the Comparable interface
 override the equals method


 • What is the value of grades[1] after the following statements are executed?
 
   int[] grades = new int[2];
   grades[0] = 98;
   grades[1] = 84;
   grades = new int[2];

 98
 84
 0

 • What is the value of times[2][1] in the array that follows?
 
   double[][] times = { {23.0, 3.5}, {22.4, 3.6}, {21.3, 3.7} };

 3.7
 22.4
 3.5
 21.3
 3.6


 • Why won’t the following code execute?
 
   double values[] = new double[5];
   values[5] = 6;

 The brackets in the first statement are misplaced.
 An int value can’t be assigned to a double.
 The index is out of bounds.


 • Since the sort method of the Arrays class can sort String objects, what must be true of the String class?

 It contains a sort method.
 It implements the comparable method.
 It inherits a sort method.
 It implements the Comparable interface.


 • Which of the following statements gets the number of Customer objects 
   in the array that follows?
 
   Customer[] customers = new Customer[55];

 int size = customers.length();
 int size = customers.length;
 int size = customers.size();
 int size = Arrays.size(customers);


 • When you use an enhanced for loop with an array, you don’t 
   need to use a ________________ to iterate through the elements of the array.

   (counter variable or counter) 


 • Before you can use the binarySearch method of the Arrays class to 
   search for an element with a specified value in an array, you must ________________.  
   (sort the array)

 • Each row of a two-dimensional array is stored as a/an ____________. 
   (array)

 • Consider the following code:
 
   double[] times = {3.56, 3.9, 2.6, 4.5, 2.4, 5.2}; 
   double[] bestTimes = new double[4]; 
   Arrays.sort(times); 
   bestTimes = Arrays.copyOfRange(times, 1, 4); 
 
   What is the length of the bestTimes array?

 6
 5
 4
 3


 • What is the value of the variable named len after the code that follows is executed?
 
   int[][] nums = { {1, 2, 3}, {3, 4, 5, 6, 8}, {1}, {8, 8} };
   int len = nums[2].length;

 1
 2
 3
 4
 5


 • Consider the following code:
 
   double[] times = {3.56, 3.9, 2.6, 4.5, 2.4, 5.2};
   double[] bestTimes = new double[4];
   Arrays.sort(times);
   bestTimes = Arrays.copyOfRange(times, 1, 4);
 
   What values are in the times array after the code is executed?

 2.4, 2.6, 3.56, 3.9, 4.5, 5.2
 3.56, 3.9, 2.6, 4.5, 2.4, 5.2
 2.4, 2.6, 3.56
 2.4, 2.6, 3.56, 3.9


 • What is the value of nums[2] after the following statements are executed?
 
   int[] values = {2, 3, 5, 7, 9};
   int[] nums = values;
   values[2] = 1;

 3
 1
 5
 0






Sunday, October 16, 2016

Java Gotchas.


  • A default constructor without any parameters has to be provided if you have another constructor with parameters.
  • "!" only applies to booleans.
  • All interface methods have to be defined when you implement the interface into a class.
  • When you assign sub-class to parent-class handle, the compilation will pass but the methods available are in parent class code. It is during the run-time, the reference would actually point to the child class's overriding methods.
  • Constructors should never have static members.
  • During compilation, a stack of codes/data/pointers are built. The real memory space is allocated in the "Heap".
  • Static {}, namely initial static block will be called before any static methods.

Sunday, October 9, 2016

OOP Programming Terms.


CRUD versus REST

CRUD means the basic operations to be done in a data repository. You directly handle records or data objects; apart from these operations, the records are passive entities. Typically it's just database tables and records. It is a simple term that was abbreviated because it's a common feature in many applications, and it's easier to say CRUD. It describes the 4 basic operations you can perform on data (or a resource). Create, Read, Update, Delete.

REST, on the other hand, operates on resource representations, each one identified by an URL. These are typically not data objects, but complex objects abstractions. It is more of a named practice just like AJAX but not a technology in itself. It encourages use of capabilities that have long been inherent in the HTTP protocol, but seldom used. When you have a URL (Uniform Resource Locator) and you point your browser to it by the address line, you're sending an HTTP request. Each HTTP request contains information that the server can use to know which HTTP response to send back to the client that issued the request.

Each request contains a URL, so the server knows which resource you want to access, but it can also contain a method. A method describes what to do with that resource.

But this "method" concept wasn't used very often.

Usually, people would just link to pages via the GET method, and issue any type of updates (deletions, insertions, updates) via the POST method.

And because of that you couldn't treat one resource (URL) as a true resource in itself. You had to have separate URLs for deletion, insertion or update of the same resource.

For example, a resource can be a user's comment. That means not only a record in a 'comment' table, but also its relationships with the 'user' resource, the post that comments, maybe another comment that it answers.

Operating on the comment isn't a primitive database operation, it can have significant side effects, like firing an alert to the original poster, or recalculating some gamelike 'points', or updating some 'followers stream'.

Also, a resource representation includes hypertext (check the HATEOAS principle), allowing the designer to express relationships between resources, or guiding the REST client in an operation's workflow.

In short, CRUD is a set primitive operations (mostly for databases and static data storages), while REST is a very-high-level API style (mostly for webservices and other 'live' systems).

a single URL describes a single resource. A single post is a single resource. With REST you treat resources the way they were meant to be treated. You're telling the server which resource you want to handle, and how to handle it.

There are many other features to "RESTful architecture", which you can read about in Wikipedia, other articles or books, if you're interested. There isn't a whole lot more to CRUD itself, on the other hand.


Example
http://...com/posts/create- POST request  -> Goes to posts.create() method in the server
http://...com/posts/1/show- GET request  -> Goes to posts.show(1) method in the server
http://...com/posts/1/delete - POST request  -> Goes to posts.delete(1) method in the server
http://...com/posts/1/edit- POST request  -> Goes to posts.edit(1) method in the server
With REST, you create forms that are smarter because they use other HTTP methods aside of POST, and program your server to be able to distinguish between methods, not only URLS. So for example:
http://...com/posts - POST request  -> Goes to posts.create() method in the server
http://...com/posts/1 - GET request  -> Goes to posts.show(1) method in the server
http://...com/posts/1 - DELETE request  -> Goes to posts.delete(1) method in the server
http://...com/posts/1 - PUT request  -> Goes to posts.edit(1) method in the server

CDN (Content Distribution Network)
  • Several companies, including Google and Microsoft, allow you to link to jQuery, and some other common libraries, and get that file directly from their servers.
  • This is more reliable and speedier.
  • Spreading the requests across different servers can improve performance.
  • Caching benefits - shared sites got cached on the client machine.
  • Remove "http:" to avoid complaints of encryption or not.
Example
// Linking to Google CDN
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>
// remove http:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js">
</script>

Abstract Factory pattern vs Factory Method pattern

Abstract Factory vs. Factory Method

The methods of an Abstract Factory are implemented as Factory Methods. Both the Abstract Factory Pattern and the Factory Method Pattern decouples the client system from the actual implementation classes through the abstract types and factories. The Factory Method creates objects through inheritance where the Abstract Factory creates objects through composition.

The Abstract Factory Pattern consists of an AbstractFactory, ConcreteFactory, AbstractProduct, ConcreteProduct and Client.

How to implement

The Abstract Factory Pattern can be implemented using the Factory Method Pattern, Prototype Pattern or the Singleton Pattern. The ConcreteFactory object can be implemented as a Singleton as only one instance of the ConcreteFactory object is needed.

Factory Method pattern is a simplified version of Abstract Factory pattern. Factory Method pattern is responsible of creating products that belong to one family, while Abstract Factory pattern deals with multiple families of products.

Factory Method uses interfaces and abstract classes to decouple the client from the generator class and the resulting products. Abstract Factory has a generator that is a container for several factory methods, along with interfaces decoupling the client from the generator and the products.

When to Use the Factory Method Pattern

Use the Factory Method pattern when there is a need to decouple a client from a particular product that it uses. Use the Factory Method to relieve a client of responsibility for creating and configuring instances of a product.

When to Use the Abstract Factory Pattern

Use the Abstract Factory pattern when clients must be decoupled from product classes. Especially useful for program configuration and modification. The Abstract Factory pattern can also enforce constraints about which classes must be used with others. It may be a lot of work to make new concrete factories.


Sunday, October 2, 2016

Java Math.

Math
  • Math.round()

BigDecimal

   java.math.BigDecimal
  • BigDecimal (int)
  • BigDecimal (double)
  • BigDecimal (long)
  • BigDecimal (String) // better
  • Methods
    • add (value)
    • compareTo(value)
    • divide(value, scale, rounding-mode)
    • multiply(value)
    • setScale(scale, rounding-mode)
    • subtract(value)
    • toString()

   java.math.RoundingMode
  • HALF_UP
  • HALF_EVEN
import java.math.*; // imports all classes and 
                    // enumerations in java.math

// convert subtotal and discount percent to 
BigDecimal BigDecimal decimalSubtotal =
    new BigDecimal(Double.toString(subtotal)); 
decimalSubtotal =
    decimalSubtotal.setScale(2, RoundingMode.HALF_UP); 
BigDecimal decimalDiscountPercent =
    new BigDecimal(Double.toString(discountPercent));

// calculate discount amount 
BigDecimal discountAmount =
    decimalSubtotal.multiply(decimalDiscountPercent); 
discountAmount = discountAmount.setScale(
    2, RoundingMode.HALF_UP);
// calculate total before tax, sales tax, and total
BigDecimal totalBeforeTax =
   decimalSubtotal.subtract(discountAmount);
BigDecimal salesTaxPercent =
   new BigDecimal(SALES_TAX_PCT);
BigDecimal salesTax =
   salesTaxPercent.multiply(totalBeforeTax);
salesTax = salesTax.setScale(2, RoundingMode.HALF_UP);
BigDecimal total = totalBeforeTax.add(salesTax);

// Create another BigDecimal object from existing BigDecimal Object
BigDecimal total2 = new BigDecimal(total.toString());

Java OOP.


  • Java String is immutable object

Using "this"
public class MyClass {
     private final String value;
     private final String type;

     public MyClass(int x){
         this(Integer.toString(x), "int");
     }

     public MyClass(boolean x){
         this(Boolean.toString(x), "boolean");
     }

     public String toString(){
         return value;
     }

     public String getType(){
         return type;
     }

     private MyClass(String value, String type){
         this.value = value;
         this.type = type;
     }
}

Java Exceptions.


Exception Basics

Order of Catch Matters
userChoice = 0; //initialize it
    try {
        userChoice = getInput(inputReader); 
    }// order of catch is important

    catch (NullPointerException e) { 
        System.out.println("Message:"+e.getMessage());
    }
    catch (MyOutOfRangeException e) {
        System.out.println("Message: " + e.getMessage()); 
    }
    catch (Exception e) {
        System.out.println("Catch all Exception"); 
    }

    finally { //always exectued with our without catch
        if (userChoice==0) //still has initial value
            System.out.println("Please try again ..."); 
        else
            System.out.println("Your choice is:"+ userChoice); 
    }
 

Prevent Exceptions As Possible
// Get valid numeric format
public static double getDouble(Scanner sc, String prompt) {
          double d = 0.0;
          boolean isValid = false;
          while (isValid == false)
          {
              System.out.print(prompt);
              if (sc.hasNextDouble())
              {
                  d = sc.nextDouble();
                  isValid = true;
              }
              else {
                  System.out.println(
                      "Error! Invalid number. Try again.");
              }
              sc.nextLine(); // discard any other data
           }
           return d; 
}

// Get valid numeric format
public static double getDoubleWithin (
        Scanner sc,
        String prompt,
        double min, double max )
{
    double d = 0.0;
    boolean isValid = false;
    while (isValid == false) {
        d = getDouble(sc, prompt);
        if (d <= min) {
            System.out.println(
                "Error! Number must be greater than " + 
                min + ".");
        }
        else if (d >= max){
            System.out.println(
                "Error! Number must be less than " +
                max + ".");
        } 
        else
            isValid = true;
    }
    return d; 
}

Scanner sc = new Scanner(System.in);
double subtotal1 = getDouble(sc, "Enter subtotal: "); 
double subtotal2 = getDoubleWithinRange(
                              sc,
                             "Enter subtotal: ",
                             0,
                             10000);


Tuesday, September 27, 2016

Java - How to Write to a File.

public class FileTrace implements Trace {
          
      private java.io.PrintWriter pw;
      private boolean debug;
      public FileTrace() throws java.io.IOException {
            // a real FileTrace would need to obtain the filename
            // somewhere for the example I'll hardcode it
            pw = new java.io.PrintWriter
                ( new java.io.FileWriter( "c:\trace.log" ) );
      }
      public void setDebug( boolean debug ) {
            this.debug = debug;
      }
      public void debug( String message ) {
            if( debug ) {  // only print if debug is true
                  pw.println( "DEBUG: " + message );
                  pw.flush();
            }
      }
      public void error( String message ) {
            // always print out errors
            pw.println( "ERROR: " + message );
            pw.flush();
      }
}

public class SystemTrace implements Trace {
      private boolean debug;
      public void setDebug( boolean debug ) {
            this.debug = debug;
      }
      public void debug( String message ) {
            if( debug ) {  // only print if debug is true
                  System.out.println( "DEBUG: " + message );
            }
      }
      public void error( String message ) {
            // always print out errors
            System.out.println( "ERROR: " + message );
      }
}

// To use the class
SystemTrace log = new SystemTrace();
log.debug( "entering log" );
Factory Method

// To use factory method
public class TraceFactory {
      public static Trace getTrace() {
            return new SystemTrace();
      }
}
Trace log = new TraceFactory.getTrace();

// A better factory method
public class TraceFactory {
      public static Trace getTrace() {
            try {
                  return new FileTrace();
            } catch ( java.io.IOException ex ) {
                  Trace t = new SystemTrace();
                  t.error( "could not instantiate FileTrace: " 
                          + ex.getMessage() );
                  return t;
            }
      }
}

Object Creation Initialization.

Initialization happens when,
  1. A class is loaded.
  2. A class is created/instantiated.
JVM does the following when it encounters class instantiation,
  1. Allocates memory space for a new object, with room for the instance variables.
  2. Process the constructor. If the constructor has parameters, JVM creates variables for the parameters and assigns them values passed in.
  3. If the invoked constructor begins with a call to another constructor by using "this" keyword, JVM processes the called constructor.
  4. Initialize instance and instance variable for this class. Undefined instance variables will be assigned default values.
  5. Executes the rest of the invoked constructor.
  6. Returns a reference variable that refers to the newly created object
Note:
  • Static initialization is performed first before any instantiation takes place, even if the code comes later in the program.

EXAMPLE
package mypackage;

public class MyClass {
    int x = 3;
    int y;

    // instance initialization code block
    {
        y = x*2;
        System.out.println (y);
    }

    // static initialization code happens first
    static {
        System.out.println ("Static initialization, this will come first.");
    }

    public static void main (String[] args) {
        MyClass inst0 = new MyClass();
        MyClass inst1 = new MyClass();
    }
}


The instance initialization code can go unnoticed when the code gets bigger. A better practice to write initialization code is to put it in the constructor so it's more noticeable.
package mypackage;

public class MyClass2 {
    int x = 3;
    int y;

    // instance initialization code in the constructor
    public MyClass2 () {
        y = x*2;
        System.out.println (y);
    }

    // static initialization code happens first
    static {
        System.out.println ("Static initialization, this will come first.");
    }

    public static void main (String[] args) {
        MyClass2 inst0 = new MyClass2();
        MyClass2 inst1 = new MyClass2();
    }
}


If you have more than one constructor and each calls the same block of code, wrap the common initialization code in a method and let the constructors call it.
package mypackage;

public class MyClass3 {
    int x = 3;
    int y;

    // Two constructors
    public MyClass3 () {
        init();
    }
    public MyClass3 (int x) {
        this.x = x;
        init();
    }

    // instance initialization code in a method
    private void init () {
        y = x*2;
        System.out.println (y);
    }

    // static initialization code happens first
    static {
        System.out.println ("Static initialization, this will come first.");
    }

    public static void main (String[] args) {
        MyClass3 inst0 = new MyClass3();
        MyClass3 inst1 = new MyClass3();
    }
}


In C++, you must destroy objects after use. Java comes with a garbage collector which destroys unused objects and frees memory space.


Monday, September 26, 2016

Java Packages.


Import and Static import

There are some Java classes that contain static final fields. One of them is the java.util.Calendar class, that has the static final fields representing days of the week. To use a static final field in the Calendar class, you must first import the Calendar class.
import java.util.Calendar;
if (today == Calendar.SATURDAY) {
}

// You can also import static fields using the import static keywords.
import static java.util.Calendar.SATRDAY;

java.lang.Object

   Methods:
  • clone
  • equals
  • finalize
  • getClass
  • hashCode
  • wait, notify, notifyAll

java.lang.String
  • Java string is immutable object
  • String()
  • String (arrayName)
  • String (arrayName, intOffset, intLength)
  • String Array Methods:
    • length()
    • indexOf (StringName)
    • indexOf (StringName, startIndex)
    • lastIndexOf (StringName)
    • lastIndexOf (StringName, startIndex)
    • trim() // remove all whitespaces before and after the String, but not within between
    • substring (startIndex)
    • substring (startIndex, endIndex)
    • replace (oldChar, newChar)
    • split (delimiter)
    • charAt (index)
  • String Compare Methods
    • equals (String)
    • eqaulsIgnoreCase (String)
    • startsWith (String)
    • startsWith (String, startIndex)
    • endsWith (String)
    • isEmpty()
    • compareTo (String)
      • if returns '0': true equal
      • if returns positive: longer or greater
      • if returns negative: shorter or less
    • compreToIgnoreCase (String) 
      • ref to above
  • Two mutable String API:
    • StringBuilder
      • faster but not thread-safe
    • StringBuffer
      • dated, too slow, StringBuilder is faster
      • thread-safe
String message = new String ("Java is cool!");
String s1 = "Java";
String s2 = "Java";
if (s1 == s2) { // returns true
}

String s1 = new String ("Java");
String s2 = new String ("Java");
if (s1 == s2) { // returns false
}

// if s1 == null without checking, it will generate a runtime error
// also the order matters so is the use of "&&" logical operator
// using "&&" will prevent JVM to evaluate the s1.equals()
// second expression and generate an error

if (s1 != null && s1.equals("Java")) // returns true
{
}
// Another coding style, no need to check if "Java" is null
if ("Java".equals (s1)) {
}

// Create a string from an array of characters
char cityArray[] = {'D','a','l','l','a','s'}; 
String cityString1 = new String(cityArray); 
String cityString2 = new String(cityArray, 0, 3);

// Create a string from an array of bytes
byte cityArray[] = {68, 97, 108, 108, 97, 115}; 
String cityString1 = new String(cityArray); 
String cityString2 = new String(cityArray, 0, 3);


Java Exception

   Keyword:
  • try
  • catch
  • throw
  • throws
  • finally
import java.io.*;
import java.util.List;
import java.util.ArrayList;

void method1 () {
    try {
        method1();
    }
    catch (Exception e) {
    }
}
void method2 () throws Exception {
    method3();
}
void method3 () throws Exception {
    method4();
}
public static int getInput (Scanner in) 
    throws NullPointerException, MyOutOfRangeException {
    throw new Exception();
}
class MyOutOfRangeException extends Exception {
    MyOutOfRangeException(String message){ 
        super(message); // call the base class constructor
    } 
}
public static int getInput2 (Scanner in) 
    throws NullPointerException, MyOutOfRangeException {

    int userChoice = 0;

    if (in == null) {
        throw new NullPointerException("Null Scanner");
    }
    System.out.println(
        "Please enter a value between 1 to 5");
    userChoice = Integer.parseInt(in.next());
    if (userChoice < 1 || userChoice > 5) {
        throw new MyOutOfRangeException
            ("Please enter value between 1 to 5");
    }
    return userChoice;
}

// Code to prevent NullPointerException
if (customerType != null)
{
    if (customerType.equals("R"))
        discountPercent = .4;
}


java.lang.Scanner

  • getInt() 
  • getDouble() 
  • getDoubleWithRange() 
  • hasNext() 
  • hasNextInt() 
  • hasNextDouble() 
  • next() 
  • nextLine()

if (sc.hasNextDouble()) {
    subtotal = sc.nextDouble();
}
else {
    sc.nextLine();    // discard the entire line
    System.out.println(
        "Error! Invalid number. Try again.\n");
    continue;         // jump to the top of the loop
}

// Code to get a valid double value within range
Scanner sc = new Scanner(System.in);
double subtotal = 0.0;
boolean isValid = false;
while (isValid == false) {
        // get a valid double value
        System.out.print("Enter subtotal: ");
        if (sc.hasNextDouble()) {
            subtotal = sc.nextDouble();
            isValid = true;
        }
        else
        {
            System.out.println(
                "Error! Invalid number. Try again.");
        }
        sc.nextLine();
                // discard any other data entered on the line

        // check the range of the double value
        if (isValid == true && subtotal <= 0) {
            System.out.println(
                "Error! Number must be greater than 0.");
            isValid = false;
        }
        else if (isValid == true && subtotal >= 10000)
        {
            System.out.println(
                "Error! Number must be less than 10000.");
            isValid = false;
        } 
}



Good Practices!

  • Organize your constants, put all constants in a class.
    This class most often does not have methods or other fields and is never instantiated.
package AllConstants;
public class Months {
public static final int JANUARY = 1;
public static final int FEBRUARY = 2;
public static final int MARCH = 3;
public static final int APRIL = 4;
public static final int MAY = 5;
public static final int JUNE = 6;
public static final int JULY = 7;
public static final int AUGUST = 8;
public static final int SEPTEMBER = 9;
public static final int OCTOBER = 10;
public static final int NOVEMBER = 11;
public static final int DECEMBER = 12;
}

// Get the representation of January by
int thisMonth = Months.JANUARY;


More About "javac" et cetera ...


javac - Java compiler
javac [ options ] [ sourcefile.java ] [ @filelist ]
  • For large number of source files, list all file names in @filelist
  • In <filelist>, separate files with space or line breaks.
  • Inner class definitions produce additional class files.
  • [ options ]
-classpath pathname Set the user class path
-d directory Set the destination directory for class files
-g Generate all debugging information, including local variables.
-g:none Does not generate any debugging information.
-g:source Generate source file debugging information
-help Prints a synopsis of standard options
-nowarn Disables warning messages. (Same as -Xlint:none)
-sourcepath path Specify the source code path to search for class or interface definitions
-verbose Verbose output.
-X Display information about non-standard options and exit.

EXAMPLE
// Create a file named "options" containing:
//
//    -d classes
//    -g
//    -sourcepath /java/pubs/src/share/classes
//
// Create a file named "classes" containing:
//
//    MyClass1.java
//    MyClass2.java
//    MyClass3.java
//
// Run javac as follows:
//    javac @options @classes
//    javac @path1/options @path2/classes
//
% ls path1
   options
% cat path1/options
   -d classes
   -g
   -sourcepath /java/pubs/src/share/classes
% ls path2
   classes
% cat path2/classes
   MyClass1.java MyClass2.java MyClass3.java
% javac @path1/options @path2/classes
% java -classpath classes MyClass1
...

JVM

  1. Invoking the class's main method.
  2. There are 3 things that JVM do:
    • Loading
    • Linking
      • Verification - Checks the binary code with Java's semantic requirements.
      • Preparation - Prepares the class for execution by allocating memory space for data and static variables.
      • Resolution (optional) - Checks if the class references other classes/interfaces and find/load them. Checks are done recursively.
    • Initialization
      • Initializes static variables and execute static initializers in static blocks. This is done before the main method is executed. Before the class can be initialized, its parent class has to be loaded, linked and initialized first so this process happens recursively to the top most class.

JDK
  • javac - Java compiler
  • jar - Java Archive
  • javap - Java Disassembler
  • jdb - Java Debugger