Thursday, 24 September 2015

java quiz-2


java quiz-2



1
class Test
{
public static void main(String args[])
{
byte g=3;
switch(g)
{
case 3:
System.out.printf("java");
case 129:
System.out.printf("for");
}
System.out.printf("ocpjp");
}
}
java
javaforocpjp
CompileError
RunTimeException


2
class Test
{
boolean sum()
{
for(int i=0;i<3;i++)
{
System.out.printf("java");
return true;//line y
}
return false;//line x
}
public static void main(String args[])
{
Test t1=new Test();
boolean fp=t1.sum();
 }
}
java
javajavajava
compilation fails due to line x
compilation fails due to line y


3
class Test
{
public static void main(String args[])
{
int x=5;
switch(x)
{
case 1:
System.out.println("Nature");
break;
case 5:
System.out.println("Beauty");
continue;
}
System.out.println("AXXL");
}
}
Compilation fails
execute infinte times
Beauty AXXL
Beauty


4
class Test
{
public static void main(String args[])
{
int arr[]=new int[5];
try
{
for(int i=0;i<=5;i++)
System.out.printf(arr[i]);
}
catch(Exception e)
{
e.printStackTrace();
}
catch(ArrayIndexOutOfBoundsException e)
{
e.printStackTrace();
}
}
}
000000
012345
Compilation fails
An exception is thrown at run-time


5
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static void go()
{
System.out.println("baba");
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :go();
System.out.println(ans);
}
}
}
4321 for more information of the exception it will print baba
Runtime exception
4321
Compile Error


6
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static int go()
{
return 25;
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :go();
System.out.print(ans);
}
}
}
runtime exception
comile error
it will print 4321
it will print 4321 and for more information of the exception it will print 25


7
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static void go()
{
System.out.println("baba");
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :new Exc15();
System.out.print(ans);
}
}
}
it will print 4321 and for more information of the exception it will print hashcode of the object
it will print 4321 and terminate
it will print 4321 only
comile time error


8
public class Test {
public static void main(String [] args) {
int I = 1;
do while ( I < 1 )
System.out.print("I is " + I);
while ( I > 1 ) ;
}
}
compilation error at line 4
1
No output is produced
compilation error at line 6


9
1. import java.io.*;
2. public class MyProgram {
3. public static void main(String args[]){
4. FileOutputStream out = null;
5. try {
6. out = new FileOutputStream("test.txt");
7. out.write(122);
8. }
9. catch(IOException io) {
10. System.out.println("IO Error.")
11. }
12. finally {
13. out.close();
14. }
15. }
16. }
This program fails to compile due to an error at line 4.
This program fails to compile due to an error at line 13.
This program will compile successfully.
This program fails to compile due to an error at line 9.


10
class Exc15
{
static int n=5;
static int sum()
{
return --n;
}
static void go()
{
System.out.println("baba");
}
public static void main(String args[])
{
for(int i=0;i<=10;i++)
{
int ans=sum();
assert ans>0 :Exc15 e
System.out.print(ans);
}
}
}
compile time error
1234
it will print 1234 and then print the refernce of class Exc15
runtime Exception

Wednesday, 23 September 2015

"assert" keyword in Java

The assert keyword is used in assert statement which is a feature of the Java programming language since Java 1.4. Assertion enables developers to test assumptions in their programs as a way to defect and fix bugs.

Syntax of assert statement:-

(short version):

assert expression1;
 or (full version):
assert expression1 : expression2;
  • expression1 must be a boolean expression.
  • expression2 must return a value (must not return void).
By default,assertion is disabled at runtime to enable assertion,specify the switch -ea or 
-enableassertions  at command line of java program.for example to enable assertion for the program IsTest
                                                 
                                                       java -enableassertions IsTest 
or this for short
                                                              java -ea IsTest

1. You can combine switches to say disbale assertions in single class but keep enabled for       all others.                         
                                 java -ea -da:com.geekanonymous.Foo
    
    the preceding command line tells the jvm keep the assertions enable in general and             disable it for class Foo.

2. You can enable the assertion or disable the assertion in the System class with the -esa         and -dsa flags.

3. if assertion statement is false then it will throw Assertion Error which you should never           handle.


class Exc15
{
static int n=5;
       static int sum()
      {
      return --n; 
      }
public static void main(String args[])
{
      for(int i=0;i<=10;i++)
      {
      int ans=sum();
      assert ans>0;
     //assert ans>0 :"negative number";//give more information
     System.out.println(ans);
      }
}
}
 

  

Friday, 18 September 2015

Counting Sort

In this sort, we count the frequencies of distinct elements of array and store them in an auxiliary array, by mapping its value as index of auxiliary array and then place each element in its proper position in the output array .
Complexity: As the above code runs in linear time so the complexity in worst case will be O(max + n), where n is the number of elements and max is the range of input element of array A[ ].


