Monday, 1 May 2017

All About "static"

All About "static"





Static means “no change”. In Java static is used with a variable or a class which is same for every instance. The variable marked as static is common for all the instances.

So why do we use static keyword, you ask?

It is used for optimizing the memory. By this I mean is that instead of making a separate copy of the same thing we can store it in one place and share it with others.

The static elements belong to the class. We do not have to instantiate the class to invoke the method or access the variable. We can simply write, class_name.variable  or class_name.method_name. The main() method in a Java program is static because the program execution starts from here. So, this method is invoked without any object creation.

We can use the static keyword with:

  1. variables
  2. methods
  3. block 
  4. nested class

Static variable or class variable

A variable declared as static is also called as class variable as we can directly access it using the class name:

class_name.statiVariable

You can change the value of a static variable. This is one of the main difference between a final and static variable:

public class StaticVariableExample {
   
    public static String SCHOOL_NAME = "KV";


    public static void main(String args[])
    {
       
        System.out.println(StaticVariableExample.SCHOOL_NAME);
        SCHOOL_NAME = "DY";
        System.out.print(StaticVariableExample.SCHOOL_NAME);
       
    }

   
}

The following program is a simple counter example:

package counterexample;


public class CounterExample {

    
    public static int COUNT = 0;
    CounterExample()
    {
        COUNT++;
        System.out.print(COUNT);
            
    
    }

    

    public static void main(String[] args) {
      
        
        CounterExample c1 = new CounterExample();
        System.out.println(c1);
        CounterExample c2 = new CounterExample();
        System.out.println(c2);
        
    }
    
}



This gave the following output:
1
2

The COUNT variable will retain its value. If it is non-static variable then the output will be 1.

Static method or class method

A static method is also called as a class method as we can directly invoke them without creating an object.

A static method can only access the static variables. Let's understand this by the following example:



package staticmethod;

public class StaticMethod {

    public static void main(String[] args) {

        StaticMethod.helloWorld();

    }

    public static void helloWorld()

    {

        System.out.println("Hello World");
     }



}

One of the main point to notice is that the static method cannot access a non-static data member:





Static block

Static block is mostly used for changing the default values of static variables.This block gets executed when the class is loaded in the memory.

The code in the static block is executed only once.


public class StaticBlock {
    
     static int n1;
    static String name;
    
    static{
        n1 = 5;
        name = "five";
        System.out.println("Static block");
    
    }
    
   
    
    public static void main(String args[])
    {
        StaticBlock sb = new StaticBlock();
        
        StaticBlock sb2 = new StaticBlock();
       
               
    }
    
}


Here is the output:



Static nested class

Let's see what happens when we make a class static:



So, this implies that we cannot make a top level class static. Now, let's create an inner class or a nested class and make it static:


As you can see, I am not getting any error here. That means we can create a static nested class.

public class StaticClassExample {

     public static class NestedClass
    {
         public void displayMessage()
         {
             System.out.println("This is nested class");
         }
    
    }
    
    public static void main(String[] args) {
        
        NestedClass nc = new NestedClass();
        nc.displayMessage();
        
        
    
    }
    
   
}

Here is the output I got after executing this program: 




I tried accessing the displayMessage() using the object of the outer class but I got an error. We cannot access elements of the static nested class using the reference of the outer class.


Conclusion

The static keyword is quite popular among the programmers. Many of us do not exactly understand the use of it 😂😅

I hope this article will help and if you want to make any correction to this article please comment down below.

Thank you!








Saturday, 1 April 2017

Exception Handling in Java



Exception Handling in Java



An exception is a problem that arises during the execution of the program.

Let's see a practical example....

public class ExceptionExample {
    
    
    public static void main(String args[])
    {
        
       int a = 5,b=0,c;
             
       c = a/b; 
       
       System.out.println(c);
    }
    
    

}


As you can see, the value of the b variable is 0. If we divide any number with 0, the answer will be infinity. In Java an exception called ArithmeticException is thrown when this occurs.


When I executed this program, I got the following output:






So, we have to handle these exceptions so that the execution of our program does not disrupts or stops.

