Posts by Chang Park

[String] concat() vs. +

Screen Shot 2016-08-07 at 4.44.23 PM

concat() and + both add up strings. It looks same, but + do one more step. As seen below, + will create string builder and append the strings inside, and then it will give the string. So, concat() is less expensive.

/*      Using + sign      */
String myStr = "str";
myStr += "end";

// Same as above
String myStr = "str";
myStr = new StringBuilder().append(myStr).append("end").toString();

 

/*      Using concat()     */
String myStr = "str";
myStr = myStr.concat("end");

 

DHCP

Definition & steps

DHCP stands for Dynamic Host Configuration Protocol. When DHCP assigns an IP address, it actually leases that connection identifier to the user’s computer for a specific amount of time. The default lease is five days.

Pros

  • Because there is certain lease duration, if not using after the duration, they will automatically collect it after the lease. So, it can be used for other computer.
  • Because you don’t need to set the IP one by one, if you move to other office and connect to the that network, it will automatically assign an IP for you.

Screen Shot 2016-08-07 at 12.36.24 PM

How DHCP works

  • Discover: client computer sends a broadcast request looking for a DHCP server to answer.
  • Router directs the DISCOVER packet to the correct DHCP server.
  • The server receives the DISCOVER packet. Based on availability and usage policies set on the server, the server determines an appropriate address (if any) to give to the client.
  • Offer: The server then temporarily reserves that address for the client and sends back to the client an OFFER packet, with that address information.
  • Request: Letting the server know that it intends to use the address.
  • ACK: Confirming that the client has a been given a lease on the address for a server-specified period of time.

 

 

Error & Exception

Error & Exception

Screen Shot 2016-08-06 at 10.39.14 PM

Error is thrown by JVM in a scenario which is fatal and there is no way for the application program to recover from that error.

  • Unchecked type: Errors happen at run time. They will not be known to compiler
  • Cannot recover
  • eg. java.lang.StackOverflowError, java.lang.OutOfMemoryError

Exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime.

  • Unchecked & Checked type: checked exceptions are known to compiler where as unchecked exceptions are not known to compiler because they occur at run time.
  • Can recover from exceptions by handling then through try-catch blocks.

 

Types of exceptions

  • Checked Exception: The classes that extend Throwable class except RuntimeException and Error are known as checked exceptions. Checked Exceptions are checked at compile-time.
    • e.g.IOException, SQLException etc.
  • Unchecked Exception: Unchecked exceptions are not checked at compile-time rather they are checked at runtime.
    • e.g. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException etc.

 

Unchecked Exception scenarios

  • ArithmeticException: If we divide any number by zero, there occurs an ArithmeticException.
int a = 50/0;

 

  • NullPointerException: If we have null value in any variable, performing any operation by the variable occurs an NullPointerException.
String s = null;
System.out.println(s.length());

 

  • NumberFormatException: The wrong formatting of any value, may occur NumberFormatException. Suppose I have a string variable that have characters, converting this variable into digit will occur NumberFormatException.
String s = "abc";
int i = Integer.parseInt(s);

 

  • ArrayIndexOutOfBoundsException: If you are inserting any value in the wrong index, it would result ArrayIndexOutOfBoundsException as shown below.

int a[] = new int[5];

a[10] = 50;

 

Handling checked exceptions

Due to compilation error, checked exceptions need to be handled by programmer. There are two ways to handle these exceptions.

  • Throw when declaring method
  • Try, catch, and finally inside the method

 

Throw when declaring method: Toss the exception handling to user when using the method.

public void connect() throws MyException{
   // try ~ catch ~ finally will not be used
}

 

Try, catch, and finally inside the method: Handling exception inside the method

