Monday 5 October 2020

Java program to create ODDEVEN thread using Runnable Interface

Threads are the lightweight processes. 
Java supports thread-based multitasking. 
Thread-based multi-tasking means a single program executing several tasks in the form of threads. 
The advantage of thread-based multitasking are: 
1) threads share the same address space
2) threads cooperatively share the same process 
3) inter-thread communication is inexpensive 
4) context-switching from one thread to another is not time-consuming 

 Threads can be created using one of the following two methods: 
 1) By extending Thread class in java.lang package 
 2) By implementing the Runnable interface 

In the following program, two threads are created: one thread will display all the even numbers in the range 0 to 10 while the second thread will display all the odd numbers in the range 0 to 10. The threads are created by implementing the runnable interface.

 Program 

//Program to create two threads 
class EvenThread implements Runnable
{
   Thread T;
    String n;

   EvenThread(String name)
   {
       n=name;
       T = new Thread(this, n);
    System.out.println("New thread: " + T);
    T.start();                     // Start the thread
  }

  // This is the entry point for thread.
  public void run() {
    try {
      for(int i = 0; i<=10; i++) {
         if (i%2==0)
        System.out.println(n + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(n + "Interrupted");
    }
    System.out.println(n+ " exiting.");
  }
}

class OddThread implements Runnable
{
   Thread T;
    String n;

   OddThread(String name)
   {
       n=name;
       T = new Thread(this, n);
    System.out.println("New thread: " + T);
    T.start(); // Start the thread
  }

  // This is the entry point for thread.
  public void run() {
    try {
      for(int i = 0; i<=10; i++) {
         if (i%2!=0)
        System.out.println(n + ": " + i);
        Thread.sleep(1000);
      }
    } catch (InterruptedException e) {
      System.out.println(n + "Interrupted");
    }
    System.out.println(n+ " exiting.");
  }
}

class Thread_OddEven
 {
  public static void main(String args[]) 
 {
    OddThread o=new OddThread("Odd"); // start threads
    EvenThread e=new EvenThread("Even");
    
    try 
   {
         e.T.join();
         o.T.join();
        
     } catch (InterruptedException e1) {
      System.out.println("Main thread Interrupted");
    }
   
    System.out.println("Main thread exiting.");
  }
}


OUTPUT 
D:\Java\Programs>java Thread_OddEven
New thread: Thread[Odd,5,main]
New thread: Thread[Even,5,main]
Even: 0
Odd: 1
Even: 2
Odd: 3
Even: 4
Odd: 5
Even: 6
Odd: 7
Even: 8
Odd: 9
Even: 10
Odd exiting.
Even exiting.
Main thread exiting.

Friday 25 September 2020

Java Program to handle divide by zero exception

 Exception Handling

Exceptions are the run-time errors that can be caught and handled by the programmers to avoid termination of program execution. The statements which may cause a run-time error are written inside the try block and the statements which are to be executed when an error is encountered are placed inside the catch block. A try block can be followed by more than one catch block or a finally block. The statements inside the finally block will be executed either if there is an error or no error in the program. The following program explains how to write try and catch blocks to handle exceptions. If more than one catch block follows the try block, then the catch blocks must be placed in the reverse order of the order in which the exceptions are inherited. All the exceptions both pre-defined and user-defined are the derived class of the base class Exception.


Program

import java.io.*;

class TryCatch
{
  public static void main(String[] arg)
  {
    BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
    int a,b,c;
    try
    {
        System.out.println("Enter two numbers");
        a=Integer.parseInt(x.readLine());
        b=Integer.parseInt(x.readLine());
        c=a/b;
        System.out.println("Division result = "+c);
    }
    catch(NumberFormatException e)
    {
        System.out.println("Input must be an Integer");
    }
    catch(ArithmeticException e)
    {
        System.out.println("Divide by zero error "+e);
    }
    catch(Exception e)
    {
        System.out.println(e);
    }
  }
}


OUTPUT

D:\Java\19csc>java TryCatch
Enter two numbers
10
2
Division result = 5

D:\Java\19csc>java TryCatch
Enter two numbers
10
0
Divide by zero error java.lang.ArithmeticException: / by zero

D:\Java\19csc>java TryCatch
Enter two numbers
a
Input must be an Integer java.lang.NumberFormatException: a

Monday 14 September 2020

Java program to find the power(m, n) using user-defined function.

In Java, the Math class in java.lang package contains library functions for most of the often-used mathematical functions. Here we will write a program to find the power(m, n) which is similar to the built-in function Math.pow(m, n).


Program

import java.io.*;
//Program to find the power(m,n)
class Power
{
    public static void main(String arg[]) throws IOException
    {
        int pow=1;
        BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter two numbers x and y");
        int m=Integer.parseInt(x.readLine());
        int n=Integer.parseInt(x.readLine());
        for(int i=0;i<n;i++)
        {
          pow=pow*m;
        }
        System.out.println("Power( "+m+" , "+n+" ) = "+pow);
  }
}


OUTPUT
>java Power
Enter two numbers x and y
5
3
Power( 5 , 3 ) = 125

>java Power
Enter two numbers x and y
5
0
Power( 5 , 0 ) = 1

Sunday 13 September 2020

Java program to find the maximum in an array of integers.

In this program, the input is given as console input. Hence the readLine() function defined in the InputStreamReader class is used to get the input. The readLine() reads the input as a string which is to be converted into an integer using the Integer.parseInt() function. The BufferedReader class is used to read a stream of character from a given source ie either from a file or standard input device. Here in this program since the input is read from a standard input device (keyboard), the InputStreamReader object is initialized with System.in. All the InputStream classes are defined in the java.io package. Hence, the first line of the program must be import java.io.*; to access the classes defined in the java.io package.


Program

import java.io.*;
class Maximum
{
    public static void main(String arg[]) throws IOException
    {
        double sum=0,avg;
        int number[]=new int[20];
        int max_position=-1;
       
        BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
        
        System.out.println("Enter the number of elements");
        int n=Integer.parseInt(x.readLine());
        System.out.println("Enter "+n+" numbers");
        for(int i=0;i<n;i++)
            number[i]=Integer.parseInt(x.readLine());
        
        int max=number[0];
        for(int i=0;i<n;i++)
            if (number[i]>max)
            {
                max=number[i];
                max_position=i+1;
            }
        System.out.println("The given array");
        for(int i=0;i<n;i++)
            System.out.print(number[i]+"\t");
            
        System.out.println("\nThe maximum number in the array = "+ max +" found at                                                         position = "+ max_position);
        
    }
}      

OUTPUT

>java Maximum
Enter the number of elements
5
Enter 5 numbers
4
3
9
8
1
The given array
4       3       9       8       1
The maximum number in the array = 9 found at position = 3

Java program to find the average of n numbers given as input in the command line argument.

 In Java programs, the simplest way to give input is to pass in the values along the command line while executing the program. This program finds the average of n numbers. The input given in the command line is assigned to the arg[ ] array as strings. To know the number of inputs, arg.length is used. Each element in the arg[ ] array is converted into an integer using the Integer.parseInt( ) function where Integer is a predefined wrapper class. If the input is a floating-point value then use Double.parseDouble() function to convert the command line string values to the corresponding floating-point values.

Note: The program uses the DecimalFormat class function format( ) to format the decimal output to two decimal places. This DecimalFormat class is defined in the java.text package. Hence the first line of the program imports this package.

Program

import java.text.*;
class Average
{
    public static void main(String arg[])
    {
        double sum=0,avg;
        int n=arg.length;
        DecimalFormat df = new DecimalFormat("#.##");
        for(int i=0;i<n;i++)
            sum=sum+Integer.parseInt(arg[i]);
        avg=sum/n;
        System.out.print("The average of the "+n+" numbers = ");
        System.out.println(df.format(avg));
    }
}


OUTPUT

>java Average 3 5 8 4 6 6 7 8

The average of the 8 numbers = 5.88        

Wednesday 26 August 2020

Java program to process result

PROGRAM

import java.io.*;

class StudentExam
{
    String name;
    String regno;
    double CIA1, CIA2,assgn,quiz,ext_mark,int_mark;
    String result;

  StudentExam()
  {
       name="\0";
       regno="\0";
       CIA1=CIA2=assgn=quiz=ext_mark=int_mark=0;
       result="\0";
  }

  StudentExam(String n,String r,double c1,double c2,double a,double qz,double e)
  {
       name=n;
       regno=r;
       CIA1=c1;
       CIA2=c2;
       assgn=a;
       quiz=qz;
       ext_mark=e;
  }
   
  void getData() throws IOException
  {
      BufferedReader x=new BufferedReader(new InputStreamReader(System.in));
      System.out.println("Enter name, regno");
      name=x.readLine();
      regno=x.readLine();
      System.out.println("Enter CIA1(50), CIA2(50), Assig(15), quiz(15)");
      CIA1=Double.parseDouble(x.readLine());
      CIA2=Double.parseDouble(x.readLine());
      assgn=Double.parseDouble(x.readLine());
      quiz=Double.parseDouble(x.readLine());
      System.out.println("Enter Sem_mark(50)");
      ext_mark=Double.parseDouble(x.readLine());
  }

  void getResult()
  {
       double cia = (CIA1+CIA2) * 70 /100;
       int_mark = (cia + assgn+quiz)/2;
       if  (ext_mark >= 20)
       {
           if ((int_mark + ext_mark) >=40)
              result="PASS";
           else
              result = "FAIL";
       }
       else
           result="FAIL";
  } 
  
  void display()
  {
       System.out.println("Student details");
       System.out.println("--------------------");
       System.out.println("Name = "+name);
       System.out.println("RegNo = "+regno);
       System.out.println("CIA1 = "+CIA1 +", CIA2 = "+CIA2);
       System.out.println("Assignment = "+assgn+", Quiz = "+quiz);
       System.out.println("Internal Mark = "+int_mark);
       System.out.println("External Mark = "+ext_mark);
       System.out.println("Result = "+result);
  }
}

class StudentResult
{
   public static void main(String args[]) throws IOException
   {
       StudentExam s1=new StudentExam();
       s1.getData();
       s1.getResult();
       s1.display();
    }
}

OUTPUT
Enter name, regno
Safi
33
Enter CIA1(50), CIA2(50), Assig(15), quiz(15)
20
20
15
10
Enter Sem_mark(50)
25

Student details
------------------
Name = Safi
RegNo = 33
CIA1 = 20.0, CIA2 = 20.0
Assignment = 15.0, Quiz = 10.0
Internal Mark = 26.5
External Mark = 25.0
Result = PASS

Tuesday 28 July 2020

Shell script to find the total size of the files given as positional parameters using function


PROGRAM
#size function to find the total size of the files
size()
{
  s=0
  for i in $*
  do
    if test -f $i
    then
       sz=`ls -l $i|tr -s " "|cut -d " " -f5`
       s=`expr $s + $sz`
    else
       echo $i is not a file
    fi
  done
  return $s
}
size $*
ret=$?
echo "Total size is " $s



OUTPUT
sh sizFunc.sh fibt file fil2
fil2 is not a file
Total size is  159

Shell script to find the LCM and GCD of two numbers


PROGRAM
echo enter two numbers
read m n
echo "The given numbers are \c"
echo $m and $n
temp=`expr $m \* $n`
while [ $m -ne $n ]
do
    if [ $m -gt $n ]
    then
        m=`expr $m - $n`
    else
        n=`expr $n - $m`
    fi
done
echo GCD = $n
lcm=`expr $temp / $n`
echo LCM = $lcm



OUTPUT
enter two numbers
24 60
The given numbers are 24 and 60
GCD = 12
LCM = 120

Sunday 26 July 2020

Shell script to convert a decimal number to hexadecimal number



PROGRAM

echo "Enter a decimal number"
read n
num=$n
while test $n -gt 0
do
  d=`expr $n % 16`
  case $d in
      10) d='A' ;;
      11) d='B' ;;
      12) d='C' ;;
      13) d='D' ;;
      14) d='E' ;;
      15) d='F' ;;
  esac
  res=$res$d
  n=`expr $n / 16`
