Sunday, 16 April 2017

Checked and Unchecked Exception in java

Two categories of Exception that we come across are:

Checked Exception:

Checked Exception extends java.lang.Exception

If there is possibility that the code written may result in throwing exception then compiler senses it and reminds programmer to handle such codes in either of these two ways during compilation:
  • enclose code within try/catch
  • declare the exception using throws keyword
At the very basic level you can think of it as exceptions which are caught at the compile time.


For example,

You have a code where you want to read a file from particular location  say ("D:\\JavaFiles\\myFile.txt")


import java.io.*;

class MyFileReader {

    public static void main(String[] args) {

        FileReader file = new FileReader("D:\\JavaFiles\\myFile.txt");
        BufferedReader fileInput = new BufferedReader(file);
         
        // Print first 4 lines of file "C:\test\a.txt"
        for (int counter = 0; counter < 4; counter++)
            System.out.println(fileInput.readLine());
         
        fileInput.close();
    }
}

What would be fate of above code?

It is sure to throw compile time error.

Reason being the presence of FileReader which throws Checked Exception FileNotFoundException and readLine & close which throws checked exception IOException.

In order save your code from compile time error enclose the code within try/catch block. Or declare all Exceptions that could possibly occur using throws like this,


 public static void main(String[] args) throws IOException


Since FileNotFoundException is the child (sub class) of IOException so declaring only IOException using throws will serve the purpose here.

ExamplesSQLExceptionClassNotFoundExceptionIOExceptionetc




Unchecked Exceptions:

Unchecked Exceptions extends java.lang.RuntimeException

Unchecked Exceptions are those that goes beyond the range of compilers and escapes their notice. It occurs due to error in programming logic. There are exceptions which can only be detected at run time such as illogical codes. 

Like, a code where you perform division by 0(zero) or you try to access value from an index which is not present in the array. 

These kind of code will compile fine and will look perfect until run. So unchecked Exception are run time exceptions.

For example consider this code,

class MyFile {

    public static void main(String[] args) {
         
        // Division by 0
        int x = 5/0; // illogical code will throw ArithmeticException
        System.out.println(x);
    }
}

The above code will not show any compile time error. But if you run it, you will find ArithmeticException.

So as a programmer you are never expected to write a code like,
int i=5, int j=0;
int k=i/j;

because it is loop hole in coding logic and will show its erroneous face while you run it and will result in abrupt termination of your code if it is not taken care by try/catch block.
And if you write such code then you have to waste lot of time in debugging your code and find out this kind of logical error.

ExamplesArithmeticExceptionArrayIndexOutOfBoundsException,NullPointerExceptionsetc




You may also like to read:


Saturday, 8 April 2017

Why java is secure as programming language?

Java is considered as portable and secure in nature.

For understanding portability nature(read here).

Now lets concentrate on security aspect of java. There are many security feature provided by the security manager present in JVM.

So as far as I  have found out there are numerous angle which helps java to achieve security. I will explain all those aspects below:

1. At first security is provided by JVM(Java Virtual Machine) by checking the .class files for any malicious virus or threats that is presented to it before executing those files. So bytecode verification by JVM adds to security.

2. Memory security is provided by the Memory Management architecture of java. (Read more)
Here garbage collector starts its task of collecting the garbage objects as soon as it senses that out of memory condition is about to reach or even before it.

Programmer don't need to take any headache of releasing the memory space manually as is in other languages. Here JVM controls the garbage collector and it does this task for you. Manually programmer can also give instruction to garbage collector to run but then in that case also JVM has full decision control of whether to run it or not.(Read more)

3. Java Package concept provides security from namespace collision in java.

4. Access modifier like public, private, protected and default defines the level to which a class/method/variable can be exposed. So depending upon the level of exposure needed these access modifiers can be used.
In this way we can secure the data from unintended user who is in no way concerned with it thus protecting it from getting misused.

5. Immutability of String adds to security as well. Because of immutable nature String can be used to store password/username, database connection(& other details), key in HashMap without worrying much about String getting tampered/or modified by unauthorized/malicious user.


If you know about any other aspects that add to security of java then please help us know in the comment box.


You may also like to read:

Tuesday, 4 April 2017

String[ ] args parameter in java main()

In java when one supply parameter(s) from command line then this String[] args comes into play.

It holds the parameters passed from command line as an array of String objects.

Lets consider this example:

File: Example.java

class Example{
       public static void main(String[] args){
           for(int i=0; i<args.length; i++){
               System.out.println(args[i])
           }
       }
}

Compile this program: javac Example.java
Run this program by passing command line argument: java Example 12  13  14

Then args will contain array of String as ["12","13","14"]

And when you loop through the args, the output will be:
12
13
14

Getting printed on new line because of ln in println where ln indicates new line.


Note:

  • args is not necessarily bound to be named so. What I mean to say is you can give it any name(eg, a or abc or xyz).
  • It could also be written as String... args


Read more:

Explain public static void main(String[ ] args) in java.

Each word has certain meaning associated to it. 
Let’s find out what each word means:

public

public keyword is an Access Modifier. It tells that the main() method can be accessed by any class irrespective of the package to which it belongs.

static

The static keyword signifies that the main() method is a class method. To access it one does not require to create instance of the class to which this method belongs.

This is the reason that JVM is able to call this method even before any instance of the class containing main() is created.

void

void is just a return type. The void in the code signifies that the main() method is not going to return any value.

main()

This is the name of the method.
main() method is the entry point of any core java program. When you run your code, JVM search for this method with the same signature as shown in the code above.

String args[]

It is used for the command line argument. (working of String[] args)

System.Out.Print()

It is used to print the statement. (See internal working here)

Saturday, 1 April 2017

Difference:Collection vs Collections in java

Collection and Collections in java differs based on following parameters:

1.      Basic
Collection is the base interface of java collection framework in java.util package. 
In the below given diagram you can see that Collection is base interface and List, Set, etc extends it.


Collection interface by Java Radar
Collection interface

Collections is a utility class in java.util package.


2.      Purpose
Collection interface is the root of which interface like List, Set, Queue, etc form sub-interface.

Collections class consists of only static methods that can be used to perform operation on objects of type Collection.

For example,

*click each listed example to see programmatic explanation

     In above example you can see that all methods like sort(), binarySearch, etc are static method which can be directly called using class name(Collections). For calling static method you don't need to create instance and thus these methods become simple to use while working on collection classes like array list, linked list, hashset, etc.



You may also like to read:
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
If you are looking for a reference book on java then we recommend you to go for → Java The Complete Reference
Click on the image link below to get it now.