public void connect(){

   try{
      // Do work here
      System.out.println(10/0);
   } catch (MyException e){
      // Catch lower Exception first
   } catch (Exception e){
      // Highest Exception at the end

      // There are three ways to see the excetption
      e.printStackTrace();
      System.out.println(e.toString());
      System.out.println(e.getMessage());
   } finally {
      // Code on here will be always printed
   }

}
  • e.printStackTrace(): Name of the Exception, Message of the Exception, Stack trace
    • On example code above:
java.lang.ArithmeticException: /by Zero
   at main()
  • e.toString(): Name of the Exception, Message of the Exception
    • On example code above:
java.lang.ArithmeticException: /by zero
  • e.getMessage(): Message of the Exception
    • On example code above:
/by zero

Creating your own Exception

Extends Exception classe: you can make the most suitable exception for your program.

public class MyException extends Exception{
   public Myexception(String msg){
      super(msg);
   }
}

 

 

 

Wait() vs. Sleep()

Wait and sleep method are completely different to each other

  • wait() & notify(): method for inter thread communication.
  • sleep(): introducing small pause during thread execution.

Screen Shot 2016-07-26 at 2.49.35 PM

wait() & notify()

  • wait() method puts a thread on wait
    • For example, in Producer Consumer problem, producer thread should wait if Queue is full or Consumer thread should wait if Queue is empty.
  • notify()  & notifyAll() method is used to wake up waiting thread by communicating that waiting condition is over now
    • For example, once producer thread puts an item on empty queue it can notify Consumer thread that Queue is not empty any more.
    • notify(): wakes up one thread
    • notifyAll(): wakes up all the threads (use this when you are not sure which one to use)
Example...
/*
   Until pizza arrives, eatPiazza will in wait
   If pizzaGuy() executed, it will wake up eatPiazza()
   by using notifyAll();
*/
class MyHouse{
   private boolean pizzaArrived = false;
   
   public void eatPizza(){
      synchronized(this){
         while(!pizzaArrived){
            wait();
         }
      }
      System.out.println("yumyum...");
   }

   public void pizzaGuy(){
      synchronized(this){
         this.pizzaArrived = true;
         notifyAll();
      }
   }
}

sleep()

  • sleep() hold a lock, doesn’t release any lock or monitor while sleeping.
  • When a Thread goes to Sleep it can be either wake up normally after sleep duration elapsed or it can be woken up abnormally by interrupting it.
Example...
/*
   It will print out count string one at a time
   with a 3 seconds term
*/
public class Example{
   public static void main(String[] args){
      String count[] = ("One","Two","Three","Four","Five");

      for(int i=0; i<count.length;i++){
         Thread.sleep(3000);             // sleep for 3 seconds
          System.out.println(count[i]);  // printout count string
      }
   }
}

Synchronized in Thread

synchronized

  • While running multi-threads, there will be a significant problem when those threads try to use same resource.
    • For example, multiple people try to deposit money into the same account. Let’s say initial balance is $0. If 5 people are accessing at the same time, they all will see $0 as an account balance. Then, after all people’s deposit of $500 each, it will have $500 for total deposit. This is because they accessed at the same time, and they all updated balance as $500. However, the balance should be $2,500.
  • So, lock is needed to avoid other thread trying to use the same resource at the same time.
  • That lock can be done by Synchronized.

There is two ways to use synchronized.

  • Synchronized method
public synchronized /* Method name  */(){
   ...
}
  • Synchronized block
synchronized( /* Object to be shared */ ){
   ...
}

Primitive type vs. Reference type

Primitive vs Reference Type Java

Primitive type

  • Basic types for characters, different kinds of integers, and different kinds of floating point numbers (numbers with a decimal point), and also types for the values true and false – char, int, float, and bool. All of these basic types are known as primitive types.
  • The value of the variable is stored in the memory location assigned to the variable. For example, if an integer variable is declared as “int a = 5″, then when we look at the memory location of “a”, there will be a “5” stored there just as expected.