done
cnt=`echo $res|wc -c`
while test $cnt -gt 0
do
  c=`echo $res|cut -c $cnt`
  hex=$hex$c
  cnt=`expr $cnt - 1`
done
echo "($num) decimal = ($hex) hexadecimal"



OUTPUT
Enter a decimal number
10456
(10456) decimal = (28D8) hexadecimal

Monday 20 July 2020

Shell script to count the number of lines in a file that do not contain vowels.


PROGRAM
echo "Enter a filename"
read file
grep -v '^$' $file > gfl
lc=`grep -i -v -c [aeiou] gfl`
echo "Number of lines that do not contain any   vowels are: $lc"


OUTPUT
Enter a filename
fibt
Number of lines that do not contain any   vowels are: 0

Enter a filename
file3
Number of lines that do not contain any   vowels are: 3

Shell script to count the number of files whose size exceeds 100 bytes.


Program


c=0
for i in *
do
     if test -f $i
     then
        s=`ls -l $i | tr -s " " | cut -d " " -f5`
        if test $s -gt 100
        then
           c=`expr $c + 1`
        fi
     fi
done
echo "Number of files whose size exceeds 100 bytes is:$c"




OUTPUT
Number of files whose size exceeds 100 bytes is:91

Shell script to accept a string from the terminal and echo a suitable message if it doesn’t have at least 10 characters.