import java.util.Scanner;
class Count
{
void sort(int a[])
{
int max=a[0];
for(int i=1;i<a.length;i++)
{
if(a[i]>max)
max=a[i];
}
int count[]=new int[max+1];
int output[]=new int[a.length];
for(int i=0;i<a.length;i++)
count[a[i]]++;
for(int i=1;i<count.length;i++)
count[i]=count[i]+count[i-1];
for(int i=0;i<a.length;i++)
{
output[count[a[i]]-1]=a[i];
count[a[i]]=count[a[i]]-1;
}
System.out.println("the sorted array is:");
for(int i=0;i<output.length;i++)
System.out.println(output[i]+"\t");
}
}
class CountTest
{
public static void main(String args[])
{
Count c1=new Count();
System.out.println("enter the total number of elements:");
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.printf("enter the %d element:",(i+1));
arr[i]=sc.nextInt();
}
c1.sort(arr);
}
}


Thursday, 17 September 2015

Quick Sort

Quick Sort: This algorithm is also based on the divide and conquer approach. It reduces the space complexity and removes the use of auxiliary array used in merge sort.
Idea: It is based on the idea of choosing one element as pivot element and partitioning the array around it such that the left side of pivot contains all elements less than the pivot element and right side contains all elements greater than the pivot.
Selecting a random pivot in an array results into an improved time complexity in average cases.
Implementation:
Choose the first element of array as pivot element First, we will see how the partition of the array takes place around the pivot.


Example: you have an array A[]={9,7,8,3,2,1}.






import java.util.Scanner;
class Quick
{
void sort(int a[],int start,int end)
{
if(start<end)
{
int pos=partition(a,start,end);
sort(a,start,pos);
sort(a,pos+1,end);
}
}
int partition(int a[],int start,int end)
{
int piv=a[start];
int pindex=start+1;
for(int i=start+1;i<end;i++)
{
if(a[i]<=piv)
{
int temp=a[i];
a[i]=a[pindex];
a[pindex]=temp;
pindex=pindex+1;
}
}
pindex=pindex-1;
int x=a[pindex];
a[pindex]=a[start];
a[start]=x;
return pindex;
}
}
class QuickTest
{
public static void main(String args[])
{
Quick q1=new Quick();
Scanner sc=new Scanner(System.in);
System.out.println("enter the total number of elements:");
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
System.out.printf("enter the %d elements:",(i+1));
arr[i]=sc.nextInt();
}
q1.sort(arr,0,n);
System.out.println("the sorted array is:");
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}
Complexity:The worst case time complexity of this algorithm is O(n2),but as this is randomized algorithm,its time complexity fluctuates between O(n2) and O(n(log n) ) and mostly it comes out to be O(n(log n)) .



Wednesday, 16 September 2015

Merge Sort

Merge Sort: This sorting algorithm works on the following principle - Divide the array in two halves. Repeatedly sort each half, then merge two halves.
Lets say we have an array A[ ] = { 9, 7, 8, 3, 2, 1} .
First we will divide it in two halves A1 [ ] = {9, 7, 8} and A2[ ] = {3, 2, 1}. Again divide these 2 halves in their two halves. For A1 it will be A1_a[ ] = {9, 7} and A1_b[ ] = {8}. Again, divide A1_a and then as they further cannot be divided, so merge them by comparing them. A1_a will be {7, 9} and then compare and merge A1_a and A1_b. Now, A1 will be { 7, 8, 9} . Do same for A2 and then A2 will be {1, 2, 3} . Now, compare A1 and A2 and then merge them. Now, A will be {1, 2, 3, 7, 8, 9}.

complexity:Array with n elements is divided recursively in 2 parts, so it will form a tree with nodes asdivided parts of array (subproblems).The height of the tree will be log2n and at each level of tree the computation cost of all the subproblems will be n. At each level the merge operation will take O( n) time.So the overall complexity of this algorithm will be O( n(log2 n)).



Here in merge function, we will merge the two part of arrays where one part has starting and ending positions from start to mid respectively and another part has positions from mid+1 to end.
We will start from starting positions of both the parts that are p and q.Then we will compare respective elements of both the parts and the one with the smaller value will be stored in the auxiliary array. If at some condition ,one part comes to end ,then all the elements of another part of array are added in the auxiliary array in the same order they exist.





import java.util.Scanner;
class Merge
{
void sort(int arr[],int n)
{
int left[];
int right[];
if(arr.length<2)
return;
int mid=arr.length/2;
left=new int[mid];
right=new int[arr.length-mid];
for(int i=0;i<mid;i++)
left[i]=arr[i];
for(int i=mid;i<n;i++)
right[i-mid]=arr[i];
sort(left,left.length);
sort(right,right.length);
Merge m2=new Merge();
m2.merge(arr,right,left);
}
void merge(int arr[],int right[],int left[])
{
int i=0,k=0,j=0;
while(i<left.length && j<right.length)
{
if(left[i]<=right[j])
{
arr[k]=left[i];
k++;
i++;
}
else
{
arr[k]=right[j];
k++;
j++;
}
}
while(i<left.length)
{
arr[k]=left[i];
k++;
i++;
}
while(j<right.length)
{
arr[k]=right[j];
k++;
j++;
}
}
}
class MergeTest
{
public static void main(String args[])
{
Merge m1=new Merge();
Scanner sc=new Scanner(System.in);
System.out.println("enter the total number of elements:");
int n=sc.nextInt();
int a[]=new int [n];
for(int i=0;i<n;i++)
{
System.out.printf("enter the %d elements:",i+1);
a[i]=sc.nextInt();
}
m1.sort(a,n);
System.out.println("the sorted array is:");
for(int i=0;i<n;i++)
System.out.print(a[i]+"\t");
}
}


