Saturday, December 27, 2014

Java 5 New Features

Java 2 Platform Standard Edition 5.0 (J2SE 5.0 or Java 5 or JDK 1.5) came up with a full bunch of significant new features which are very useful for java developers as well as for JVM in order to improve performance. In this tutorial, you can find some important J2SE 5.0 new features added in JDK 1.5 which are part of day-to-day java coding.

List of most commonly used Java 5 new features

  1. Generics for Collections
  2. Enhanced for Loop (for-each loop)
  3. Autoboxing/Unboxing
  4. Typesafe Enums
  5. Varargs/Vargs (Variable-length Argument Lists)
  6. Static Import
  7. Metadata (Annotations)
  8. Formatting
  9. Scanner

1. Generics

Generics is one of the most useful features added in Java 5. It adds compile-time type safety to the Collections Framework and eliminates the necessity for type casting.
Example to show the benefits of Generics:

    import java.util.*;
    public class GenericsTest 
    {
public static void main(String[] args) 
{
   List<String> names = new ArrayList<String>();
   names.add("Ram");
   names.add("Peter");
   names.add("Khan");
   names.add("Singh");
   names.add(new Date()); // Compiler error
   for(int i = 0; i < names.size(); i++) {
// No need of type casting (String)
String name = names.get(i);
System.out.println(" Name = " + name);
   }
}
    }

The above example program is written using Generics feature of Java 5. Here we are telling java compiler to accept only ‘String’ type objects for the List by using <String> thus providing compile-time type safety. Since we have declared ‘names’ as List of Strings, we need not do type casting for retrieving the elements from ‘names’. If we try to add any object other than String, java compiler shows compiler error and won’t allow us to go-ahead until we remove that black sheep object. So, in order to compile the above program you need to comment/remove the line which adds Date object. This avoids unwanted exceptions during runtime when we try to cast/use the objects stored under List. If you wanna see what does this mean, run the following code:
    List names = new ArrayList();
    names.add("Ram");
    names.add("Peter");
    names.add("Khan");
    names.add("Singh");
    names.add(new Date()); // Compiler accepts
    for(int i = 0; i < names.size(); i++) {
        // Gets Exception for Date object
        String name = (String)names.get(i);
        System.out.println(" Name = " + name);
    }
In this old Java code, compiler accepts Date() object to be added to names List without any issue. But in runtime while retrieving that Date object, you will get the following exception:
    Exception in thread "main" java.lang.ClassCastException: 
        java.util.Date cannot be cast to java.lang.String
So, to avoid such kind of unwanted exceptions, we can use Generics to provide compile-time type safety to collections.
We can also nest generics as follows:
    Map<Integer, List<String>> mapStudents = new HashMap<Integer, List<String>>();

Here is a small excerpt from the definitions of the interfaces List and Iterator in package java.util:
public interface List <E> {
    void add(E x);
    Iterator<E> iterator();
}
public interface Iterator<E> {
    E next();
    boolean hasNext();
}

You might imagine that List<Integer> stands for a version of List where E has been uniformly replaced by Integer:
public interface IntegerList {
    void add(Integer x);
    Iterator<Integer> iterator();
}

A note on naming conventions. We recommend that you use pithy (single character if possible) yet evocative names for formal type parameters. It's best to avoid lower case characters in those names, making it easy to distinguish formal type parameters from ordinary classes and interfaces. Many container types use E, for element, as in the examples above. We'll see some additional conventions in later examples.

Generic References: Oracle.

Six important points about Java 5 Generics:
  1. Use of wildcards with extends or super to increase API flexibility
  2. Generics are implemented using Type Erasure
  3. Generics does not support sub-typing
  4. You can't create Generic Arrays
  5. Use of Multiple Bounds
  6. Generic Method (when to use Generic method vs Wildcard)

1.1 Java Generic's wildcards

There are times that you need to work not only with T but also with sub types of T. For example, the addAll method in the Collection interface which adds all the elements in the specified collection to the collection on which it is called. addAll method has the signature
boolean addAll(Collection<? extends E> c)

This ? extends E makes sure that you can not only add collection of type E but also of subtype of E. ? is called the wildcard and ? is said to be bounded by E. So,if we create a List of Number then we can not only add List of number but we can also add List of Integer or any other subtype of Number.
List<Number> numbers = new ArrayList<Number>();
ArrayList<Integer> integers = new ArrayList<Integer>();
ArrayList<Long> longs = new ArrayList<Long>();
ArrayList<Float> floats = new ArrayList<Float>();
numbers.addAll(integers);
numbers.addAll(longs);
numbers.addAll(floats);

So far we have covered the use of extends with wildcards and we saw that API became more flexible after using extends . But where will we use super? Collections class has a method called addAll which add all the specified elements to the specified collection. It has following signature
public static <T> boolean addAll(Collection<? super T> c, T... elements) ;

In this method you are adding elements of type T to the collection c. super is used instead of extends because elements are added into the collection c whereas in the previous example of Collection interface addAll method elements were read from the collection.

PECS stands for producer extends, consumer super. It proves very helpful whenever you are confused about whether you should use extends or super.

It is a mechanism in Java Generics aimed at making it possible to cast a collection of a certain class, e.g A, to a collection of a subclass or superclass of A. This text explains how.
Here is a list of the topics covered:

The Basic Generic Collection Assignment Problem: Imagine you have the following class hierarchy:
public class A { }
public class B extends A { }
public class C extends A { }
The classes B and C both inherit from A.

Then look at these two List variables:
List<A> listA = new ArrayList<A>();
List<B> listB = new ArrayList<B>();

Can you set listA to point to listB ? or set listB to point to listA? In other words, are these assignments valid:
listA = listB;
listB = listA;
The answer is no in both cases. Here is why: In listA you can insert objects that are either instances of A, or subclasses of A (B and C). If you could do this:
List<B> listB = listA;
Then you could risk that listA contains non-B objects. When you then try to take objects out of listB you could risk to get non-B objects out (e.g. an A or a C). That breaks the contract of the listB variable declaration.
Assigning listB to listA also poses a problem. This assignment, more specifically:
listA = listB;

If you could make this assignment, it would be possible to insert A and C instances into the List<B> pointed to by listB. You could do that via the listA reference, which is declared to be of List<A>. Thus you could insert non-B objects into a list declared to hold B (or B subclass) instances.

When are Such Assignments Needed?
The need for making assignments of the type shown earlier in this text arises when creating reusable methods that operate on collections of a specific type.
Imagine you have a method that processes the elements of a List, e.g. print out all elements in the List. Here is how such a method could look:
public void processElements(List<A> elements)
{
   for(A o : elements)
   {
      System.out.println(o.getValue());
   }
}
This method iterates a list of A instances, and calls the getValue() method (imagine that the class A has a method called getValue()).
As we have already seen earlier in this text, you can not call this method with a List<B> or a List<C> typed variable as parameter.

Generic Wildcards: The generic wildcard operator is a solution to the problem explained above. The generic wildcards target two primary needs:
  • Reading from a generic collection
  • Inserting into a generic collection
There are three ways to define a collection (variable) using generic wildcards. These are:
  • List<?>                        listUknown = new ArrayList<A>();
  • List<? extends A>       listUknown = new ArrayList<A>();
  • List<? super   A>        listUknown = new ArrayList<A>();
The following sections explain what these wildcards mean.

The Unknown Wildcard "?"
List<?> means a list typed to an unknown type. This could be a List<A>, a List<B>, a List<String> etc. Since the you do not know what type the List is typed to, you can only read from the collection, and you can only treat the objects read as being Object instances. Here is an example:
public void processElements(List<?> elements)
{
   for(Object o : elements)
   {
      System.out.println(o);
   }
}
The processElements() method can now be called with any generic List as parameter. For instance a List<A>, a List<B>, List<C>, a List<String> etc. Here is a valid example:
List<A> listA = new ArrayList<A>();
processElements(listA);

The extends Wildcard Boundary
List<? extends A> means a List of objects that are instances of the class A, or subclasses of A (e.g. B and C).

When you know that the instances in the collection are of instances of A or subclasses of A, it is safe to read the instances of the collection and cast them to A instances. Here is an example:

public void processElements(List<? extends A> elements)
{
   for(A a : elements)
   {
      System.out.println(a.getValue());
   }
}
You can now call the processElements() method with either a List<A>, List<B> or List<C>. Hence, all of these examples are valid:

List<A> listA = new ArrayList<A>();
processElements(listA);

List<B> listB = new ArrayList<B>();
processElements(listB);

List<C> listC = new ArrayList<C>();
processElements(listC);
The processElements() method still cannot insert elements into the list, because you don't know if the list passed as parameter is typed to the class A, B or C.

The super Wildcard Boundary

List<? super A> means that the list is typed to either the A class, or a superclass of A.

When you know that the list is typed to either A, or a superclass of A, it is safe to insert instances of A or subclasses of A (e.g. B or C) into the list. Here is an example:
public static void insertElements(List<? super A> list){
    list.add(new A());
    list.add(new B());
    list.add(new C());
}
All of the elements inserted here are either A instances, or instances of A's superclass. Since both B and C extend A, if A had a superclass, B and C would also be instances of that superclass.

You can now call insertElements() with either a List<A>, or a List typed to a superclass of A. Thus, this example is now valid:
List<A>      listA      = new ArrayList<A>();
insertElements(listA);

List<Object> listObject = new ArrayList<Object>();
insertElements(listObject);

The insertElements() method cannot read from the list though, except if it casts the read objects to Object. The elements already present in the list when insertElements() is called could be of any type that is either an A or superclass of A, but it is not possible to know exactly which class it is. 

However, since any class eventually subclass Object you can read objects from the list if you cast them to Object. Thus, this is valid:
Object object = list.get(0);

But this is not valid:
A object = list.get(0);

1.2 Generics are implemented using Type Erasure

In Java a class or an interface can be declared to define one or more type parameters and those type parameters should be provided at the time of object construction. For example,
List<Long> list = new ArrayList<Long>();
list.add(Long.valueOf(1));
list.add(Long.valueOf(2));
In the example shown above a List is created which can only contain elements of type Long and if you try to add any other type of element to this list, it will give you compile time error. It helps detect errors at compile time and makes your code safe. Once this piece of code is compiled ,the type information is erased resulting into similar byte code as we would have got if the same piece of code was written using Java 1.4 and below. This results in binary compatibility between different versions of Java. So, a List or List<> are all represented at run-time by the same type, List.

1.3 Generics does not support sub typing