Program
echo "enter the string"
read str
Len=`expr  "$str" :  '.*'`
if test $Len -lt 10
then
     echo " $str has less than 10 characters"
else
echo  " the input string is \"$str\" "
fi


OUTPUT
enter the string
welcome to the world of UNIX
 the input string is "welcome to the world of UNIX"

enter the string
jhhj
 jhhj has less than 10 characters

Shell script to print n Fibonacci numbers


Program
echo "enter the number"
read n
echo "The Fibonacci numbers are"
f1=0
f2=1
echo "$f1"
echo "$f2"
n=`expr $n - 2`
while test $n -gt 0
do
   f3=`expr $f1 + $f2`
   echo "$f3"
   n=`expr $n - 1`
   f1=$f2
   f2=$f3
done



OUTPUT
enter the number
10
The Fibonacci numbers are
0
1
1
2
3
5
8
13
21
34

Saturday 23 May 2020

Shell Script to Delete All Even Numbered Lines from a Text File



Program
echo "enter a file name"
read fname
lc=0
if test -f $fname
then
   while read line
   do
      lc=$((lc+1))
      even=$((lc%2))
      if test $even -ne 0
      then
         echo $line>>newfile.txt
      fi
   done < $fname
   rm $fname
   mv newfile.txt $fname
else
   echo "$fname file not exist"