To handle the exception we have several options:
  1. Try and catch
  2. Throws
  3. Throw
  4. Finally

Try and catch

We surround the code which may throw an exception with try/catch block. In the try block we enclose the code which is prone to throw an exception. In the catch block we will declare the exception we are going to handle.

So let's understand this using the above example:


public class TryCatch {
    
    
     public static void main(String[] args) {
    
         int a = 5,b=0,c,d = 0;
             
         try
         {
             c = a/b; 
         }
         catch(ArithmeticException ae)
         {
         }
         d = a + b;
         
         System.out.println(d);
   
    }
    
}

Here is the output:



As you can see, because we have handled the exception using try/catch block the program execution didn't stop and printed the output.

Now, let's see how we can use throws and throw for exception handling.

Throws

This keyword is used to declare the particular exception you think that the method might throw.
It is used in the method declaration and you can specify as many exceptions you think the method will throw separated with a comma.

Let's see the syntax:


public void hello() throws XyzException, PqrException  //You can declare as many exceptions you want
{

}

This keyword can be used to mention that the method will throw an exception and if other programmer is calling this method then he has to handle this exception.


Throw

The throw keyword is used to explicitly throw an exception. The throw keyword is usually used for handling custom exceptions.


  1. In the following example, first of all, I created a custom exception called InvalidArrayElementException.
  2. Then I used the throw keyword to invoke the InvalidArrayElementException.
  3. Then the throws keyword mentions that the arrayElements() method will throw an exception. So, the method invoking this method has to handle this exception.
  4. Finally, we handle the exception in the main method using try/catch.




package exceptionhandling2;

import java.util.Scanner;


class InvalidArrayElementException extends Exception //Here I am creating my custom exception
{
    public InvalidArrayElementException(){
             System.out.println("Array element should not be smaller than 0.");
    }
}
public class ThrowsException {
    
    public static void main(String[] args)
    {
        ThrowsException te = new ThrowsException();
        try
        {
            te.arrayElements();
        }
        catch(InvalidArrayElementException ie)
        {
        }

    }   
    
    public void arrayElements() throws InvalidArrayElementException
    {
    
        int[] a = new int[5];
        int i;
        Scanner s = new Scanner(System.in);
        
        for(i=0;i<5;i++)
        {
           
           a[i] = s.nextInt();
           if(a[i]<0)
           {
               throw new InvalidArrayElementException();
           }
    
           
        }
        
        
        
    }
    
    

}

Here is the output:




Finally


This block does exactly what its name suggests. It executes regardless of exception occurrence.
It follows the try block or catch block.

It can be used to execute some cleanup code like closing a connection, stream, etc.

Let's see an example:


import java.util.Scanner;

public class FinallyException {
    
    public static void main(String[] args)
    {
    
        int a,b,c;
        Scanner s = new Scanner(System.in);
        a = s.nextInt();
        b = s.nextInt();
        try{
            c = a/b;
        }
        catch(ArithmeticException ae)
        {
             
            System.out.println("b should not be zero.");
            
        }
        finally
        {
            System.out.println("Therefore, the exception has been handled :)");
        
        }
    
    }
            
    
}

Here is the output:



So, with this exception handling in java is explained. If you have any doubt or want to make any improvements in this article please comment down below.






Tuesday, 7 February 2017

Program Question:

Write a program to print all multiples of a user input number from an array.


import java.util.Scanner;

public class PracticeQuestion {
   
   
   
 
    public void practicefunction(int number)
    {
            int i;
            int a[] = {2,5,10,20,30};
            for(i=0; i < a.length; i++)
            {
                if(a[i]%number == 0)
                {
                    System.out.print(a[i]);
           
                }
            }
   
    }
   
    public static void main(String args[])
    {
   
       
        int a;
        Scanner s = new Scanner (System.in);
        System.out.println("Enter a number:");
        a = s.nextInt();
        PracticeQuestion pq = new PracticeQuestion();
        pq.practicefunction(a);
       
       
    }
   
}

All About "static"

All About "static"

All About "static" Static means “no change”. In Java static is used with a variable or a class which is same for every...