Generics does not support sub-typing which means that List is not considered to be a sub-type of List, where S is a subtype of T. For example,
List<Number> numbers = new ArrayList<Integer>(); // will not compile

The piece of code shown above will not compile because if it compiles than type safety can't be achieved. To make this more clear, lets take the following piece of code shown below where at line 4 we are assigning a list of long to a list of numbers. This piece of code does not compile because if it could have compiled we could add a double value in a List of longs. This could have resulted in ClassCastException at runtime and type safety could not be achieved.
List<Long> list = new ArrayList<Long>();
list.add(Long.valueOf(1));
list.add(Long.valueOf(2));
List<Number> numbers = list; // this will not compile
numbers.add(Double.valueOf(3.14));

1.4 We can't create Generic Array

You can't create generic arrays as shown below because arrays carry runtime type information about the type of elements . Arrays uses this information at runtime to check the type of the object it contains and will throw ArrayStoreException if the type does not match. But with Generics type information gets erased and the array store check will succeed in cases where it should fail.
T[] arr = new T[10];// this code will not compile

You can't even create Arrays of Generic classes of interfaces. For example, the code shown below does not compile.
List<Integer>[] array = new List<Integer>[10]; // does not compile

Arrays behave differently from the collections because arrays are covariant by default, which means that S[] is a subtype of T[] whenever S is a subtype of T, where as Generics does not support covariance. So, if the above code had compiled then the array store check would succeed in cases where it should fail. For example,
List<Integer>[] ints = new List<Integer>[10]; // does not compile
Object[] objs = ints;
List<Double> doubles = new ArrayList<Double>();
doubles.add(Double.valueOf(12.4));
objs[0] = doubles; // this check should fail but it succeed

If the generic arrays were allowed, then we could assign ints array to an object array because arrays are covariant. After that we could add a List of double to the obj array. We will expect that this will fail with ArrayStoreException because we are assigning List of double to an array of List of integers. But the JVM cannot detect type mismatch because the type information gets erased. Hence the array store check succeeds, although it should have failed.

1.5 Use of multiple Bound

Multiple bounds is one of the generics features which most developer do not know. It allows a type variable or wildcard to have multiple bounds. For example, if you to define constraint such as that the type should be a Number and it should implement Comparable.
public static <T extends Number & Comparable<? super T>> int compareNumbers(T t1, T t2){
   return t1.compareTo(t2);
}

It makes sure that you can only compare two numbers which implement Comparable. Multiple bounds follows the same constraints as followed by the a class i.e. T can't extend two classes ,you have to first specify the class then the interface, and T can extend any number of interfaces.
   public static <T extends String & Number > int compareNumbers(T t1, T t2) // does not work..can't have two classes
   public static <T extends Comparable<? super T> & Number > int compareNumbers(T t1, T t2) // does not work..
   public static <T extends CharSequence & Comparable<T>> int compareNumbers(T t1, T t2)// works..multiple interfaces

1.6 Generic Method

Wildcards are designed to support flexible subtyping, Type argument is being used for polymorphism; its only effect is to allow a variety of actual argument types to be used at different invocation sites.

Generic methods allow type parameters to be used to express dependencies among the types of one or more arguments to a method and/or its return type. If there isn't such a dependency, a generic method should not be used.

It is possible to use both generic methods and wildcards in tandem. Here is the method Collections.copy():
class Collections {
    public static <T> void copy(List<T> dest, List<? extends T> src) {
    ...
}

Now that Class has a type parameter T, you might well ask, what does T stand for? It stands for the type that the Class object is representing. For example, the type of String.class is Class<String>, and the type of Serializable.class is Class<Serializable>. This can be used to improve the type safety of your reflection code.

2. Enhanced For Loop (For-Each Loop)

Enhanced for loop is also referred as ‘forEach’ Loop and is specifically designed to iterate through arrays and collections.

Let’s check the benefits of enhanced for loop with the earlier Generics example program.
import java.util.*;

public class ForEachTest 
{
    public static void main(String[] args) 
    {
        List<String> names = new ArrayList<String>();
        names.add("Ram");
        names.add("Peter");
        names.add("Khan");
        names.add("Singh");

         for (String name : names) {
            System.out.println(" Name = " + name);
        }

    }
}
Here, we can simply iterate through the list ‘names’ and retrieve each element into variable ‘name’. After that, we can do whatever we want with that variable as usual. Enhanced for loop avoids the need for using temporary index variable and simplifies the process of iterating over arrays and collections.

3. Autoboxing / Unboxing

The Autoboxing feature eliminates the need for conversion between primitive data types such as int, float etc. and their respective wrapper classes Integer, Float, etc.

What is Autoboxing in Java?
The implicit automatic conversion of primitive values into corresponding wrapper class objects is known as ‘Autoboxing’.

Autoboxing Examples:

    (1) Integer age = 31;  // Autoboxing: 31 => Integer.valueOf(31) 
The above statement creates a new Integer object with value 31 and assigns to Integer reference variable ‘age’.

    (2) List<Double> weights = new ArrayList<Double>();
         weights.add(64.5);  // Autoboxing: 64.5 => Double.valueOf(64.5) 
         weights.add(73.2);  // Autoboxing: 73.2 => Double.valueOf(73.2) 
Here, two Double objects will be created with values 64.5 & 73.2 and those objects would be added to the list ‘weights’.

What is Unboxing (Auto-unboxing) in Java?
The implicit automatic conversion of wrapper class objects to primitive values is called ‘Unboxing’.

Unboxing Examples:

    (3)  if (age > 25) {  // Unboxing: age => age.intValue()
// do something 
         }
Since age is an Integer object and we can’t perform relational operations (<, >, <=, >=) on objects, first age will be converted to ‘int’ using intValue() method of ‘Integer’ class. Later it will be compared with 25 using ‘>’ relational operator.

    (4)  double totalWeight = weights.get(0) + weights.get(1); // 137.7
         // Unboxing: weights.get(0).doubleValue() 
         //           + weights.get(1).doubleValue()
Like in example (3), we can’t perform arithmetic operations (+, -, *, /, %) on objects, hence the two ‘Double’ objects will be converted to ‘double’ primitive values using doubleValue() method. Now, with no issues, those two double values will be added and the sum would be assigned to ‘totalWeight’.

4. Type Safe Enum:

This new feature allows us to create enumerated types with arbitrary methods and fields. The standard way of representing enumerated types in java using ‘int’ has its own problems. The below example program uses standard enum types:

    public class OldEnumTest
    {
        public static final int SUNDAY = 0;
        public static final int MONDAY = 1;
        public static final int TUESDAY = 2;
        public static final int WEDNESDAY = 3;
        public static final int THURSDAY = 4;
        public static final int FRIDAY = 5;
        public static final int SATURDAY = 6;

        void printAppointment(int day) {
            System.out.println(" Please come on " + day);
        }

        public static void main(String[] args) 
        {
            new OldEnumTest().printAppointment(WEDNESDAY);
        }
    } 

    Output: Please come on 3
Here, there is no type-safety for enum values because compiler can accept any integer number for ‘int’ variable. We can’t stop somebody from passing outside range values to enum variable. For example, we can call printAppointment() method with value 10 or even -25, compiler won’t complain that this is not valid even though we are expecting a number between 0 and 6.

Another issue is that the value displayed would be a number which is not informative. By seeing that number we do not know which enum value it is referring to, moreover we do not even know that it is an enum because of the number. You can understand this better by seeing the above output.

Now consider the following type-safe enum example program:

    public class NewEnumTest 
    {
        public enum Day {
            SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
        }

        void printAppointment(Day day) {
            System.out.println(" Please come on " + day);
        }

        public static void main(String[] args) 
        {
            new NewEnumTest().printAppointment(Day.TUESDAY);
        }
    } 

    Output: Please come on TUESDAY
Here, compiler accepts only those values which are defined in enum ‘Day’ to be passed to printAppointment() method, thus providing compile time type-safety. Also, the output is so informative that we can understand very easily.

5. Varargs / Vargs (Variable-length argument list)

The Varargs java 5.0 feature avoids the need to group up arguments into an array in order to pass while invoking a method.

Example java code to show the usage of Varargs:
    public class VarargsTest 
    {
        public static void main(String[] args) 
        {
            System.out.println(" Sum = " + sum(41, 22, 58));
        }
        static int sum(int... numbers) {    // varargs
            int sum = 0;
            for (int i = 0; i < numbers.length; i++) {
                sum += numbers[i];
            }
            return sum;
        }
    }

    Output: Sum = 121
In the above example java code, ‘int…’ allows us to pass any number of int arguments to the method ‘sum’. The following examples are all valid.
    sum(98, 33, 105, 10, 7) =>  Sum = 253
    sum(208, 27, 89, 320, 42, 154, 111, 65, 93) =>  Sum = 1109
You can try out float…, char…, String… etc. to understand Varargs much better.

Varargs can also be combined with other arguments, but there should be only one vararg for a method and that vararg should be the last argument for that method.

Java Varargs Examples:
    double calculator(String operation, double... numbers)
    void print(long productId, double price, int qty, String... orderDetails)

6. Static Import:

This feature eliminates the process of qualifying the static members of a class with the class name. Those members can be methods as well as fields.

Example java code to show the usage of Static Import:

    import static java.lang.Integer.*;
    import static java.lang.String.format;