fi


OUTPUT
csc@csc-SVE1513CYNB ~ $ cp avg ttavg
csc@csc-SVE1513CYNB ~ $ bash avg
enter a file name
ttavg


echo "enter a file name"
lc=0
then
do
even=$((lc%2))
then
fi
rm $fname
cat $fname
echo "$fname file not exist"

Shell script to accept student test marks and find the result

Write a shell script to accept student information like name, class and 3 subject marks. Calculate the total and average. Result will be displayed based on average. If avg >=90 (Distinction), avg >=60 and avg<90 (First class), avg>=35 and avg<=59(Second class), avg <35 (Fail).


Program
echo "enter name"
read name
echo "enter class"
read class
echo "enter marks of 3 subjects"
read a
read b
read c
total=$(($a+$b+$c))
avg=$(($total/3))
echo "Total:$total"
echo "Average:$avg"
echo -n "Result:"
if test $avg -ge 80 -a $avg -le 90
then
   echo "Distinction"
elif test $avg -ge 60 -a $avg -lt 80
then
   echo "First class"
elif test $avg -ge 35 -a $avg -le 59
then
   echo "Second class"
else
   echo "Fail"
fi

OUTPUT
csc@csc-SVE1513CYNB ~ $ bash avg
enter name
martin
enter class
bsc
enter marks of 3 subjects
45
54
55
Total:154
Average:51
Result:Second class

Friday 15 May 2020

Shell script to count the number of lines in a file which does not contain a vowel.

PROGRAM

echo "Enter the file"
read fname
ans=`echo grep -v '[aeiou]' $fname|wc -l`

echo "Number of lines in $fname which does not contain a vowel is $ans."

OUTPUT
Enter the file
vw
Number of lines in vw which does not contain a vowel is 1.
 

Friday 27 March 2020

Shell program to find the sum of the square of the digits of a number

PROGRAM
echo "Enter the Number :"
read number
n=$number
sum=0
while test $number -gt 0
do
    rem=` expr $number % 10 `
    sum=` expr $sum + $rem \* $rem `
    number=` expr $number / 10 `
done
echo "The Sum Of Square Of Digits in the Given Number $n is $sum"



OUTPUT
Enter the Number :
12
The Sum Of Square Of Digits in the
Given Number 12 is 5

Shell program to find the sum of odd digits and even digits from a number.

PROGRAM
echo "enter a number"
read n
os=0
es=0
while test $n -gt 0
do
  r=`expr $n % 10`
  if test `expr $r % 2` -eq 0
  then
     es=`expr $es + $r`
  else
     os=`expr $os + $r`
  fi
  n=`expr $n / 10`
done
echo "sum of odd digits in the number = $os"
echo "sum of even digits in the number = $es"


OUTPUT
enter a number
12345
sum of odd digits in the number = 9
sum of even digits in the number = 6

Write a shell script to count the number of occurrences of a particular digit in an 8 digit number input. 

PROGRAM
echo enter an 8 digit number
read d
echo enter a digit to find
read f
n=8
for((i=1;i<=n;i++))
do
      k=`echo $d|cut -c $i`
       if test $f -eq $k
       then
            cnt=`expr $cnt + 1`
        fi
done
echo the number of occurrences of number $f is $cnt





OUTPUT
enter an 8 digit number
12323332
enter a digit to find
2
the number of occurrences of number 2 is 3