Basic Java Programs

throws vs throw vs try catch
-If there is an error and if you have used throw or throws then it will not execute any line after that error ie.remaining code does not execute
-You can declare multiple exception for throws e.g. public void method() throws IOException,SQLException
but you cannot declare multiple exceptions with throw. To manually throw an exception we use throw
-The keyword throw is used inside method body and throws clause is used in method declaration.
-throws and throw prints the stack trace to find error in actual line and method.
-If there is an error and if you have used try catch then remaining code after error gets executed. Use e.printStackTrace() to find error in actual line and method.

public class Test{
public static void main(String[] args) throws Exception {
try {
 int data=50/0;
System.out.println("If there is error in division then this line will not be printed");
} catch (Exception e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
finally
{
System.out.println("Finally");
}
//divideThrow();
//divideThrows();
System.out.println("This line will be printed only in try catch exception");
}

public static void divideThrow() {
int a = 1 / 0;
throw new ArithmeticException("throw");
}
public static void divideThrows() throws Exception {
int a = 1 / 0;
}
}


Basics of try catch     (Concepts of  return and System.exit(0) has been explained below)
package string;

class Try_Catch{
    public static void main(String args[]){
     try{
        int data=50/0;
      
System.out.println("If there is error in division then this line will not be printed");

        }
     catch(ArithmeticException e)
     {
         System.out.println(e);
         System.out.println("inside catch");
         //return; // rest of the code not executed, only finally of this try-catch blog is executed
         // finally block of any other try catch is never executed
         // return should always be the last statement


     // System.exit(0);
       /*terminates the prog finally/remaining block not executed;
         a nonzero status code indicates abnormal termination
    0(code) is a successfull exit with no errors.*/ 

     }
     
     finally
     {
         System.out.println("finally block is always executed");
     }
   
     System.out.println("rest of the code...");
     try
     {
         int data=0/5;
         System.out.println("0/5 not exception:: data is:"+data);
       
        }
     catch(ArithmeticException e)
     {
         System.out.println(e);
     }
     try
     {
         int data1=0/0;
         System.out.println("This line is not printed:: data1:"+data1);
         }
     catch(ArithmeticException e)
     {
         System.out.println(e);
     }
     finally
     {
         System.out.println("finally block no 2 executed");
     }
  }
  }

  Output:
java.lang.ArithmeticException: / by zero
inside catch
finally block is always executed
rest of the code...
0/5 not exception:: data is:0
java.lang.ArithmeticException: / by zero
finally block no 2 executed


Output: If return statement is not commented
java.lang.ArithmeticException: / by zero
inside catch
finally block is always executed


Output:  If System.exit(0) is not commented
java.lang.ArithmeticException: / by zero
inside catch


Note:
System.exit(0)
1)It terminates the currently running Java virtual machine by initiating its shutdown
sequence. This method never returns normally.
2)The System.exit method forces termination of all threads in the Java virtual machine.
3)There is one JVM per application.
If you start three Java applications at the same time, on the same computer,you'll get three
Java virtual machine instances. Each Java application runs inside its own Java virtual
machine.
Any class with such a main() method can be used as the starting point for a Java application.

When a Java application starts, a runtime instance is born.
Cases in which System.exit is appropriate (not recommended): utility scripts



Basics of String:

package string;

import java.text.BreakIterator;

public class Basics
{
 public static void main(String args[])
     {
     System.out.println("args.length:"+args.length);
    
     /*System.out.println( "later initialize " +abc );
     int abc=1;*/   // compile error

    
     String c="Rahul";
     System.out.println( "c: " +c );
      c="Iyengar";
      System.out.println( "c: " +c );
    
      String value=new String("abc");
      value="xyz";
      System.out.println( "value " +value );
    
      /*String a=abc;
      System.out.println( "c: " +a );*/ //  will not compile

    
       
      String str = new String("");
      System.out.println( "String blank: " + str );
    
      String str1 = new String("null");
      System.out.println( "String null: " + str1 );
     
    
     
      String str3=null;
      System.out.println( "St3: " + str3 );
    
      /*String str5 = new String(1);   or null in place of 1(without "")
      System.out.println( "String null: " + str5 );*/    // compile error

    
      /*String str2 = new String(null);
      System.out.println( "String str2: " + str2 );*/

    
      String str4="";
      System.out.println( "St4: " + str4 );
    
    
      int zero=0;
      System.out.println( "zero: " + zero );
    
      /*String str5;
      System.out.println( "St5: " + str5 );*/

    
      /*int ab;
      System.out.println( "int ab: " + ab );*/

    
    
    
      int[] x=new int[2];
      System.out.println( "array____: " + x );
      //prints add location. Add keeps on changing when u run
    
      System.out.println( "array x[0]: " + x[0] );
      System.out.println( "array x[1]: " + x[1] );
// System.out.println( "array x[2]: " + x[2] );//ArrayIndexOutOfBound
    // since array size is only 2

    
      int[] y={1,2};
      System.out.println( "array y: " + y );
      System.out.println( "array y[0]: " + y[0] );
      /*int[] z;
      System.out.println( "array z: " + z );*/

        
      StringBuilder strBuilder = new StringBuilder("abc");
      StringBuilder a=strBuilder;
      System.out.println( "strBuilder before reverse: " +a );
          
      StringBuilder b=a.reverse();
      System.out.println( "after reverse: " + b );
    
      if(a.toString().equals(b))//.toString() can be done for either
          //a or b
             
          System.out.println( "palindrome" );
           
      else
          System.out.println( "not palindrome" );
          
     }


}