    public class StaticImportTest 
    {
        public static void main(String[] args) 
        {
            int num = parseInt("526");  // => Integer.parseInt()
            Integer num2 = valueOf("123");  // => Integer.valueOf()
            // => String.format()
            System.out.println(format("Numbers: %d, %d", num, num2));
            // => Integer.MAX_VALUE
            System.out.println(" Integer MAX value = " + MAX_VALUE);
        }
    }
Output:
    Numbers: 526, 123
    Integer MAX value = 2147483647

Important Note: Remember the order of keywords. It is ‘import static‘ but not ‘static import’. (I know, it is little bit confused with feature title)

In the above example program, we have imported all static members of the class Integer and format() static method of the class String. Hence, we need not qualify those members like Integer.parseInt(), Integer.valueOf(), String.format(), and Integer.MAX_VALUE. You might have observed that we have used Varargs also in the above example. Yes, String.format() method accepts any number of arguments with syntax “format(String formatStr, Object… args)”.

7. Meta-data (Annotation)

This Java 5 feature lets you avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a “declarative” programming style where the programmer says what should be done and tools emit the code to do it. Also it eliminates the need for maintaining “side files” that must be kept up to date with changes in source files. Instead the information can be maintained in the source file.

What are Annotations?
Annotations provide a little extra information about the classes we write. This feature is very useful because we can attach extra information to our code that may determine how it is used.

For example, in J2SE 5.0, we can declare our intent to override a method like toString() in one of our classes as follows:
public class MyClass extends Object {
        @Override
        public String toString() {
            return "My overridden toString() method!";
        }
    }
In the above example, we declared that we are going to override the toString() method using @Override annotation. So the compiler looks in super class (Object) for toString() method with same signature (parameters and return type) and make sure it exists. If, for some reason, we tried to overload toString() by declaring it with different parameters or return type, then the compiler gives an error as there is no such version of toString() method in java.lang.Object. This is really useful to make sure we override correct method and avoid overloading the method by mistake.

We can also define our own Annotations. They basically looks like interfaces, but they can contain values.

Example to explain custom annotations:
    public @interface Meeting 
   {
        String what() default "Project meeting";
        String when();
        String location();
    }
This annotation declares three members: what, when, location and sets them up to have “getters” and “setters” automatically. That means each @Meeting annotation has those three fields associated with it, and we don’t have to define the accessor and mutator methods to set them up. If we define this annotation like this, we can use it to mark code that we use for the XYZ Project Meeting:

    @Meeting(what="Project XYZ",when="11-Apr-2013",location="New York")
      public class MeetingXyz 
     {
        //... class definition
      }
Now the @Meeting type of data is associated with MeetingXyz class. Later on, we could write an analyzer that goes through all of the code and let us know which classes were used at meetings as well as which meetings they were used at and when.

Here, we have discussed about one most commonly used annotation @Override. Few other commonly used annotations are @Deprecated and @SupressWarnings.

8. Formatting

Java 5 provides an interpreter for C language printf-style format strings. This feature provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. The String class has a method called ‘format’ which takes first argument as formatted string and the remaining arguments as values to be substituted for conversions (%d, %f, etc) inside the formatted string.

The below example shows how to use different type conversions for formatting strings:
    int m1 = 78, m2 = 93, m3= 85;
    int total = m1 + m2 + m3;
    double avg = total / 3.0;
    String result = String.format("Marks: %d, %d, %d. Total: %d, Avg: %.2f", 
                                    m1, m2, m3, total, avg);
    System.out.println(result);

Output:
    Marks: 78, 93, 85. Total: 256, Avg: 85.33
The following are the commonly used conversions in formatting:
%d denotes decimal integer types such as byte, short, long and double.
%f denotes floating point types such as float and double.
%b denotes boolean.
%c denotes character.
%s denotes String.

9. Scanner

The java.util.Scanner class can be used to convert text into primitives or Strings.

Example to show the usage of Scanner:
    java.util.Scanner scanner = new java.util.Scanner(System.in);
    System.out.println("Enter your name:");
    String name = scanner.next();
    System.out.println("Enter your age:");
    int age = scanner.nextInt();

    System.out.printf("Name = %s, age = %d", name, age);

Old Style:
String firstName;
InputStreamReader inStream = new
InputStreamReader(System.in);
BufferedReader inBuf = new BufferedReader(inStream);
System.out.print("Please enter your first name => ");
try {
firstName = inBuf.readLine();
} // end of first try block
catch (IOException e) {
System.out.println("Problem reading first name");
return;
} // end catch block

New Style:
String lastName;
System.out.print("Please enter your last name => ");
Scanner fromkeyboard = new Scanner(System.in);
lastName = fromkeyboard.next();

In the above example, we are reading the user’s name as String and her age as int from console (System.in). We can use Scanner to convert text from console, files, network stream etc into appropriate variables like String, int, float, byte, long, boolean etc.

10. String Builder

• java.lang.StringBuilder classprovides a faster alternative to StringBuffer
– In most ways StringBuilder works exactly thesame as StringBuffer
– StringBuilder is faster than StringBuffer because it is not ThreadSafe (multiple threads should not access StringBuilder objects without Synchronizing)
– Use StringBuilder when speed is important in a single-thread environment and use StringBuffer if multiple threads might require access.
String myString = "How";
StringBuilder myStrBldr = new StringBuilder("How");
myString += " now";
myString += " Brown";
myString += " Cow?";
myStrBldr.append(" now");
myStrBldr.append(" Brown");
myStrBldr.append(" Cow?");
System.out.println("String = " + myString);
System.out.println("StringBuilder = " + myStrBldr);

11. Synchronization

• The java.util.concurrent.locks, java.util.concurrent, and java.util.concurrent.atomic packages are available providing better locking support than provided by the "synchronized" modifier.
• All existing code still works as before
• The java.util.concurrent.xxx packages include interfaces and classes used to simplify synchronization and locking
• The java.util.concurrent.locks.Lock interface has several methods including:
– lock() to obtain a lock (blocks if can’t get lock)
– unlock() to release a lock
– lockInterruptibility() gets lock, allows interruptions
– tryLock() attempts to obtain a lock without a wait.
• The java.util.concurrent.locks.ReentrantLock class behaves like using synchronized does today
• The java.util.concurrent.locks.Condition interface allows complex and multiple conditional waits
• The java.util.concurrent.locks.ReadWriteLock interface allows separate read/write locks


Sunday, December 7, 2014

Maven to use default JDK on MAC


Apple JDK(s) Location: $ ls -latr /System/Library/Java/JavaVirtualMachines
Oracle JDK(s) Location: $ ls -latr /Library/Java/JavaVirtualMachines
Apple Versions Location/System/Library/Frameworks/JavaVM.framework/Versions

There are 2 ways to update java version on mac:
1. Following are equivalent for ~/.bash_profile
  * export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
  * export JAVA_HOME=`/usr/libexec/java_home -v '1.7*'`
2. update the softlink like below on mac:
  * $ java -version
  * $ cd /System/Library/Frameworks/JavaVM.framework/Versions/
  * $ rm CurrentJDK
  * $ ln -s /Library/Java/JavaVirtualMachines/jdk1.7.0_21.jdk/Contents/ CurrentJDK
  * $ java -version

even after updating version by above mechanism maven still pointing to mac-osx 1.6, because it internally use mac java 6:
$ java -version: java version "1.7.0_51"
$ mvn -version: Apache Maven 3.2.1

When i check it '$M2_HOME/bin/mvn' we can see during start-up, maven look for 2 files '/etc/mavenrc' and '~/.mavenrc'.
So my /etc/mavenrc looks like this:
JAVA_HOME=`/usr/libexec/java_home` # pick the latest version
or we can also define java specific version as : JAVA_HOME=`/usr/libexec/java_home -v 1.7`
bash-style: $ export JAVA_HOME=`/usr/libexec/java_home`
csh-style: % setenv JAVA_HOME `/usr/libexec/java_home`

vi ~/.bash_profile
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)
# export M2_HOME="/Users/adixit/Documents/XYZ/apache-maven-3.2.3" # brew install take care of setting path
# export PATH="$PATH:${HOME}/Documents/XYZ/apache-maven-3.2.3/bin" # brew install take care of setting path

$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin


sudo ln -nsf /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK

= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 
First run /usr/libexec/java_home -V which will output something like the following:
SISs-MacBook-Pro:Commands adixit$ /usr/libexec/java_home -V
Matching Java Virtual Machines (4):
    1.8.0_25, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home
    1.7.0_72, x86_64: "Java SE 7" /Library/Java/JavaVirtualMachines/jdk1.7.0_72.jdk/Contents/Home
    1.6.0_65-b14-466.1, x86_64: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
    1.6.0_65-b14-466.1, i386: "Java SE 6" /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
/Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home

Pick the version you want to be the default (1.8.0_25 for arguments sake) then:
export JAVA_HOME=`/usr/libexec/java_home -v 1.8.0_25`

SISs-MacBook-Pro:Commands adixit$ java -version
java version "1.8.0_25"
Java(TM) SE Runtime Environment (build 1.8.0_25-b17)
Java HotSpot(TM) 64-Bit Server VM (build 25.25-b02, mixed mode)
SISs-MacBook-Pro:Commands adixit$ 

Just add the export JAVA_HOME… line to your shell’s init file.
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
After installing java 7 you will need to do the sudo ln -snf in order to change the link to current java. To do so, open Terminal and issue the command:

$ sudo ln -nsf /Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK

to set JAVA_HOME:
export JAVA_HOME="/Library/Java/JavaVirtualMachines/jdk1.7.0_51.jdk/Contents/Home"
= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = 

We can also use jenv script to automatically do execute above task using script.
/System/Library/Frameworks/JavaVM.framework/Versions
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home

AppleJava6: /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
OracleJava7: /Library/Java/JavaVirtualMachines/jdk1.7.0_72.jdk/Contents/Home
OracleJava8: /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home


MacBook-Pro:~ adixit$ jenv add /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home
oracle64-1.6.0.65 added
1.6.0.65 added
1.6 added

MacBook-Pro:~ adixit$ jenv add /Library/Java/JavaVirtualMachines/jdk1.7.0_72.jdk/Contents/Home
oracle64-1.7.0.72 added
1.7.0.72 added
1.7 added

MacBook-Pro:~ adixit$ jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_25.jdk/Contents/Home
oracle64-1.8.0.25 added
1.8.0.25 added

1.8 added

MacBook-Pro:~ adixit$ jenv global 1.7.0.72
MacBook-Pro:~ adixit$ jenv local 1.7.0.72
MacBook-Pro:~ adixit$ jenv shell 1.7.0.72

MacBook-Pro:~ adixit$ jenv versions

References:
  1. Apple way to became root on mac appledoc & terminal.
  2. Give sudo access on macbook.
  3. Change java version on mac and source at github.
  4. jenv utility that let you change environment on mac.
  5. oracle blog
  6. jenv

Installing / Uninstalling IntelliJ & important shortcuts

Uninstalling Intellij on a Mac for the most part is no different from uninstalling any application on a Mac you’ll need to go to the Applications directory and and remove the application bundle though there will be some residual files that will need deleting. 

All application installed in directory "/Application", same of intelliJ as "/Application/IntelliJIdeaXX" where XX stands for version for us XX is 14 ("/Application/IntelliJIdea14").