Reference type

  • You might be confused by all the different terminology used. However, class types, object types, and reference types all mean the exact same thing.
  • A variable of a reference type only stores the memory address of where the object is located. For example, “SomeClass anObject”, then when we look at “anObject” in memory, it just stores an address of another place in memory where all the details of “anObject” reside. This memory address is called a reference to the object.

 

 

System.nanoTime()

  • It will give you current time in nanoseconds(precise).
  • Usually used for measuring performance of the code.
  • To convert it to in seconds, divide it by 10^9 (1 sec = 1 nano second * 10 ^ 9)

Example…

long before = System.nanoTime();
//
// Some work goes to here
//
long after = System.nanoTime();

// Prints out time taken in nano seconds
System.out.println("Time taken: "+ (after-before) );  

Runnable vs. Thread

Difference

For both, you need to Override run() method to be created as a new thread by start() call.

thread runnable

implements Runnable (preferred way)

  • it shares the same object to multiple threads.
  • you can save a space for your class to extend any other class in future or now.

extends Thread

  • Each of your thread creates unique object and associate with it.
  • You can’t extend any other class which you required. (Java does not allow inheriting more than one class).

Runnable

  • You need to make Thread and put the ExampleThread in the parameter, and call .start()
public class ExampleThread implements Runnable{
   public void run(){
      System.out.println("Thread running");
   }
}

public class App{
   public static void main(String[] args){
      ExampleThread ex = new ExampleThread();
      Thread t = new Thread(ex);    // Runnable in Thread parameter
      t.start();
   }
}

thread

  • You can directly use .start(), because ExampleThread extends Thread
public class ExampleThread extends Thread{
   public void run(){
      System.out.println("Thread running");
   }
}

public class App{
   public static void main(String[] args){
      ExampleThread ex = new ExampleThread();
      ex.start();
   }
}

 

Types of Casting & instanceof

upcasting-downcasting

You must understand, that by casting you are not actually changing the object itself, you are just labeling it differently.

upcasting

  • Object of child class is assigned to reference varibale of parent type.
  • You do not need to upcast manually (implicit).
Manager x = new Manager();
Employee e = x;            // Doesn't need (Employee) before the x. 

downcasting

  • Object of parent class is assigned to reference varibale of child type.
  • You need to downcast manually which subtype to downcast (Explicit). Unless, compiler doesn’t know which subtype to downcast.
    • ex) Employee can downcast to either Manager or Clerk
Employee e = new Manager();
Manager x = (Manager) e;                // (Manager) is needed

 

  • If subtype is different, you will get ClassCastException.
  • To avoid the exception, you need to check which original subtype it was.
Employee e = new Clerk();
Manager x = (Manager) e;       // ClassCastException. 
                               // Original subtype is Clerk()

instanceof

  • You can use instanceof if casting is possible.
class Animal{}
class Dog extends Animal{
   static void cast(Animal a){
      Dog d = (Dog) a;              // Downcasting
   }

   public static void main(String[] args){
      Animal a1 = new Dog();
      if(a1 instanceof Dog){        // True
         Dog.cast(a1);              
      }
      
      Animal a2 = new Animal();
      if(a2 instanceof Dog){        // False
         Dog.cast(a2);              
      }
   }   
}

 

 

 

Types of variables

local variables

  • Local variables are declared in methods, constructors, or blocks.
  • Local variables are visible only within the declared method, constructor or block.

Example…Screen Shot 2016-07-24 at 2.42.25 PM

instance variables

instance

  • Instance variables are declared in a class, but outside a method, constructor or any block.
  • The instance variables are visible for all methods, constructors and block in the class.

Example…Screen Shot 2016-07-24 at 2.43.22 PM

Class / Static variables

static

  • Class variables also known as static variables are declared with the static keyword in a class, but outside a method, constructor or a block.
  • Visibility is similar to instance variables. However, most static variables are declared public since they must be available for users of the class.
  • Static variables can be accessed by calling with the class nameClassName.VariableName.

Example…Screen Shot 2016-07-24 at 2.44.22 PM