Output:
args.length:0
c: Rahul
c: Iyengar
value xyz
String blank:
String null: null
St3: null
St4:
zero: 0
array____: [I@1cfb549
array x[0]: 0
array x[1]: 0
array y: [I@186d4c1
array y[0]: 1
strBuilder before reverse: abc
after reverse: cba
not palindrome


Note:
All data types must be initialized.
It is not necessary to initialise static variable (written outside main method).
Default value of
1)int is 0
2)long is 0
3)float is 0.0
4)double is 0.0
5)char is blank ie. nothing is printed
6)booleal is false
eg.
public class Basics
{
    static long z;  
 public static void main(String args[])
     {   
     System.out.println("z="+z);  
      }
}
Output: 0




Static Block:

package basics;

class StaticBlock{
  
public static void main(String args[]){
    System.out.println("main");
 }

static
{
 System.out.println("static block is always executed first even before main method");
}

}

Output:
static block is always executed first even before main method
main



Simple Array program: 
package arrays;

class Simple_Array{
    public static void main(String args[]){
    //int b[]=new int[5];
    int a[]=new int[5]; //declaration and instantiation
    a[0]=10;//initialization
    a[1]=20;
    a[2]=70;
    a[3]=40;
    a[4]=50;

    //printing array
    for(int i=0;i<a.length;i++)//length is the property of array
    //System.out.println(b[i]=a[i]);
    System.out.println(a[i]);
    }}


Output:
10
20
70
40
50
 



Linked List (Program for reversing)
package linkedList;

import java.util.Collections;
import java.util.LinkedList;

public class Reverse {
   public static void main(String[] args) {
      LinkedList linkedList = new LinkedList();
      linkedList.add("A");  //0
      linkedList.add("C");  //1
      linkedList.add("D");  //2
      linkedList.add("E");  //3
      linkedList.add("B");  //4
      linkedList.add(4,"X"); //5
// linkedList.add(4,"Z");--> this will add Z at 4th position ie. after E
      linkedList.addLast("Z");//6
  
      System.out.println("Before Reverse Order: " + linkedList);
      System.out.println("Size(size counted from 1) of Array: " + linkedList.size());
      System.out.println("2nd element: " + linkedList.get(2));
      System.out.println("getFirst: " + linkedList.getFirst());
      System.out.println("getLast: " + linkedList.getLast());
      System.out.println("before removing z: " + linkedList);
      System.out.println("remove z: " + linkedList.remove("Z"));
      System.out.println("after removing z: " + linkedList);
      System.out.println("remove last: " + linkedList.removeLast());
      System.out.println("after removing last: " + linkedList);
  
      Collections.reverse(linkedList);
      System.out.println("After Reverse or descending Order: " + linkedList);
  
      Collections.sort(linkedList);
      System.out.println("asc Order: " + linkedList );
 
      Collections.reverse(linkedList);
      System.out.println("After Reverse or descending Order: " + linkedList);
   }
}

Output:
Before Reverse Order: [A, C, D, E, X, B, Z]
Size(size counted from 1) of Array: 7
2nd element: D
getFirst: A
getLast: Z
before removing z: [A, C, D, E, X, B, Z]
remove z: true
after removing z: [A, C, D, E, X, B]
remove last: B
after removing last: [A, C, D, E, X]
After Reverse or descending Order: [X, E, D, C, A]
asc Order: [A, C, D, E, X]
After Reverse or descending Order: [X, E, D, C, A]