XX : 14
Follow these steps for a complete removal
  1. Goto /Application/<ApplicationName>  directory right click or drag and move to trash, for some reason if we are not able to delete then run command from terminal window [rm -rf /Application/IntelliJIdea14 as user / or as super user ( sudo) ].
  2. Goto the following directory where ‘username’ is your username and AppName will be something like ‘jetbrains.intellij’ /Users/username/Library/Preferences/AppName
  3. remove all residue files [~ is user home directory /Users/username]:
    1. ~/Library/Caches/IntelliJIdeaXX
    2. ~/Library/Logs/IntelliJIdeaXX
    3. ~/Library/Preferences/IntelliJIdeaXX
    4. ~/Library/Application Support/IntelliJIdeaXX
    5. ~/Library/Preferences/com.appname.plist
      1. ~/Library/Preferences/com.jetbrains.intellij.plist
    6. ~/Library/Preferences/com.jetbrains.intellij.plist.lockfile
    7. ~/Library/Caches/com.jetbrains.intellij
    8. ~/Library/Saved Application State/com.jetbrains.intellij.savedState
    9. /Library/Preferences/AppName
    10. /Library/Preferences/com.appname.plist
    11. /Library/Application Support/AppName
    12. Also clear any files from location ~/.intellij  folder or something similar in your home directory.
References:
1. https://intellij-support.jetbrains.com/entries/23358108
2. https://devnet.jetbrains.com/docs/DOC-181

 Installing Intelli J to use JDK 7 /JDK 8

Open Info.plist in an editor and make following changes and save and exit.
$ vi /Applications/IntelliJ IDEA 14.app/Contents/Info.plist
      <key>JVMVersion</key>
      <string>1.6*</string>
change to 
      <key>JVMVersion</key>
      <string>1.8*</string>
and make sure we have LANG=en_US.UTF-8 in our environment.

Intelli J Shortcut
  1. Search everywhere with Double Shift Click.
  2. Open a file name with 'Shift'+ 'Command'+'O'.
  3. Open recent Files with 'Command'+'E'.
  4. Open Navigation Bar with 'Command'+'up arrow'.
  5. Drag and drop files here from Finder.
  6. Search for a java method in a java class: 'Fn'+'Command'+'F12'.
  7. Control+space: completion (shift: smart)
  8. Command+O to navigate to any class
  9. Option+F7 : Edit /find/find usage
  10. F1: quick documentation
  11. Command+B: navigate declaration
  12. Command+F12: Navigate File structure
  13. Shift+F6: refactor / rename
  14. Control+o: code override methods
  15. Control+I: code implements method of interface
  16. Command+N [code generation]
  17. Option +F1: 
  18. F12: moves the focus from editor to last focus tool window
  19. Option+Command+T: Code / surround with
  20. Navigate implementation of abstract method: option+command+B
  21. Option+up arrow: extend selection.
  22. Option+Command+V: simplify complicated statement (refractor / extract / variable)
  23. Comment(s):Command+/  and option+command+/
  24. Browser with documentation: shift+F1
  25. Command+D: duplicates
  26. Command+Delete: Delete
  27. Command+P: paranthesis parameter
  28. Shift+Command+Delete: Naviagate last editted location - history
  29. Shift+Command+F7: Edit find highlighted item in file (Command+G and Shift+Command+G: to naviage)
  30. Control+Shift+Q: view / context info, to see declaration of current method.
  31. Command+E: view recent files
  32. F2/Shift+F2: to jump between highlighted syntax error.
  33. Option+command+up arrow / option+command+down arrow: shortcut to jump between compiler error messages or search option results
  34. Command+J: live code completion template
  35. Control+ uparrow / Control+down arrow: to move between methods
  36. Control+Shift+J: combine two lines
  37. Shift+Command+V: clipboard paste
  38. Control+H: inheritance hierarchy of a selected class.
  39. Option+Command+O: to search a method or a field in a class.
  40. Option+Shift+C: to quickly review your recent changes to the project
  41. Control+tilt: View quick switch schemes
  42. Shift+Command+Enter: to complete a current statement such as if , try catch return etc.
  43. Option + space: view quick definition
  44. Option+Shift+Commnad+C:Edit copy reference
  45. Control+Option+R: access run / debug dropdown on the main toolbar
  46. Option+Command+F7: Edit find show usage
  47. Shift+Command+A: Help / Find action
  48. To quickly find and run an inspection: option+shift+command+I
  49. Option+Enter: to create test
  50. Alt: multiple cursor
  51. Control+K: commit changes
  52. Command+F: search pane Command+R: replace [Path: Shift]

Check Port bind exception:
1. We can try $ netstat -anp tcp | grep 8080
2. If our netstat doesn't support -p, use lsof then try $ lsof -i tcp:8080
3. to free up run $ kill -9 processId.




Wednesday, September 10, 2014

Understanding Asynchronous I/O in Play Framework

The problem: Many web based applications invoke external web services. Network I/O involves significant amount of waiting. Waiting comes from two sources:

  • Service latency: The time it takes for the external service to complete the task.
  • Network latency: A thread doing read can wait for data to become available in the network socket. A thread doing write sometimes need to wait when the write buffer is full and can no longer accept new data.
In traditional web application each HTTP request is handled by an application thread. For example, if we have 50 concurrent requests we will have 50 threads created to process those requests. If the application code makes web service calls we will have many of these threads simply waiting for the I/O to finish. To serve more concurrent requests we will need to create more threads. Having a large number of threads increases memory overhead.

The asynchronous model

In this model we offload all the network I/O to a very small number of worker threads. These threads use the select system call (or, equivalent calls like epoll and kqueue) to efficiently wait on a large number of sockets to become readable or writable. Application threads are then used only to run application code. For example, let’s say that you have 50 concurrent requests and 40 of them are making web service calls and 10 are executing application code. The 40 web service calls can be made by a small number of worker threads, say about 2. The 10 requests that need to run actual application logic will need 10 application threads. This way, we are serving 50 HTTP requests with 12 threads. This model scales very well. Again assuming your application makes a lot of web service calls, you can support a very large number of HTTP requests using a small number of threads.

Java NIO wraps the select (or epoll or kqueue) call in the java.nio.channels.Selector class. If you are not familiar with how these system calls work I will highly recommend you to read about them. The real magic of any asynchronous network I/O comes from these functions.

How do I do asynchronous I/O?

For the asynchronous model to work it is essential that you are using the correct way to make web service calls. For example, if you use the traditional way of using the java.net.URL to make HTTP calls you will always get the synchronous model. The key is to do these things when a HTTP call is made:
  1. Ask a worker thread to add the HTTP operation to the collection of HTTP calls that it is already tracking.
  2. Return the application thread back to the pool of available threads.
  3. The worker thread will send the request and wait for response data to be available. It does so for all the sockets that it is tracking. As response data begins to trickle in it will parse the data and detect when the response is completed. It will then invoke the completion callback of the application in an application thread.
Doing these things can be very very tricky. You will almost always rely on a well known library for this. In Play the play.api.libs.ws.WS class does this. In Java you can use a library like the AsyncHttpClient.

Watching Play in action

To observe how async I/O works in Play, we use this bit of controller code.
object Application extends Controller {
def index = Action.async {
 def onResult(r: Any) {
   println("Response completed. " +
     Thread.currentThread().getName)
 }
 //Call web services in parallel
 println("Sending out requests to WS. " +Thread.currentThread().getName)
 val svc1 = WS.url("http://example.com/svc1").get().map(onResult)
 val svc2 = WS.url("http://example.com/svc2").get().map(onResult)
 val svc3 = WS.url("http://example.com/svc3").get().map(onResult)

 //Wait for all web service calls to finish
 Future.sequence(Seq(svc1, svc2, svc3)).map { case times => Ok("We are done")
 }
}
}

Basically, we print out the name of the thread before making the web service calls and after the calls complete. The console output may look something like this:
Sending out requests to WS. play-akka.actor.default-dispatcher-6
Response completed. play-akka.actor.default-dispatcher-4
Response completed. play-akka.actor.default-dispatcher-6
Response completed. play-akka.actor.default-dispatcher-4

In Play, a dispatcher thread is what I called application thread earlier. They run actual application logic. After a web service call completed system invoked the completion callback function (onResult) in one of the available dispatcher threads.

To get a better idea about what the threads are doing we need to use a JVM monitoring tool. I will use jvisualvm which comes with JDK.

Here are some of the threads running in a freshly started JVM. I ran my test controller a few times using curl.


Note that a small number of network I/O worker threads have been created. Even smaller number of application or dispatcher threads have been created.
What will happen if I hammer the controller concurrently from 50 users? If all goes well we should see the number of worker threads remain more or less the same. But the dispatcher thread count will grow.

Let’s go!

ab -n 50 -c 50 http://localhost:9000/

I immediately saw 50 “Sending out requests to WS” message printed on the console. Not all requests came exactly at the same time. Some of the dispatcher threads already made the call to WS.url().get() and hence became free. They were reused to serve another HTTP request. Below is a sample console output where we can see that the dispatcher thread #19 being reused a lot.
Sending out requests to WS. play-akka.actor.default-dispatcher-18
Sending out requests to WS. play-akka.actor.default-dispatcher-19
Sending out requests to WS. play-akka.actor.default-dispatcher-14
Sending out requests to WS. play-akka.actor.default-dispatcher-19
Sending out requests to WS. play-akka.actor.default-dispatcher-19
Sending out requests to WS. play-akka.actor.default-dispatcher-14

According to jvisualvm, the number of dispatcher threads grew to abut 12. The important thing to note here is that the number is not 50. In a traditional application this number will certainly be 50.

Very quickly all 50 requests will issue a total of 150 HTTP web service calls. According to jvisualvm, the number of I/O worker thread was only 8. (Note, these threads are used not only to do the external web service calls, they are also used by the Play web server to accept request from the browser). Play limits the maximum size of these worker threads. Even with say 8 threads the server can handle many thousand connections (both incoming to the server and outgoing to the web services).

In summary, I saw about 20 threads used to handle 50 concurrent requests.
If you take a thread dump at any point, you should see the worker threads calling select.

"New I/O worker #12" daemon prio=5 tid=0x00007fc6ec383800 nid=0x7413 runnable [0x000000011a742000]
java.lang.Thread.State: RUNNABLE
at sun.nio.ch.KQueueArrayWrapper.kevent0(Native Method)
at sun.nio.ch.KQueueArrayWrapper.poll(KQueueArrayWrapper.java:200)
at sun.nio.ch.KQueueSelectorImpl.doSelect(KQueueSelectorImpl.java:103)
at sun.nio.ch.SelectorImpl.lockAndDoSelect(SelectorImpl.java:87)
- locked (a sun.nio.ch.Util$2)
- locked (a java.util.Collections$UnmodifiableSet)
- locked (a sun.nio.ch.KQueueSelectorImpl)
at sun.nio.ch.SelectorImpl.select(SelectorImpl.java:98)
at org.jboss.netty.channel.socket.nio.SelectorUtil.select(SelectorUtil.java:68)