Insertion Sort

Insertion Sort: The idea behind is that in each iteration, it consumes one element from the input elements, removes it and finds its correct position i.e., where it belongs in the sorted list and places it there.
It iterates the array by growing the sorted list behind it at each iteration. It checks the current element with the largest value in the sorted list. If the current element is larger, then it leaves the element at its place and moves to the next element else it finds its correct position in the sorted list and moves it to that position. It is done by shifting all the elements which are larger than the current element to one position ahead.

Since, 7 as the first element has no other element to be compared with, it remains at its position. Now when we move towards 4, we have 7 which is the largest element in the sorted list and greater than 4. So we will move 4 to its correct position. Similarly with 5, as 7 (largest element in the sorted list) is greater than 5, we will move 5 to its correct position. Finally for 2, all the elements on left side of 2 (sorted list) are moved one position forward as all are greater than 2 and then 2 is placed on first position. Finally you will get a sorted array.
Complexity : Complexity of Insertion sort is O(n2) .

import java.util.Scanner;
class Insertion
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
void input()
{
for(int i=0;i<n;i++)
{
System.out.printf("Enter the %d element:",(i+1));
arr[i]=sc.nextInt();
}
}
void sort()
{
for(int i=1;i<n;i++)
{
int j=i;
int key=arr[j];
int x=j-1;
while(key<arr[x]&&j>0)
{
arr[j]=arr[j-1];
j=j-1;
x=j-1;
if(x==-1)
break;
}
arr[j]=key;
}
}
void display()
{
System.out.println();
System.out.println("the sorted array is:");
for(int i=0;i<n;i++)
{
System.out.print(arr[i]+"\t");
}
}
void showsteps()
{
for(int i=1;i<n;i++)
{
int j=i;
int key=arr[j];
int x=j-1;
System.out.println();
System.out.printf("OuterLoop: %d",i);
while(key<arr[x]&&j>0)
{
System.out.println();
System.out.printf("InnerLoop: %d",j);
System.out.println();
arr[j]=arr[j-1];
j=j-1;
x=j-1;
for(int t=0;t<n;t++)
System.out.print(arr[t]+"\t");
System.out.println();

if(x==-1)
break;
}
arr[j]=key;
try
{
Thread.sleep(3000);
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
}
}

}
class InsertionTest
{
public static void main(String args[])
{
System.out.println("enter the total number of elements:");
Insertion i1=new Insertion();
i1.input();
//i1.sort();
//i1.display();
i1.showsteps();
i1.display();
}
}

Friday, 11 September 2015

selection sort

Selection Sort: This algorithm is based on the idea of finding the minimum or maximum element in the unsorted array and then putting it in its correct position for a sorted array.
We have an array A [ ] = {7, 5, 4, 2} and we need to sort it in ascending order.
Let’s find the minimum element in the array i.e., 2 and then replace it with the first position's element, i.e., 7. Now we find the second largest element in the remaining unsorted array and put it at the second position and so on.


Complexity : Here as to find the minimum element from the array of n elements, we require n-1 comparisons to be performed. Then, after putting minimum element to its proper position, size of unsorted array reduces to n-1and then n-2 comparisons are required to find the minimum in the unsorted array. Therefore (n-1) + (n-2 ) + .......+ 1 = ( n * (n-1) ) / 2 comparisons and n exchanges (swapping ), which gives the complexity of O( n2 ).



import java.util.Scanner;
class Selection
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
void input()
{
for(int i=0;i<n;i++)
{
System.out.printf("enter the value of %d element",(i+1));
arr[i]=sc.nextInt();
}
}
void display()
{
System.out.println();
System.out.println("the sorted array is:");
for(int i=0;i<n;i++)
System.out.print(arr[i]+"\t");
}
void sort()
{
int minimum=0;
for(int i=0;i<n-1;i++)
{
minimum=i;
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[minimum])
{
minimum=j;
}
int temp=arr[i];
arr[i]=arr[minimum];
arr[minimum]=temp;
}
}
}
void showSteps()
{
int minimum=0;
for(int i=0;i<n-1;i++)
{
minimum=i;
System.out.println();
System.out.printf("outer loop i=%d\t",i);
for(int j=i+1;j<n;j++)
{
if(arr[j]<arr[minimum])
{
minimum=j;
}
}
int temp=arr[i];
arr[i]=arr[minimum];
arr[minimum]=temp;
try
{
Thread.sleep(2000);
}
catch(InterruptedException e)
{
System.out.println(e.getMessage());
}
for(int k=0;k<n;k++)
System.out.print(arr[k]+"\t");
}
}
}
class SelectionTest
{
public static void main(String args[])
{
System.out.println("enter the value of total number of elements:");
Selection s1=new Selection();
s1.input();
//s1.sort();
//s1.display();
s1.showSteps();
s1.display();
}
}