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.


Friday, September 25, 2015

Java Keywords (Return, Super, This)


Return: This keyword is a keyword. This can be use with methods, loops, and statements. The behavior of return is different with different scenarios.

1)   Methods: Return keyword is always used with method when the return type is not void. Return type of methods could be anything. The return value must be as the return type declared with method signature.

package com.demo;

public class DemoClass {

       public String getName() {

              String name = "Try Catch";

              return name;
       }

}


2)   Loops: In context of loops, return keyword used when we want to exit from loop. Here is no need to declare return value.

package com.demo;

public class DemoClass {

       public void getName() {

              while (true) {

                     System.out.println("Try Catch");

                     return;
              }
       }
}



Super: Super is a keyword which is use to access the members of super or parent class. To use super keyword, inheritance must be there. This keyword could use with following statements:

package com.demo;

public class SuperClass {

       String name = "Instance varibale of SuperClass";
      
       public SuperClass() {
              System.out.println("Super class constructor...");
       }
      
       void getName(){
              System.out.println("Method of Super class...");
       }

}


1)    Instance Variables: Super keyword use to access or call the instance variable of parent or super class into child or base class.


2)    Constructor: Using super keyword, we can call the constructor of super class. You will see that, while calling super class constructor there is () brackets. This is because; constructor is also like a normal method. So to tell compiler that, we are calling constructor not other members of super class, we have to use these brackets.

3)    Methods: Methods of super call can be access using super keyword.

package com.demo;

public class BaseClass extends SuperClass {

       String name = "Try Catch";

       public BaseClass() {
              super();
       }

       public static void main(String[] args) {

              BaseClass base = new BaseClass();

              base.getName();
              base.showMethod();
             
       }

       void getName() {
              System.out.println(super.name);
       }

       void showMethod() {

              super.getName();
       }

}


This: This keyword is to use to call all the members of same class rather than super class. Rest behavior is always same as super keyword.

package com.demo;

public class BaseClass extends SuperClass {

       String name = "Try Catch";

       public BaseClass() {
              System.out.println("Basse class constructor...");
       }

       public static void main(String[] args) {

              BaseClass base = new BaseClass();
              base.getName();
              base.showMethod();

       }

       void getName() {

              System.out.println(this.name);
       }

       void showMethod() {

              this.getName();
       }


}


Thursday, September 24, 2015

Java Keywords

(interface, abstract, import, implements)
http://www.try2catch.in

Interface: Interface is same as like a class. It is also contains methods and variables. But, behavior of the member is different. To declare a class as interface we just need to use interface keyword in place of class keyword. In case of use of the members of interface, you need to use implements keyword to get all the members in class. We could never make any object of an interface. This keyword is only use with a class to which we want to declare as interface. All the members are public.

1)   Variables: Variable of an interface is always public static and final.

2)   Methods: Methods of an interface are always abstract. In other words, they have only declaration not implementation.

package com.demo;

public interface InterfaceDemo {

       public static final String name = "Try Catch";

       public String showName();

}
  


Abstract: Abstract can be a class or method. It contains all normal member of a concrete class. To declare a class or method as abstract, we need to use abstract keyword. If a class is declared as abstract, it is not mandate that it should have at least one abstract method. To use any member of abstract class, we need to use extends keyword. But if a method is declared as abstract then the class must be an abstract class. Abstract method should not be private. Abstract class may have non abstract methods. It can have private members also. Abstract keyword can be use with class and method.



package com.demo;

public abstract class AbstractDemo {

       private String name = "Try Catch";

        abstract String showName();

       private void getName() {

              System.out.println(name);
       }

}

Implements: This keyword works same as extend keyword but to inherit the properties of an interface.

package com.demo;

public abstract class AbstractDemo implements InterfaceDemo {

@Override
public String showName() {
       // TODO Auto-generated method stub
       return null;
}


}

Import: To inherit the properties of any class, we need to give the full path of the class directory in form of packages.

package com.demo;

import com.demo.*;
public abstract class AbstractDemo  {


}


Tuesday, September 22, 2015

Architecture of JVM


1)   Class Loader
2)   Method Area
3)   Heap
4)   Stack
5)   PC Registers
6)   Native Method Stack
7)   Interpreter
8)   JIT




Let’s learn these concepts one by one.

Class Loader: It will load the class on request.

Method Area: Inside a Java virtual machine instance, information about loaded types is stored in a logical area of memory called the method area. When the Java virtual machine loads a type, it uses a class loader to locate the appropriate class file. The class loader reads in the class file, a linear stream of binary data and passes it to the virtual machine. The virtual machine extracts information about the type from the binary data and stores the information in the method area. Memory for class (static) variables declared in the class is also taken from the method area.

Heap: It is to store java objects. Size of heap is depends on JVM. It can be increase or decrease by developer also. All objects in heap are accessible by all threads. Whenever size of heap is full, JVM will throw an exception of OutofMemoryException.

Stack: It is to store the Methods and the structure of class like, variables, constructor, local variables etc. When the stack is full, JVM will throw StackOverflowException.


PC Registers: It contains address of JVM activity, which is currently being executed.

Native Method Stack: It stores all the native methods information.

Interpreter: It will read the java code and convert into the machine language supported by OS.

JIT: Just in Time compiles the machine language code into byte code.

Below is the architecture of JVM Memory Allocation.