The dispatcher threads will either be idle or running application code. Below is an idle thread.
"play-akka.actor.default-dispatcher-14" prio=5 tid=0x00007fc6eef8e000 nid=0x8b0f waiting on condition [0x000000011b49c000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for (a akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinPool)

Final word

Bottom line, asynchronous I/O allows you serve a large number of HTTP requests with a small number of threads. This is true for applications that make a lot of external web service calls. It is essential that you use proper method to make web service calls. In Play use the WS class. Finally, always verify that you are indeed benefiting from the asynchronous model. Run a stress test and observe the threads like we did here. The total number of I/O worker and dispatcher threads should be well below the number of active HTTP requests.

Friday, September 5, 2014

Google Chrome, Mac OS X and Self-Signed SSL Certificates

Let's say you have a server with a self-signed HTTP SSL certificate. Every time you hit a page, you get a nasty error message. You ignore it once and it's fine for that browsing session. But when you restart, it's back. Unlike Firefox, there's no easy way to say "yes, I know what I'm doing, ignore this." This is an oversight I wish Chromium would correct, but until they do, we have to hack our way around it.

Caveat: these instructions are written for Mac OS X. PC instructions will be slightly different at PCs don't have a keychain, and Google Chrome (unlike Firefox) uses the system keychain.

So here's how to get Google Chrome to play nicely with your self-signed SSL certificate:

  1. In the address bar, click the little lock with the X. This will bring up a small information screen. Click the button that says "Certificate Information." 
  2. Click and drag the image to your desktop. It looks like a little certificate. 
  3. Double-click it. This will bring up the keychain Access Utility. Enter your password to unlock it.
  4. Be sure you add the certificate to the System keychain, not the login keychain. Click "Always Trust," even though this doesn't seem to do anything.
  5. After it has been added, double-click it. You may have to authenticate again.
  6. Expand the "Trust" section.
  7. "When using this certificate," set to "Always Trust".



or from command line execute following command:
sudo security add-trusted-cert -d -r trustRoot -k /Library/Keychains/System.keychain site.crt


That's it! Close Keychain Access and restart Chrome, and your self-signed certificate should be recognized now by the browser.

This is one thing I hope Google/Chromium fixes soon as it should not be this difficult. Self-signed SSL certificates are used *a lot *in the business world, and there should be an easier way for someone who knows what they are doing to be able to ignore this error than copying certificates around and manually adding them to the system keychain.

Saturday, July 19, 2014

Apple important Shortcuts & Tricks






  1. Command + Delete to delete a file, Command + Shift + Delete to delete it permanently even from Trash, Command+Shift+Option+Delete : means delete without confirmation dialog even from trash.
  2. Your security preferences allow installation of only apps from the Mac App Store and identified developers: press Control + Click [Permanently Changes: Preferences > 'Security & Privacy’ > click unlock at the bottom > to allow it by default.]
  3. Command +Control + Power Button : Force Mac to restart
  4. Command + Shift + 3: capture screen to a file
  5. Command + Shift + Control + 3: capture screen to clipboard
  6. Command + Shift + 4: Capture a selection of screen to a file, or press the spacebar to capture just a window.
  7. Command + Shift + Control + 4: Capture a selection of screen to clipboard, or press the spacebar to capture the just a window.
  8. Command + Shift + [+]: Zoom out
  9. Command + Shift + [-] : Zoom in
  10. Command + Spacebar: Spotlight
  11. Command + Tab: switch between windows ; Command+Shift+ Tab: navigate in reverse direction ( and when we press Q, it will close respective tab).
  12. Control + Tab: navigate Tabs, Control+Shift+Tab: navigate in reverse direction.
  13. Command+[:]: display spelling and grammar window.
  14. Command+[;]: find mis-spelled word in the document.
  15. Command+[,]: open front application - preference window.
  16. Command + D: bookmark current page
  17. Command+G: find next occurrence of selection, Command + Shift + G: find previous occurrence of selection.
  18. Command + Z: undo, Command + Shift+Z: redo
  19. Command + Option + ESC: Choose force quit an application.
  20. Command + Shift + Option + ESC ( hold for 3 sec) force quit front most application.
  21. Command + 'Left bracket' [ : Previous browser web page
  22. Command + 'Right bracket' ] : Next browser web page
  23. Delete: backward delete, fn+Delete: forward delete.
  24. Command + Shift + Q: Logout, Command+Shift+Option+Q: logout immediately.
  25. Finder Shortcuts:
    1. Select All: Command + A
    2. De-select All: Command + Option +A
    3. Open Application Folder: Command + Shift +A
    4. Duplicate selected Item: Command+D
    5. Open Desktop Folder: Command + Shift +D
    6. Show View option: Command + J
    7. Connect to server: Command +K
    8. Open network window: Command + Shift +K
    9. Make aliases of selected items: Command +L
    10. Minimize window: Command +M
    11. Minimize all window: Command +Option +M
    12. New finder window: Command +N
    13. New Folder: Command +Shift +N
    14. Close curent tab: command + W, re-open closed tabs: command +Z
    15. New browser Window: Command + N
    16. command + Q: close safari window and all tabs.
    17. Go to end of line: Command + Right arrow
    18. Go to beginning of line: Cmd-left arrow
    19. Go to end of all the text: Cmd-down arrow
    20. Go to beginning of all the text:Cmd-up arrow
    21. Go to end of current or next word: Option-right arrow
    22. Go to beginning of current or previous word: Option-left arrow
  26. Finder PathBar and few handy functions (The finder PathBar is disabled by default, but it's very simple to enables it: 'Open Finder Window' > 'Select show PathBar from the view menu' > 'The PathBar will now display in all finder window'):
    1. Double clicking any of the folder in PathBar will take you to that folder.
    2. We can move files and folders to any element in PathBar by simply dragging and dropping them.
      1. We can copy them by holding the option key as we drag them.
      2. or create an alias to an item by holding down the Command + Option keys while we drag them.
  27. Terminal:
    1. Show hidden files on mac:
      1. $ defaults write com.apple.finder AppleShowAllFiles TRUE
      2. $ killall Finder
    2. Disable Lion/Mountain Lion's Pop-up Accent Window:
      1. $ defaults write -g ApplePressANdHoldEnabled -bool false
    3. Change the Default Backup Periods in Time Machine
      1. [This makes Time Machine backup now every 30 mins = 30*60 secs]$sudo defaults write /System/Library/Launch Daemons/com.apple.backupd-auto StartInterval -int 1800
    4. Drag Dashboard Widgets onto the Desktop (like windows 7)
      1. $ defaults write com.apple.dashboard devmode YES
    5. Change the file format of Screenshots (default is PNG): 
      1. $ defaults write com.apple.screencapture type file-extension [replace file-extension with three letter abbreviated word JPEG for JPG, PDF]
    6. Kill the Dashboard all together
      1. $ defaults write com.apple.dashboard mcx-disabled -boolean YES
      2. Then restart the Dock using the command $ killall Dock
    7. Securely erase free space: When we delete files on our mac, OS-X still leaves fragments of the file all over the free space on our hard disk drive, until these are written over by new files. if you want to securely delete all the remaining fragments on a hard disk drive (for eg. if we are going to sell our mac) then execute the following command:
      1. [replace name-of-drive with the drive we want to erase. This command uses a special algorithm to wipe over each free area of space 35 times, far above the US Dept of Defense's standard, which only requires 7 passes. Be aware through that this process can take days on larger drives] $ diskutil secureErase freespace 3 /Volumes/name-of-drive
    8. Remote Login: Being able to control your Mac remotely via SSH, or secure shell, is far more advantageous that screen sharing as it uses less system resources and less bandwidth. The first thing we will have to do is enable Remote Login on our Mac, which we can do by heading over the 'System Preferences' then 'Sharing' then Click on 'Remote Login'. 
      1. $ ssh -l username remote-address [replace username with your username you use to log into OS X and remote-address with the IP-address given to you in the sharing pane. You can now control your Mac and execute Terminal commands remotely, a real plus.
    9. Talking Mac: $ say command [eg. say Hello World !] The words will be spoken in your Mac's default voice but if we want to change this, then simply head over to System Preferences then either Dictation and Speech (on Mountain Lion) or simply Speech (on Lion). Here you can select different voices and download new one from Apple's servers if you fancy. Another "useful" feature is the ability to convert an entire text file into speech, if you so fancy. Simply enter: $ say -o audio.aiff -f FILENAME.txt  [replace FILENAME.txt with your own file. This will create a reading of your file as an AIFF file audio.aiff in Terminal's default directory].
    10. Stop / kill server instance:
      1. Control +z : (sig 3+ signal but it will not clear the instance process id)
      2. Control +c : (Kill and clear instance as well)
    11. Enable root
      1. terminal: $ sudo -s
      2. Enable from Mac GUI
        1. Open user and group preferences, click login options, then click the lock icon to unlock it. If necessary they your password then click unlock.
        2. In the Network Account Server Section, click Join or Edit.
        3. Click open Directory Utility.
        4. Click the lock icon to unlock it, then enter your administrator name and password.
        5. Do one of the following:
          1. Choose Edit > Enable Root User, then enter a root user password in the password and verify fields.
          2. Choose Edit > Disable Root User.
          3. Choose Edit > Change Root Password, then enter a new root user password.
    12. sudo interactive shell
      1. interactive shell: $ sudo -i
      2. exit interactive shell: $ exit +Enter    or   ^D ( Control + D)
  28. MAC OS X Tips:
    1. Shift + Click 'Maximize button' to fill screen.
    2. use $ purge command to force release unused blue memory.
    3. Remove icon from menu bar: hold command key, click icon, drag it off menu bar.
    4. Go to Libary folder ( ~/Library ) or (~/Application).
    5. Finder SideBar, open finder , and click 'Show SideBar', we can create shortcut of our folder for easy access.
    6. Control the apps that Launch at startup, this will reduce mac startup time: 'System & Preferences' > 'User and Groups' > then look for 'Login Items' button ( those are the apps that launch for me).
    7. Lock Macbook: To do this, head to System Preferences > Security & Privacy > General. Check the box next to “Require Password” and set an interval that meets your workflow. If you want the highest level of security, set it to “immediately”, following are 2 ways:
      1. Lock Screen: To lock your Mac’s screen, simultaneously press the following keys: Control + Shift + Eject. If you have a newer Mac that doesn’t have an optical drive(and thus has no eject key on the keyboard, such as the Retina Macbook Pro), the command is Control + Shift + Power.
      2. Sleep the Mac entirely: MacBook owners are familiar with sleep; it occurs every time they shut their computer’s lid, or automatically after a user-defined period of time. But users can also trigger an immediate sleep state with a simple keyboard command: Command + Option + Eject. Optical drive-less Mac owners can repeat the substitution discussed above and replace the Eject key with the Power key, resulting in a command for Retina Macbook Pro owners, et al. of Command + Option + Power.
  29. KeyChain: 
    1. identityserviced wants to use the "Local Items" keychain: delete the keychain entries under following folder " ~/Libarary/Keychains/" and restart the system.

Friday, July 4, 2014

DMV Written Test

To obtain a California driver's license you must pass a written exam consisting of multiple-choice questions. If you're 18 and over, there are 36 questions and you can get up to 6 wrong. If you're 18 and under, there are 46 questions and you can get up to 8 wrong. There are several different versions of the test, but they all use the same basic pool of questions.


Memorize the brief list of facts below and you should do fine:

  1. Before you change lanes, you should... check your mirrors and look over your shoulder.
  2. If you want to pass a bicyclist riding on the right edge of your lane, you should... allow a minimum of 3 feet between you and the cyclist.
  3. If an uncontrolled railroad crossing is ahead and you can't see clearly if any trains are coming, the speed limit is...15 mph.
  4. A child passenger restraint system is required for...a five-year old weighing 55 pounds.
  5. If you want to go into a store to make a quick purchase, you should...Stop the engine and set the parking brake.
  6. You should check your rearview mirrors...often to see how traffic is moving behind you.
  7. When approaching an intersection at the posted speed limit when the signal light turns yellow, you should...stop before entering the intersection, if you can do so safely.
  8. It is illegal for a person 21 years of age or older to drive with a blood alcohol concentration (BAC) that is... 0.08% - Eight hundredths of one percent or higher.
  9. If you want to pass a bicyclist in a narrow traffic lane when an oncoming car is approaching...Slow down and let the car pass, then pass the bicyclist.
  10. When driving on a slippery surface such as snow or ice...Shift to a low gear before going down steep hills.
  11. If you are driving on a two-way street and you want to turn left at an upcoming corner, give the right-of-way to... Vehicles coming towards you.
  12. When you see a vehicle stopped on the right shoulder of the road ahead with its hazard lights on, slow down and pass very carefully.
  13. Vehicles displaying a diamond-shaped sign... must stop before crossing railroad tracks.
  14. You must notify DMV within 5 days if you...sell or transfer your vehicle.
  15. It helps to improve traffic flow if you... do not slow down to look at an accident scene.
  16. Bridges freeze first when wet.
  17. It is a proper use of vehicle lights to... use low beams during the day on narrow country road.
  18. If you were parked and have been waiting a long time in heavy traffic with your turn signal on to re-enter traffic...continue waiting and yielding to traffic in the lane.
  19. Allow extra space in front of your vehicle... when following a motorcycle.
  20. It is legal to drive with an open alcoholic beverage container if the container is...in the trunk.
  21. You must show proof of insurance to law enforcement...if you are involved in an accident or stopped for a citation.
  22. If there is a double solid yellow line dividing opposite lanes of traffic, you may...cross over the lines to make a left turn from or into a side street.
  23. It is a safe driving practice to...check your rearview mirrors frequently.
  24. You can make a right turn at a solid red light after you check for pedestrians and other traffic if you... stop first and if there is no sign to prohibit the turn.
  25. When parking downhill on a two-way road with no curb, turn your front wheels… Right - towards the side of the road.
  26. You may drive across a sidewalk to... enter or exit a driveway or alley.
  27. When merging onto a freeway, you should be driving...at or near the same speed as the freeway traffic
  28. If you want to turn right and your driving lane is next to a bicycle lane, merge into the bicycle lane before making your turn.
  29. When you see an emergency vehicle with flashing lights behind you. What should you do, drive to the right edge of the road and stop.
  30. If you drive 55 mph in a 55 mph zone, you can be given a speeding ticket…If road or weather conditions require a slower speed.
  31. If the driver ahead of you stops at a crosswalk, stop, then proceed when all pedestrians have crossed.
  32. You must notify DMV within 5 days if you Sell or transfer your vehicle.
  33. You see a car approaching from the rear. When you check your mirror again to change lanes but you no longer see the car. You should Look over your shoulder to be sure the car isn't in your blind spot.
  34. You park your carat the curb on a level two-way street. Before getting out of your car, you should Look for cars or bicycles on the traffic side of your vehicle.
  35. It's yours responsibility is it to know how your medications affect your driving?
  36. You are crossing an intersection and an emergency vehicle is approaching with a siren and flashing lights. You should continue through the intersection, pull to the right, and stop. 
  37. If a driver looks like he or she is going to pull out in front of you, the safest thing to do is Slow or stop your car and use your horn
  38. If you are unable to see the road ahead while driving because of heavy fog and your wipers do not help, you should: Pull off the road completely until visibility improves. 
  39. A red and white sign that reads “Do Not Enter” means: You may not enter the road from your direction 
  40. It is very foggy, you should slowdown, turn on your windshield wipers, and your Low beam lights
  41. Which of these is a legal U-turn?: On a highway where there is a paved opening for a turn
  42. You are driving 55 mph on a two-lane highway, one lane in each direction, and want to pass the car ahead of you. To pass safely, you need to have a large enough gap in the oncoming traffic.
  43. Who has the right-of-way at an intersection with no crosswalks? : Pedestrians always have the right-of-way
  44. Smoking inside a vehicle when a person younger than 18 years of age is present is Illegal at all times.
  45. A yellow sign with the picture of a pedestrian means: There is a pedestrian crosswalk ahead
  46. If five or more vehicles are following you on a narrow two-lane road: Pull off the road when it is safe and let them pass.
  47. When sharing the road with a light rail vehicle: Never turn in front of an approaching light rail vehicle
  48. You may drive off of the paved roadway to pass another vehicle: Under no circumstances
  49. You are approaching a railroad crossing with no warning devices and are unable to see 400 feet down the tracks in one direction: The speed limit is:15 mph
  50. When parking your vehicle parallel to the curb on a level street:Your wheels must be within 18 inches of the curb.
  51. When you are merging onto the freeway, you should be driving:At or near the same speed as the traffic on the freeway.
  52. A white painted curb means: Loading zone for passengers or mail only.
  53. A school bus ahead of you in your lane is stopped with red lights flashing.You should: Stop as long as the red lights are flashing.
  54. California's "Basic Speed Law" says: You should never drive faster than is safe for current conditions.
  55. To avoid last minute moves, you should be looking down the road to where your vehicle will be in about : 10 to 15 seconds.
  56. You are about to make a left turn. You must signal continuously during the last __100__ feet before the turn.
  57. Large trucks have bigger blind spots than most passenger vehicles.
  58. You have been involved in a minor traffic collision with a parked vehicle and you can't find the owner. You must Leave a note on the vehicle. AND Report the Accident without delay to city police or in unincorporated areas to the CHP.
  59. Unless otherwise posted the speed limit in a residential district is 25 mph.
  60. You may legally block an intersection: Under no circumstances.
  61. When parking uphill on a two-way street with no curbs, your front wheels should be: Turned to the right (away from the street).
  62. With a Class C drivers license a person may drive: A 3-axle vehicle if the Gross Vehicle Weight is less than 6,000 pounds.
  63. To turn left from a multilane one-way street onto a one-way street, you should turn from: The lane closest to the left curb.
  64. If you are involved in a traffic collision, you are required to complete and submit a written report (SR1) to the DMV: If there is property damage in excess of $750 or if there are any injuries.
  65. Roadways are most slippery: The first rain after a dry spell
  66. You may not park your vehicle: Next to a red painted curb
  67. Two sets of solid, double, yellow lines that are two or more feet apart: May not be crossed for any reason.
  68. You want to make a right turn at an upcoming intersection. You should: Signal for 100 feet before turning
  69. You are driving on a freeway posted for 65 MPH. The traffic is traveling at 70 MPH. You may legally drive: No faster than 65 mph.
  70. It is illegal to park your vehicle: In an unmarked crosswalk.
  71. The safest precaution that you can take regarding the use of cellphones and driving is: Use hands-free devices so you can keep both hands on the steering wheel.
  72. If you have a green light, but traffic is blocking the intersection, you should: Stay out of the intersection until traffic clears.
  73. You are getting ready to make a right turn. You should: Slow down or stop, if necessary, and then make the turn.
  74. You must obey instructions from school crossing guards: At all times.
  75. It is a very windy day. You are driving and a dust storm blows across the freeway reducing your visibility. You should drive slower and turn on your: Headlights.
  76. If you plan to pass another vehicle, you should: Not assume the other driver will make space for you to return to your lane.
  77. If you drive faster than other vehicles on a road with one lane in each direction and continually pass the other cars, you will: Increase your chances of an accident.
  78. Which of these vehicles must always stop before crossing railroad tracks? Tank trucks marked with hazardous materials placards.
  79. You are driving on a one-way street. You may turn left onto another one-way street only if: Traffic on the street moves to the left.
  80. A large truck is ahead of you and is turning right onto a street with two lanes in each direction. The truck: May have to swing wide to complete the right turn.
  81. You may cross a double, yellow line to pass another vehicle, if the yellow line next to: Your side of the road is a broken line.
  82. At intersections, crosswalks, and railroad crossings, you should always: Look to the sides of your vehicle to see what is coming.
  83. You drive defensively when you: Keep your eyes moving to look for possible hazards
  84. You are driving on the freeway. The vehicle in front of you is a large truck. You should drive: Farther behind the truck than you would for a passenger vehicle.
  85. All of the following practices are dangerous to do while driving. Which of these is also illegal?: Listening to music through headphones that cover both ears.
  86. Always stop before you cross railroad tracks when: You don't have room on the other side to completely cross the tracks.
  87. Should you always drive slower than other traffic? No, you can block traffic when you drive too slowly.
  88. You see a signal person at a road construction site ahead. You should obey his or her instructions: At all times.
  89. When can you drive in a bike lane? When you are within 200 feet of a cross street where you plan to turn right.
  90. You see a flashing yellow traffic signal at an upcoming intersection. The flashing yellow light means: Slow down and cross the intersection carefully.
  91. There is no crosswalk and you see a pedestrian crossing your lane ahead. You should: Stop and let him/her finish crossing the street.
  92. A solid yellow line next to a broken yellow line means that vehicles: Next to the broken line may pass.

  93. It is legal to use a cell phone without hands-free device *for emergency reasons*.
  94. Which of these statements ... is true: *most cold medications can make a person drowsy*.
  95. When you change lanes or merge, you need *at least 4 second gap in traffic*.
  96. Cargo extending more than 4ft from your rear bumper *must be marked with a red flag or lights*.
  97. The speed limit in any alley is *15mph*.
  98. A peace office is signalling you to drive to the edge of the roadway, but you ignore his warning and flee. You can be *jailed in the county jail for not more than 1 year*.
  99. You should stop before railroad tracks *any time a train may be approaching, whether or not you can see it*.
  100. If you see a pedestrian with guide dog or white cane waiting to cross at a corner, you should: *pull up to the crosswalk so the person can hear your engine*.
  101. If you are towing another vehicle or trailer on a freeway with 4 lanes in your direction, you may travel in: Either of the 2 right lanes.
  102. When driving near road construction zones, you should: Pass the construction zone carefully and avoid "rubbernecking"
  103. If you approach an intersection without a stop sign or signals, you: should slow down and be ready to stop if necessary
  104. You Should usually drive your vehicle more carefully when you -- Are near schools,playgrounds,and in residential areas.
  105. If you are involved in an accident, exchange with other persons involved -- Licence Information,Proof of insurance,vehicle registration,and curent address.
  106. Do not cross double solid yellow lines in the center of the roadway to-- Pass other vehicles.
  107. Where should you stop your vehicle if thee is no crosswalk or limit line--At the corner.
  108. There is one lane in your direction and the vehicle ahead of you often slows down for no apparent reason.In this situation you should -- Increase the following distance between you and other vehicle.
  109. Use your high-bean headlights at night-- whenever it is legal and safe.
  110. You are involved in a minor collision at an intersection there are no injuries and very little damage you should
  111. Move your vehuicle out of the traffic lane if possible
  112. Backing your vehicle is Always dangerous
  113. You are on the freeway and traffic is merging into your lane you should : Make room for merging traffic if possible
  114. If you are riding in a car equipped with a lap and shoulder belt you are required to wear: Both lap and shoulder belts
  115. When driving on a multilane street with two way traffic: You should drive ahead or behind the other vehicles
  116. When parking next to a curb you should use your turn signals: When pulling next to or away from the curb
  117. You reach an intersection with stop signs on all four corners at the same time as the driver on the left who has the right of way?: You have the right of way
  118. A flashing yellow traffic signal at an intersection means : Slow down and be alert at upcoming intersection
  119. A flashing red light at an intersection means: Stop before entering
  120. To turn left from a one way street with multiple lanes onto a two way street start the turn at the far left lane
  121. for which of the following traffic lights must you always stop your vehicle? ... solid red lights, flashing red lights, and blacked-out traffic signals
  122. which of these statements is true about child passengers? ... children under the age one should not ride in the front seat in airbag-equipped vehicles
  123. two vehicles are approaching an uncontrolled "T" intersection. one vehicle is on the through road and the other is on the road that ends. who has the right-of-way at the intersection? ... the vehicle on the through road
  124. the speed limit for a school zone where children are present is ____. ... 25 mph
  125. A peace officer is signaling you to drive to the edge of the roadway. you decide to ignore the officer's warning and flee the scene. you are guilty of a misdemeanor and can be punished by being: ... jailed in the county jail for not more than one year.
  126. which of these statements is true about driving and taking medications? ... most cold medications can make a person drowsy
  127. Instructions from school crossing guard must be obeyed: ... at all times
  128. Trucks often appear to travel slower because of their large size
  129. If there is a deep puddle in the road ahead, you should: ... avoid the puddle, if possible
  130. You should adjust your rear view and side view mirrors: ... before you start driving
  131. Smoking inside a vehicle when a person younger than 18 years of age is present is: ... illegal at all times
  132. You must make a written report of traffic accident occurring in california (sr 1) to dmv if you: ... are involved in a collision and there is more than $750 in damage
  133. You are required to wear your safety belt in a moving vehicle: and failure to do so will result in a traffic ticket
  134. you are crossing an intersection and an emergency vehicle is approaching with a siren and flashing lights. you should: ... pull to the right in the intersection and stop
  135. you are on a two-way road and the vehicle ahead of you is turning left into a driveway. you may legally pass on the right: ... if there is enough road between the curb and the vehicle
  136. If you have a green light, but traffic is blocking the intersection: ... stay out id the intersection and wait until trafic clears
  137. which statement is true about motorcyclists and motorists? ... motorcyclists have the same rights/responsibilities as other motorists
  138. You are driving in the far right lane of a four-lane freeway and notice thick broken white lines on the left side of your lane. you are driving in: ... an exit lane
  139. when driving near road work zones, you should: ... pass the work zone carefully and avoid "rubbernecking"
  140. If five or more vehicles are following you on a narrow two-lane road: ... drive into the turnout areas or lanes to let them pass
  141. which of these are a legal u-turn? ... on a divided highway where there is a paved opening for a turn
  142. you see a car approaching from the rear. when you check your mirror again to change lanes, you no longer see the car: ... look over your shoulder to be sure the car isn't in your blind spot:
  143. if you are towing another vehicle or trailer on a freeway with four lanes in your direction, you may travel in: either of the two right lanes
  144. you are approaching a sharp curve in the road. you should; ... start braking before you enter the curve
  145. when parking on any hill, always set your parking brake and: ... leave you r vehicle in gear or the "park" position
  146. all children under age six riding in your vehicle must use a child passenger restraint system unless: ... they weigh 60 pounds or more and wear a safety belt
  147. this yellow sign means: ... there is a pedestrian crossing ahead
  148. this lane in the middle of a two-way street is used to: ... begin or end left turns, or start a permitted u-turn
  149. it is a good habit to signal continuously during the last 100 feet before you turn at an intersection: ... even if you do not see any other vehicles around
  150. when sharing the road with a light rail vehicle: ... never turn in front of an approaching light rail vehicle
  151. you are driving at night on a dimly lit street and using high beams. you should dim your lights when you are within 500 feet of: ... a vehicle approaching you from behind
  152. allow extra space in front of your vehicle when following a: ... large tour bus
  153. even if you know your vehicle can maneuver a sharp curve at the legal speed limit, you should still slow down because: ... there may be a stalled car or collision ahead that you can't see
  154. you park your car at the curb on a level two-way street. before getting out of your car, you should: ... look for cars or bicycles on the traffic side of your vehicle
  155. who has the right-of-way at an intersection with no crosswalks? ... pedestrians always have the right-of-way
  156. if you approach a curve or the top of a hill and you do not have a clear view of the road ahead, you should: ... slow down so you can stop if necessary
  157. which of the following is true about safety belts and collisions? ... they increase your chances of survival in most types of collisions
  158. if you are unable to see the road ahead while driving because of heavy fog and your wipers do not help, you should: ... pull off the road completely until visibility improves
  159. You should increase the distance between your car and the vehicle ahead when you........are being tailgated by another driver.
  160. U-turns in business districts are........legal only at intersections, unless a sign prohibits them.
  161. If you are convicted of driving with an excessive blood alcohol concentration(BAC), you may be sentenced to serve........up to six months in jail.

  162. When you see this yellow sign (cross within a circle and two "R's") you......are approaching a railroad crossing; prepare to stop.
  163. When you see this red and white sign (an eight-sided figure with STOP written), you should stop and......check traffic in all directions before proceeding.
  164. When you want to turn left at an upcoming corner, give the right-of-way to:......all approaching vehicles.
  165. Check your rearview mirrors......often to see how traffic is moving behind you.
  166. You enter a designated turn lane to make a left turn at an upcoming intersection. There is oncoming traffic. You should......signal before you arrive at the intersection.
  167. Your driving lane is next to a bicycle lane. You want to make it right turn at the upcoming intersection. You......must merge into the bicycle lane before making your turn.
  168. You are approaching an intersection at the posted speed limit when the signal light turns yellow. You should......stop before entering the intersection, if you can do so safely.
  169. There are five vehicles following closely behind you on a road with one lane in your direction. When you see this white sign (square saying "slower traffic use turnouts") you should......drive to the side of the road into the designated area.
  170. You see a pedestrian with a white cane at the corner ready to cross the street. The person takes a step back and pulls in his cane. You should......stop and then proceed through the intersection because the person is not ready to cross.
  171. You are driving on a divided street with multiple lanes in your direction. If you need to make a U-turn, where should you start?....In the left lane.
  172. You are driving on a five-lane freeway in the lane closest to the center divider. To exit the freeway on the right you should....Change lanes one at a time until you are in the proper lane.
  173. Which of these is true about other drivers?....Never assume other drivers will give you the right-of-way.
  174. What is the best advise for driving when heavy fog or dust occurs?....Try not to drive until the conditions improve.
  175. On a sharp curve, you should use your brakes to slow your vehicle... Before you enter the curve.
  176. It is legal to leave a child six years of age or younger unattended in a motor vehicle....If the child is supervised by a person 12 years or older.
  177. Turn your front wheels toward the curb when you park ....Facing downhill
  178. Always look carefully for motorcycles before you make a turn because....their smaller size makes them harder to see
  179. Driving slowly in front of traffic in the far left (fast) lane on a freeway... Can frustrate other drivers and make them angry
  180. If the road is wet from a heavy rain, you should... Increase the distance between your vehicle and the car ahead
  181. When driving a vehicle with air bags, you are safest when seated... At least 10 inches away from the steering wheel
  182. You are being chased by a police vehicle with its light and sirens activated. You ignore the warning to stop and speed away. During the chase, a person is seriously injured. You are subjected to... Imprisonment in a state prison for up to seven years
  183. Orange-colored road signs warn you of... Road workers or road equipment ahead
  184. In California, anyone who drives a motor vehicle has consented to take a chemical test for the alcohol content of his or her blood, breath, or urine... If asked by a law enforcement
  185. Large trucks are most likely to lose speed and cause a hazard... Going up long or steep hills
  186. If you cannot stop safely at a yellow traffic light, you should... Enter the intersection cautiously and continue across
  187. When sharing the road with a light rail vehicle, you... Should monitor all traffic signals closely because light rail vehicles can interrupt traffic signals
  188. Driving along the right-rear side of another vehicle is... Dangerous because you're probably in one of the driver's blind spots
  189. To help avoid skidding on slippery surfaces you should .... Slow down before entering curves and intersections.
  190. You are driving and there are oncoming cars on your left and a row of parked cars on your right. You should steer: ... A middle course between the oncoming and parked cars.
  191. Yellow lines separate: ... Traffic moving in opposite directions on a two-way road.
  192. Three of the most important times to check traffic behind you are before: ... Backing, changing lanes, or slowing down quickly.
  193. A safety zone is a specially marked area for passengers to get on or off buses or trolleys. You may not drive through a safety zone: ... At any time or for any reason.
  194. Which of these statements is true about drinking alcohol and driving?: ... Alcohol affects judgement, which is needed for driving safely.
  195. You can be fined up to 1000 and jailed for six months if you are cited for Dumping or abandoning an animal on a highway.
  196. It is illegal to leave a child six years of a ge or younger unattended in a motor vechile: when the keys are in ignition.
  197. you are driving at night on a dimly lit street and using high beams. you should dim your lights when you are within 500 feet of : An oncoming vehicle
  198. You are approaching a sharp curve in the road you should : start breaking before you enter the curve.
  199. Car parked on any hill. always set your parking brake and : leave your vehicle in gear or the "park" position.
  200. Allow extra space in front of your vehicle when following a : large tour bus.
  201. To see vehicles in your blind spots, you must-turn your head
  202. When driving near construction zones, you should-reduce speed and be prepared to stop.
  203. You can be fined up to $1,000 an jailed for 6 months if you are cited for-dumping or abandoning an animal on a highway.
  204. Other drivers are not making room for you to merge onto a freeway with heavy traffic. if necessary, you may-stop before merging with freeway traffic.
  205. for the first 12 months after you are licensed, you must be accompanied by your parent or guardian if you-transport minors between the hours of 11pm and 5am.
  206. It is illegal for a person under 21 years of age to drive with a blood alcohol concentration (BAC) that is -o.01% one hundredth of one percent- or more. (this 1 tricks you! so be careful)
  207. This yellow sign (a diamond shaped sign with a plus sign inside)means-another road crosses yours ahead.
  208. When driving in the far right lane of a freeway. you-should expect merging vehicles at on-ramps.
  209. You are approaching an uncontrolled intersection. you-should slow down and be ready to stop.
  210. If 5 or more vehicles are following you on a narrow two-lane road-pull off the road when it is safe and let them pass.
  211. If you approach a curve or the top of a hill and you do not have a clear view of tne road ahead, you should-slow down so you can stop if necessary.
  212. You can be fined up to $1000 and jailed for six months if you are sited for: Dumping or abandoning an animal on a hwy.
  213. When changing lanes on a freeway, you should:Signal for at least five seconds.
  214. Bicycle:
    1. Maintain minimum distance of 3ft from bicycle.
    2. While making right, merge to bicycle lane 200ft, ensure to give sufficient space to any bicycle rider.
    3. Bicycle rider 
      1. should be visible from 300 ft in front.
      2. rear red reflector should be visible from 500 ft.
      3. while / yellow reflector on pedal or bicyclist shoe / ankle should be visible from 200 ft.
  215. Motorcycle:
    1. Maintain 4 sec gap for motorcycle riders.
    2. Motorcycle - Lane splitting - not illegal but unsafe.
  216. Exists:
    1. Go to proper lane.
    2. 5 sec before reading exit
    3. proper speed for leaving traffic lane - not too fast or not too slow.
  217. Speed Limit:
    1. School: 25 mph, some school: 15 mph
      1. School Bus violation: $ 1000 or 1 year in prision.
    2. Blind Intersection (not able to see 100 ft in either direction): 15 mph
    3. Alley: 15 mph
    4. Near rail road track (without gates - cannot see 400 ft): 15 mph - 100 ft from rail road crossing.
    5. Streetcars, Trolley, Buses: 10 mph 
    6. Residential: 25 mph
  218. Parking:
    1. Parallel parking:
      1. 3 ft longer that vehicle.
      2. 2 ft away from & bumper inclined
        1. First steering toward curb.
        2. Then away from curb.
      3. ensure both tires remain inside 18 inches to curb.
    2. hill / steep parking:
      1. down hill: inclined your tires toward the curb.
      2. uphill: inclined your tires away from curb.
    3. White: stop for pickup or drop off passenger.
    4. Green: limited time parking
    5. Yellow: stop no longer than posted time.
    6. Red: no stopping at any time.
    7. Blue: Parking for disabled - violators - 6 months Jail and / or $ 1000 penalty
    8. No parking 7 1/2 ft from rail road track.
    9. In case need to park on freeway, pull out of lanes - make it visible 200 ft and remain inside vehicle.
  219. Headlight:
    1. Headlight on: adverse weather conditions (fog, frost, cloud, rain, snow, dust, smoke) or visibility less than 1000 ft.
    2. Mountain roads: headlight on during day time.
    3. bring them on, when necessary to get another driver attention.
    4. turn them on.. 30 mins after sunset
    5. leave then on until.. 30 mins before sunrise.
    6. Dim your light to low beam 
      1. 500 ft vehicle coming toward you.
      2. 300 ft vehicle your are following.
  220. Horn:
    1. narrow mountain road & you cannot see 200 ft ahead of your vehicle.
  221. Turns:
    1. Left Turn:
      1. Left turn signal during last 100 ft before making turn.
      2. check left. right and left
      3. wheel should be straight.
    2. Right Turn:
      1. Right turn signal during last 100 ft before making turn.
      2. safely use bicycle lane 200 ft for making turn.
    3. U-Turn:
      1. Residential: check 200 ft no vehicle approaching you.
  222. Driving tactics:
    1. Pull-Push Steering: Pull with one hand.. push with other hand.
    2. Hand-over-hand Steering: Sharp right turn, backing and skid.
    3. One-hand-Steering: Info, backing, safety and comfort.
  223. Driving License:
    1. DMV Test Include:
      1. Vision Test:
      2. A test of traffic law and road signs:
      3. Behind-the-wheel driving test if required.
    2. License C-Class:
      1. 2 axle - 26000 lbs or less
      2. 3 axle - 6000 lbs or less
      3. House car: 40 ft or less
      4. 3 wheel motorcycle
      5. vanpool vehicle designed to carry 10 person but not more than 15 person including driver.
    3. Visitors 18 years older: can drive till their DL valid.
    4. Visitor 16-18 years: can drive for 10 days.
    5. Minor License: 
      1. Must be 15 1/2 - 18 years years older
      2. DL-44, parent , guardian, if joint custody then both parents sign the documents.
      3. Must complete Driving Education
      4. Must complete Training Progarm
      5. Accompany with adult - 25 years of age or older.
      6. 50 % of violation drivers between 15-19 years, speeding , loss of vehicle, fatal accident chances are 2 1/2 times than average drivers ( 18 years or older).
      7. Alcohol or DUI (Driving under Influence): 13-21 years - DMV suspend your DL for 1 year or delay by a year.
      8. Warnings:
        1. 1st Incident: 1 warning
        2. 2nd Incident: 30 days suspend (with 25 years older)
        3. 3 rd incident: suspend for 6 months.
  224. Financial Responsibility:
    1. Motor vehicle liability insurance policy.
    2. A deposit of $ 35000 with DMV
    3. A surety bond of $ 35K from company licensed to do business in CA.
    4. A DMV issued self-insurance certificates:
      1. $15K single death or injury.
      2. $30K death or injury of more than one person.
      3. $5k for property damage.
  225. Collision on your record:
    1. property damage of more than $750 in either party.
    2. Injured or dies.
    3. Points:
      1. 4 point - 12 months
      2. 6 point - 24 months
      3. 8 point - 36 months
    4. Court can cancel your DL for up to 2 years for person in vandalism or graffiti or delay by 3 years.
  226. Evading a police officer- 1 year,  body injury in police pursuit - 3, 5, 7 years in state or less than a year in county Jail.
  227. Drugged Driving Law:
    1. BAC (Blood Alcohol Content) : 
      1. 0.08 % or more
      2. 0.04 % or more for commercial vehicle
      3. 0.01 % if under 21
        1. substract 0.01 % for each 40 min of drinking.
      4. 1 drink = 1.5 oz 80 poof liquor, 12 oz.. 5 % beer or 5 oz 12 % wine.
      5. Only un-opened, sealed container can be kept inside vehicle, opened can be kept inside unreachable trunk.
      6. Under 21 years: alcohol cannot be kept inside vehicle. $1000, suspended driving privilege or delay by a year.
      7. DUI (Driving under Influence)
        1. 0.01 % or higher: suspend for a year
        2. 0.05 % or higher: suspension and DUI arrest: 6 months Jail and file - $390-$1000 ( 3 times fine in penalty assessment).
    2. Designated Driver Program: Designated driver should not drink and is responsible for all other passenger in vehicle.
    3. Do not smoke at any time when the minor is in the vehicle, you can be fined up to $ 100.
  228. Few Do nots:
    1. Do not dump or abandon animal on highway- $1000 and/or 6 months Jail.
    2. Do not carry anything in or on a passenger vehicle which extends beyond the fender on left side or more than 6 inches beyond the fender on right side, cargo extending more than 4 feet from the back of vehicle, must display red or fluorescent orange square flag.
    3. Do not leave child or animal alone in vehicle.
    4. Littering will be fined by $ 1000 and you will be forced to pick up.
    5. Do not drive a vehicle equipped with a video monitor is visible to driver and display anything other than vehicle information, MP3 , GPS or satellite Radio.
    6. Do not drive any vehicle into designated wilderness area.
    7. Peace officer, bus, streetcar , trolley: you may pass not more than 10 mph.
    8. Do not overtake or pass any light rail vehicle or streetcar on the left side whether it is moving or standing.
    9. It's illegal to follow 300 ft behind any fire engine, police vehicle, ambulance or other emergency vehicle with a siren or flashing lights.
    10. NEV: Neighbor Electricity vehicle
    11. LSV: Low speed vehicle
  229. Few Dos:
    1. Move over and slow down for emergency vehicle.
    2. Inform DMV if you lost of driving license.
    3. Name change - update SSA before coming to DMV
    4. Update address within 10 days when you move, new card will not issue for change of address.



Reference: DMV Handbook.