Friday, October 23, 2015

Synchronized Keyword


Synchronized is a keyword use for thread concepts. There are chances when two or more threads are trying to access same resource. At this point, program will get stuck or hang. So to come over this situation java has synchronized keyword.
We just need to share those resources to synchronized block.



public class TryCatch {
       public static void main(String args[]) {

              CounterDemo counterDemo = new CounterDemo();

              ThreadDemo thread1 = new ThreadDemo("Thread - 1 ", counterDemo);
              ThreadDemo thread2 = new ThreadDemo("Thread - 2 ", counterDemo);

              thread1.start();
              thread2.start();

              try {
                     thread1.join();
                     thread2.join();
              } catch (Exception e) {
                     System.out.println("Interrupted");
              }
       }
}

class CounterDemo {
       public void counterCount() {
              try {
                     for (int i = 0; i <= 10; i++) {
                           System.out.println("Counter   ---   " + i);
                     }
              } catch (Exception e) {
                     System.out.println("Thread  interrupted.");
              }
       }

}

class ThreadDemo extends Thread {
       private Thread thread;
       private String threadName;
       CounterDemo counterDemo;

       ThreadDemo(String name, CounterDemo counterDemo) {
              threadName = name;
              this.counterDemo = counterDemo;
       }

       public void run() {

              /*
               * Try to run this code with uncomment and comment line 53. You will see
               * the difference
               */
             
              // counterDemo.counterCount();

              synchronized (counterDemo) {
                     counterDemo.counterCount();
              }

              System.out.println("Thread " + threadName + " running...");
       }

       public void start() {
              System.out.println("Starting " + threadName);
              if (thread == null) {
                     thread = new Thread(this, threadName);
                     thread.start();
              }
       }


}


Thursday, October 22, 2015

Instanceof Keyword


It is very common, when we get ClassCastException. To get over this, we have instanceof keyword.

instanceof keyword is use to check the object is a instance of specified type.

if (objectReference instanceof type)
The following if statement returns true.

public class TryCatch {
public static void main(String[] args) {

String name = null;
if (name instanceof java.lang.String) {
System.out.println("True");
} else {
System.out.println("False");
}
}

}

Above code will print True.


When we apply instanceof on a null variable, it returns False. Below is the code sample for reference.

public class TryCatch {
  public static void main(String[] args) {

    String name = null;
    if (name instanceof java.lang.String) {
      System.out.println("True");
    } else {
      System.out.println("False");
    }
  }

}


Is a child class also the instance of parent class? Answer is Yes and to prove this refre to the below code.

class Vehicle {

public Vehicle(){

}

}

class Car extends Vehicle {

public Car(){

super();
}

}


public class TryCatch {
public static void main(String[] args) {

Car car = new Car();
if (car instanceof Vehicle) {
System.out.println("True");
} else {
System.out.println("False");
}

}

}



Saturday, October 17, 2015

Exception Keywords


Try: Try is a keyword and a block comes under Exception handling tasks. Between this block, we write the tricky codes or the codes which may raise exception at runtime.

Catch: Catch is a keyword and a block. Which is use to handle the exceptions raise due to the code in try block. There can be multiple catch blocks with a single try block.

Finally: Finally is a keyword use to free the resources after the execution of code, written in try and catch block. This is the only block which will always execute, whether there is any exception or not.



Throw: Throw is use to generate custom exceptions, created by developer. We can generate both compile and runtime exceptions both. In this case, declared methods will handle the exception

Throws: Throws keyword is use to define, what type of exception may occur while execution of the method. The implementing class will handle the exception.




TryCatch




Exception


What is Exception?

Exception is an episode that breaks the flow of program. Exceptions can handle in java by using handling method.

Now, let’s discuss about exception in brief.



Exceptions are of two types, CompileTimeException and RunTimeException.

CompileTimeException: This type of exception also known as Checked Exception. It means the exceptions which are caught at time of coding by compiler. If there is exception then, it must be handled or specify the exception using throws keyword.

Example, you write a java program that read a file from location “C:\java\file.txt” and prints text written in it. The program doesn’t compile, because the function main() uses FileReader() which throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw IOException.

import java.io.*;

public class FileReadOperation {

       public static void main(String[] args) {
              FileReader file = new FileReader("C:\\java\\file.txt");
              BufferedReader fileInput = new BufferedReader(file);

            for (int counter = 0; counter < 5; counter++)
                     System.out.println(fileInput.readLine());

              fileInput.close();
       }

}

  



RunTimeException: This type of exception also known as Un-Checked and Error. It means the exceptions which are not caught at time of coding by compiler.

Example, below program compiles without any Checked Exception, but it throws ArithmeticException when run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.

public class Divide {

          public static void main(String args[]) {
                    int a = 0;
                    int b = 10;
                    int c = y/x;
                }

}


Error: Errors are those events which could not handle at developer’s level and may not even at the same time of error generation. Like any type of hardware and software problem. Example heap’s OutOfMemoryError.



http://www/try2catch.in

Tuesday, October 13, 2015

Modifier Keywords (Protected, Final, Abstract, Default)

Protected: Protected keyword can be use with variable, methods and constructor. These member only could be accessible to child class in different package and with in the class of same package.

Final: Final keyword can be use with variable, method and class. It behaves different in each case.

Variable: Final Variable could not be re-initializing. It must be initializing at the time of declaration.

Method: Final Method never overrides.

Class: Final class never extends.




Abstract: Abstract keyword can be use with a class and method. When a class defined as abstract, it means the class may have abstract methods or a method, which do not have it body or implementation.

When a class declared as abstract, it’s not necessary that the class has abstract methods. It can contain normal methods. But if, a method declared as abstract then the class must be declared as abstract.


Default: When we are not declaring any modifier with members, compiler automatically declares as default. A method and a variable can be declared as default. But, accessible within same package.