TreeMap:

package collections;


import java.util.*;
class Treemap{
 public static void main(String args[]){

 TreeMap<Integer,String> hm=new TreeMap<Integer,String>();

 //hm.put(null,"abc"); //run time error
  hm.put(100,"Amit");  // cannot contain null key, any no of null values(ascending)
  hm.put(100,"Amit");
  hm.put(100,"Vijay");
  hm.put(103,"Rahul");


  for(Map.Entry m:hm.entrySet()){
   System.out.println(m.getKey()+" "+m.getValue());
  }
 }

}


Output:

100 Vijay
103 Rahul

Program to check if an Array contains an Item 

package arrays;

import java.util.Arrays;
import java.util.List;

/**
 *
 * Java program to check if an Array contains an Item or not
 * and finding index of that item. For example How to check if
 * an String array contains a particular String or not and What  *   is index of that String in Java program.
 * 
 */
public class StringIndex{


    public static void main(String args[]) {

      String[] programming = new String[]{"Java", "C++", "Perl", "Cobol"};
 
      // converting Array To ArrayList
      List<String> programmingList = Arrays.asList(programming);
 
      //Checking does this Array contains Java
      boolean result = programmingList.contains("Java");
 
      System.out.println("Does programming Array contains Java? " + result);
 
      int index = programmingList.indexOf("Java");
 
      System.out.println("Index of Java in programming Array is : " + index);
 
    }
   
}

Output:
Does programming Array contains Java? true
Index of Java in programming Array is : 0


Note:
1).toArray is used to convert ArraylList to array
eg.
Integer list2[] = new Integer[arrlist.size()]; //initialize array
list2 = arrlist.toArray(list2);

2)Arrays.asList(al)  is used to convert array to ArraylList



Program to get input from user 

package passionatecodes;

import java.util.Scanner;

class GetInputFromUser
{
   public static void main(String args[])
   {
      int a;
      float b;
      char c;
      double d;
      String s;
    
    Scanner in = new Scanner(System.in);

      System.out.println( "\n  Enter a string: "  );
      s = in.nextLine();
      System.out.println("You entered string "+s);
     
      System.out.println("Enter an integer");
      a = in.nextInt();
      System.out.println("You entered integer "+a);


      System.out.println("Enter a float");
      b = in.nextFloat();
      System.out.println("You entered float "+b);  
     
      System.out.println("Enter a double");
      d = in.nextDouble();
      System.out.println("You entered double "+d);  
     
      System.out.println("Enter a char");
      c = in.next().charAt(0); // if u write 1 instead of 0 char at 1st position will b displayed
      System.out.println("You entered char "+c);  
   }
}


Output:
Enter a string:
Rahul
You entered string Rahul


Enter an integer
10
You entered integer 10


Enter a float
10.1
You entered float 10.1


Enter a double
10.11
You entered double 10.11


Enter a char
a
You entered char a




Count no. of spaces in String:
package string;

public class No_Of_Spaces {
    public static void main(String args[])
    {
         int c=0;
    String str="     Today, environment is cool" ;
    String str1= new String();
    str1=str.toUpperCase();
    System.out.println("Upper case:"+str1);
    for(int x=0; x<str1.length(); x++)
    {
        if(str1.charAt(x)==32)
            c++;
    }
    System.out.println("No. of spaces:"+c);
    System.out.println("trim:"+str1.trim());
   
    }
}


Output:
Upper case:     TODAY, ENVIRONMENT IS COOL
No. of spaces:8
trim:TODAY, ENVIRONMENT IS COOL


 

Get Current Date and Time
package linkedList;

import java.util.*;

class GetCurrentDateAndTime
{
   public static void main(String args[])
   {
      int day, month, year;
      int second, minute, hour;
      GregorianCalendar date = new GregorianCalendar();

      day = date.get(Calendar.DAY_OF_MONTH); // note all in capital DAY_OF_MONTH
      month = date.get(Calendar.MONTH);
      year = date.get(Calendar.YEAR);

      second = date.get(Calendar.SECOND);
      minute = date.get(Calendar.MINUTE);
      hour = date.get(Calendar.HOUR);

      System.out.println("Current date is  "+day+"/"+(month+1)+"/"+year);
      // note that month+1 is written since
GregorianCalendar's month starts with 0 not 1
      System.out.println("Current time is  "+hour+" : "+minute+" : "+second);
   }



 Output:
Current date is  19/4/2014
Current time is  2 : 16 : 6



No comments:

Post a Comment