You are on page 1of 78

COMPUTER PROJECT

- ADITI SINGH

- XII-B

INDEX
TOPIC PAGE NUMBER SIGNATURE

Programs on Strings
QUESTION:1
Write a program to check if the two given string are anagram or not.

Anagram:
An anagram is a rearrangement of the letters of one word or phrase to
another word or phrase, using all the original letters exactly once.

1|Page
ALGORITHM

CREATE CLASS AnagramTest

CREATE METHOD isAnagram(String s1, String s2)

INITIALIZE String str1 = s1.replaceAll("\\s", "");

INITIALIZE String str2 = s2.replaceAll("\\s", "");

INITIALIZE boolean status = true;

IF(str1.length() != str2.length)

status=true

ELSE

           INITIALIZE ARRAY

    char[] s1Array = str1.toLowerCase().toCharArray();


               char[] s2Array = str2.toLowerCase().toCharArray();
               Arrays.sort(s1Array);
               Arrays.sort(s2Array);
               status = Arrays.equals(s1Array, s2Array);
          IF (status)
          
               PRINT s1+" and "+s2+" are anagrams"
          
          ELSE
          
               PRINT s1+" and "+s2+" are not anagrams"
          
     END METHOD
CREATE main(String[] args)
     
         CALL  isAnagram("keEp", "peeK");
         CALL isAnagram("Java", "Vaja");
        CALL  isAnagram("Lock", "Clock");
END MAIN

END CLASS

PROGRAM
import java.util.*;
public class AnagramTest

2|Page
{
     static void isAnagram(String s1, String s2)
     {
          //Removing white spaces from
          String str1 = s1.replaceAll("\\s", "");
          String str2 = s2.replaceAll("\\s", "");
          boolean status = true;

          if(str1.length() != str2.length())
          {
               status = false;
          }
          else
          {
               char[] s1Array = str1.toLowerCase().toCharArray();
               char[] s2Array = str2.toLowerCase().toCharArray();
               Arrays.sort(s1Array);
               Arrays.sort(s2Array);
               status = Arrays.equals(s1Array, s2Array);
          }
          if(status)
          {
               System.out.println(s1+" and "+s2+" are anagrams");
          }
          else
          {
               System.out.println(s1+" and "+s2+" are not anagrams");
          }
     }
     public static void main(String[] args)
     {
          isAnagram("keEp", "peeK");
          isAnagram("Java", "Vaja");
          isAnagram("Lock", "Clock");
     }

VARIABLE DECRIPTION
Name Data type Use

s1 String Input string 1

3|Page
s2 String Input string 2

str1 String removes space from s1

str2 String removes space from s2

status boolean used to compare lengths of


strings
s1Array char Array to store string characters

s2Array char Array to store string characters

QUESTION:2
Write a Java program which accepts string from user and displays vowel characters, digits
and blank space separately.

ALGORITHM
CREATE CLASS Alphabets

     CREATE METHOD main(String args[])


     
          INITIALIZE String str;
          INITIALIZE int vowels = 0, digits = 0, blanks = 0;
          INITIALIZE char ch;

          Scanner sc = new Scanner(System.in);


PRINT ("Enter a String : ");
          INPUT str = sc.readLine();
          FOR(int i = 0; i < str.length(); i ++)
          
               ch = str.charAt(i);
               IF(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
               ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
                    vowels ++;
               ELSE IF(Character.isDigit(ch))
                    digits ++;
               ELSE IF(Character.isWhitespace(ch))
                    blanks ++;
          
          PRINT("Vowels : " + vowels);
          PRINT ("Digits : " + digits);
          PRINT ("Blanks : " + blanks);
          PRINT ("\n\n\n ");

4|Page
     CLOSE METHOD
CLOSE CLASS

PROGRAM
import java.util.*;
class Alphabets
{
     public static void main(String args[])
     {
          String str;
          int vowels = 0, digits = 0, blanks = 0;
          char ch;

          Scanner sc = new Scanner(System.in);


          System.out.print("Enter a String : ");
          str = sc.readLine();
          for(int i = 0; i < str.length(); i ++)
          {
               ch = str.charAt(i);
               if(ch == 'a' || ch == 'A' || ch == 'e' || ch == 'E' || ch == 'i' ||
               ch == 'I' || ch == 'o' || ch == 'O' || ch == 'u' || ch == 'U')
                    vowels ++;
               else if(Character.isDigit(ch))
                    digits ++;
               else if(Character.isWhitespace(ch))
                    blanks ++;
          }
          System.out.println("Vowels : " + vowels);
          System.out.println("Digits : " + digits);
          System.out.println("Blanks : " + blanks);
          System.out.println("\n\n\n ");
     }
}

VARIABLE DECRIPTION
Name Data type Use

str String Input string from user


digits int Count no of digits

vowels int Count number of vowels

5|Page
blanks int Count number of blanks

ch char Check whether a character is


vowel or space

QUESTION:3
Write a program to find duplicate character in a string and count the number of occurrences.

ALGORITHM:
CREATE CLASS CountChar

     CREATE METHOD main()


     
          DECLARE String str
          Scanner sc = new Scanner(System.in);
          PRINT("Enter the String:")
          INPUT str
         INITIALIZE count=0, size= 0;
          DO
          
               INITIALIZE char name[] = str.toCharArray()
               size = name.length
               count = 0
               FOR(int j=0; j < size; j++)
               
                    IF((name[0] == name[j]) && ((name[0] >= 65 && name[0] <=
91) || (name[0] >= 97 && name[0] <= 123)))
                   INCREMENT count
               
               IF(count!=0)
                    PRINT(name[0]+" "+count+" Times");
               str = str.replace(""+name[0],"");          
          
          WHILE(size != 1);
     CLOSE METHOD
CLOSE CLASS

PROGRAM
import java.io.*;
public class CountChar
{
     public static void main(String[] args)
     {

6|Page
          String str;
          Scanner sc = new Scanner(System.in);
          System.out.print("Enter the String:");
          str = br.readLine();
          int count=0, size= 0;
          do
          {
               char name[] = str.toCharArray();
               size = name.length;
               count = 0;
               for(int j=0; j < size; j++)
               {
                    if((name[0] == name[j]) && ((name[0] >= 65 && name[0] <=
91) || (name[0] >= 97 && name[0] <= 123)))
                    count++;
               }
               if(count!=0)
                    System.out.println(name[0]+" "+count+" Times");
               str = str.replace(""+name[0],"");          
          }
          while(size != 1);
     }
}

VARIABLE DECRIPTION
Name Data type Use

str String Input string from user


count int Counting the number of letters

size int store size of array

name char stores characters

i,j int loop control variable

QUESTION:4
Write a program to count the number of words in given string.

ALGORITHM

7|Page
CREATE CLASS WordCount

   DECLARE static int i,count=0,result;


    CREATE METHOD static int wordcount(String str)
    
        INITIALIZE char ch[]= new char[str.length()] 
        FOR (i=0; i<str.length(); i++)
        
            ch[i] = str.charAt(i)
            IF ( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
            INCREMENT count++
        CLOSE FOR
        RETURN count

CREATE METHOD main (String args[])

      INITIALIZE  result = WordCount.wordcount("Java is a pure Object


oriented programming language ")
        System.out.println("The number of words in the String are :  "+result);
    CLOSE METHOD
CLOSE CLASS

PROGRAM
class WordCount
{
    static int i,count=0,result;
    static int wordcount(String str)
    {
        char ch[]= new char[str.length()];     
        for(i=0; i<str.length(); i++)
        {
            ch[i] = str.charAt(i);
            if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
            count++;
        }
        return count;
    }    
    public static void main (String args[])
    {
        result = WordCount.wordcount("Java is a pure Object oriented
programming language ");
        System.out.println("The number of words in the String are :  "+result);

8|Page
    }
}

VARIABLE DECRIPTION
Name Data type Use

str String Input string from user


count int Counting the number of letters

size int store size of array

name char stores characters

i,j int loop control variable

QUESTION:1
Write a recursive function to calculate and return GCD of two numbers.

ALGORITHM
CREATE CLASS Recusion_1

CREATE METHOD static int gcd(int b,int s)

IF(s==0)

RETURN b

ELSE

RETURN gcd(s,b%s)

9|Page
CREATE METHOD main(String args[])

CREATE Scanner OBJECT

PRINT("Enter first number")

INPUT int n1=sc.nextInt()

PRINT("Enter second number")

INPUT int n2=sc.nextInt()

CALL gcd=gcd(n1,n2)

PRINT("GCD = "+gcd)

CLOSE METHOD

CLOSE CLASS

PROGRAM
import java.util.Scanner;

class Recusion_1

public static int gcd(int b,int s)

if(s==0)

return b;

else

return gcd(s,b%s);

10 | P a g e
public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter first number");

int n1=sc.nextInt();

System.out.println("Enter second number");

int n2=sc.nextInt();

int gcd=gcd(n1,n2);

System.out.println("GCD = "+gcd);

VARIABLE DESCRIPTION
Name Datatype Use
gcd int To calculate gcd of two
numbers
s int To store small number
b int To store big number
n1 int To store first number
n2 int To store second number

QUESTION
Write a recursive to count and return number of digits of a number given as argument.

ALGORITHM
CREATE Recursion_2

CREATE METHOD static int countDigits(int n)

IF(n/10==0)

11 | P a g e
RETURN 1

ELSE

RETURN countDigits(n/10) + 1

CLOSE METHOD

public static void main(String args[])

CREATE Scanner OBJECT

PRINT("Enter any number")

INPUT int n=sc.nextInt()

INITIALIZE int c=countDigits(n)

PRINT("Number of digits = "+c)

CLOSE METHOD

CLOSE CLASS

PROGRAM
import java.util.Scanner;

class Recursion_2

public static int countDigits(int n)

if(n/10==0)

return 1;

else

12 | P a g e
{

return countDigits(n/10) + 1;

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter any number");

int n=sc.nextInt();

int c=countDigits(n);

System.out.println("Number of digits = "+c);

VARIABLE DESCRIPTION
Name Datatype Use
countDigits int To store number of digits that
are counted
n int To store number
c int To store number of digits that
are counted

QUESTION:3

Create a program to display the Fibonacci series using recursion

ALGORITHM
CREATE CLASS Fibonacci
   CREATE METHOD static int fibonacci(int n)
       IF (n <= 1) {
            return n;
        return fibonacci(n-1) + fibonacci(n-2)

13 | P a g e
   
    CREATE METHOD main(String[] args)
        INITIALIZE int number = 10
  
        PRINT ("Fibonacci Series: First 10 numbers:");
       FOR (int i = 1; i <= number; i++)
        
            PRINT (fibonacci(i) + " ")
        CLOSE FOR
  
CLOSE METHOD
CLOSE CLASS

PROGRAM

public class Main


{
    //method to calculate fibonacci series
    static int fibonacci(int n) {
        if (n <= 1) {
            return n;
        }
        return fibonacci(n-1) + fibonacci(n-2);
    }
    public static void main(String[] args) {
        int number = 10;
  
        //print first 10 numbers of fibonacci series
        System.out.println ("Fibonacci Series: First 10 numbers:");
        for (int i = 1; i <= number; i++)
        {
            System.out.print(fibonacci(i) + " ");
        }
  
}
}
VARIABLE DECRIPTION
Name Data type Use

n int formal variable used for


calculating fibonacci
number int actual vvariable that passes the
value to n
i int loop control variable

j int loop control variable

QUESTION:4
14 | P a g e
Write a program in java to accept a number and count its even digits using recursive
functions

ALGORITHM
CREATE CLASS EvenDigits

CREATE METHOD static int countEvenDigits(int n)

IF(n/10==0)

RETURN n%2==0?1:0

ELSE

RETURN countEvenDigits(n/10)+countEvenDigits(n%10)

CLOSE METHOD

CREATE METHOD main(String args[])

CREATE SCANNER OBJECT

PRINT("Enter any number")

INPUT int n=sc.nextInt()

INITIALIZE int c=countEvenDigits(n)

PRINT("Number of Even digits = "+c)

CLOSE METHOD

CLOSE CLASS

PROGRAM
import java.util.Scanner;

class EvenDigits

public static int countEvenDigits(int n)

if(n/10==0)

return n%2==0?1:0;

15 | P a g e
}

else

return countEvenDigits(n/10)+countEvenDigits(n%10);

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter any number");

int n=sc.nextInt();

int c=countEvenDigits(n);

System.out.println("Number of Even digits = "+c);

VARIABLE DECRIPTION
Name Data type Use

n int formal variable used for input


c int accept the return value from
fuction

PROGRAMS ON NUMBERS
QUESTION:1
Write a program to check whether a number is a Niven number or not. Any positive
integer which is divisible by the sum of its digits is a Niven number or Harshad number
Niven number.
16 | P a g e
ALGORITHM
CREATE CLASS NivenNumber

CREATE METHOD static boolean isNiven (int num)

INITIALIZE int sumofDigits=0

¬INITIALIZE int temp = num

WHILE(temp != 0)

COMPUTE int digit = temp % 10

COMPUTE sumofDigits sumofDigits + digit

COMPUTE temp = temp/ 10

RETURN(num % sumOfDigits == 0)

CREATE METHOD main(String args[])

CREATE Scanner OBJECT

PRINT("Enter an integer (0 to exit)")

INPUT int number = keyboard.nextInt()

WHILE (number != 0)

IF (isNiven (number))

PRINT(number + is a Niven number")

ELSE

PRINT(number + is NOT a Niven number")

PRINT("Enter an integer (0 to exit)")

17 | P a g e
INPUT number = keyboard.nextInt()

PRINT("Exiting...")

CLOSE METHOD

CLOSE CLASS

PROGRAM
/*NivenNumber.java*/

import java.util.Scanner;

public class NivenNumber

static boolean isNiven (int num)

int sumofDigits=0;

int temp = num;

while(temp != 0)

int digit = temp % 10;

sumofDigits sumofDigits + digit;

temp = temp/ 10;

return(num % sumOfDigits == 0);

public static void main(String args[])

Scanner keyboard = new Scanner(System.in);

18 | P a g e
System.out.println("Enter an integer (0 to exit)");

int number = keyboard.nextInt();

while (number != 0)

if (isNiven (number))

System.out.println(number + is a Niven number");

else

System.out.println(number + is NOT a Niven number");

System.out.println("Enter an integer (0 to exit)");

number = keyboard.nextInt();

System.out.println("Exiting...");

keyboard.close();

VARIABLE DESCRIPTION
Name Data Type Use
SumOfDigits int used to calculate the sum of
digits
temp int used to store the value of
num temporarily
num int used to input number
digit int used to calculate digit
number boolean formal variable used to call
the value of num

19 | P a g e
QUESTION:2
Write a program to accept a number and check whether the number is a Palindrome or not.

ALGORITHM
CREATE CLASS PalindromeNumber

CREATE METHOD main(String args[])

CREATE Scanner OBJECT

INITIALIZE int numOrginal, numReverse = 0

PRINT("Enter a number: ")

INIALIZE int num= keyboard.nextInt()

INITIALIZE numOrginal = num

WHILE (num > 0)

COMPUTE int digit = ( int )num % 10

COMPUTE numReverse = numReverse * 10 + digit

COMPUTE num = num / 10

IF (numReverse == numOrginal)

System.out.println(numOriginal + ” is a Palindrome number")

ELSE

PRINT(numOrginal+ “ is a not Palindrome number')

20 | P a g e
CLOSE METHOD

CLOSE CLASS

PROGRAM
/* PalindromeNumber.java* /

import java.util.Scanner;

public class PalindromeNumber

public static void main(String args[])

Scanner keyboard = new Scanner(System.in);

int numOrginal, numReverse = 0;

System.out.print("Enter a number: ");

int num= keyboard.nextInt();

numOrginal = num;

while (num > 0)

int digit = ( int )num % 10;

numReverse = numReverse * 10 + digit;

num = num / 10;

if (numReverse == numOrginal)

System.out.println(numOriginal + ” is a Palindrome number");

else

System.out.println(numOrginal+ “ is a not Palindrome number');

21 | P a g e
keyboard.close();

VARIABLE DESCRIPTION
Name Data Type Use
numOriginal int used to store the original
number
numReverse int used to calculate the reverse of
the number
num int used to input number from
user
digit int used to extract digits of num

QUESTION:3
Write a program to check whether a number is a perfect number or not using a do-while
loop.

ALGORITHM
CREATE CLASS PerfectNumber

CREATE METHOD main(String args[])

INITIALIZE int sum = 0

INITIALIZE int i = 1

CREATE Scanner Object

PRINT(“Enter an integer”)

22 | P a g e
INPUT int num = keyboard.nextInt()

DO

IF(num % i == 0)

COMPUTE sum += i

INCREMENT i++

WHILE (i <= num/2)

CLOSE DO WHILE

IF (sum == num)

PRINT(num + “ is a Perfect Number”);

ELSE

PRINT(num + “ is not a perfect number”);

METHOD CLOSE

CLASS CLOSE

PROGRAM
/*Perfect number.java*/

import java.util.Scanner;

public class PerfectNumber

public static void main(String args[])

int sum = 0;

int i = 1;

23 | P a g e
Scanner keyboard = new scanner(System.in);

System.out.println(“Enter an integer”);

int num = keyboard.nextInt();

do

If(num % i == 0)

Sum += i;

i++;

while (i <= num/2);

if (sum == num)

System.out.println(num + “ is a Perfect Number”);

else

System.out.println(num + “ is not a perfect number”);

keyboard.close();

Name Data Type Use


sum int used to calculate sum of
digits
i int loop control variable
num int used to store number from

24 | P a g e
user

QUESTION:4
Write a program to accept a long integer and check if it is an Armstrong number.

ALGORITHM
CREATE CLASS ArmstrongNumber

CREATE METHOD main(String args[])

CREATE Scanner OBJECT

INITIALIZE long numOrginal, sumOfPowers = 0

INITIALIZE int totalDigits= 0

PRINT("Enter a number: ")

INPUT long num keyboard.nextInt();

INITIALIZE numOrginal = num

WHILE (num ! = 0)

INCREMENT totalDigits++

COMPUTE num = num/10

CLOSE WHILE

25 | P a g e
INITIALIZE num = numOrginal

WHILE(num > 0)

COMPUTE int digit = (int)num % 10;

COMPUTE long digitPower = (int)Math.pow(digit, totalDigits);

COMPUTE sumOfPowers = sumOfPowers + digitPower;

COMPUTE num = num / 10;

CLOSE WHILE

IF (numOrginal == sumOfPowers)

System.out.println(numOrginal + “ is an Armstrong number");

ELSE

PRINT(numOrginal + " is Not an Armstrong number");

CLOSE METHOD

CLOSE CLASS

PROGRAM
/* ArmstrongNumber.java */

import java.util.Scanner;

public class ArmstrongNumber

public static void main(String args[])

Scanner keyboard new Scanner(System.in);

long numOrginal, sumOfPowers = 0;

int totalDigits= 0;

26 | P a g e
System.out.print("Enter a number: ");

long num keyboard.nextInt();

numOrginal = num;

while (num ! = 0)

totalDigits++;

num = num/10;

num = numOrginal;

while (num > 0)

int digit = (int)num % 10;

long digitPower = (int)Math.pow(digit, totalDigits);

sumOfPowers = sumOfPowers + digitPower;

num = num / 10;

If (numOrginal == sumOfPowers)

System.out.println(numOrginal + “ is an Armstrong number");

else

System.out.println(numOrginal + " is Not an Armstrong number");

keyboard.close();

27 | P a g e
VARIABLE DESCRIPTION
Name Data Type Use
numOriginal long used to store the value of
num temporarily
sumOfPowers long used to calculate sum of
digits raised to the power of
number of digits
num long used to input number from
user
totalDigits int used to calculate total
number of digits.

PROGRAMS ON ARRAYS
QUESTION:1
Write a program to create a jagged array in java

Jagged Array in Java-If we are creating odd number of columns in a 2D array, it is known as a
jagged array. In other words, it is an array of arrays with different number of columns.

ALGORITHM
CLASS TestJaggedArray

CREATE METHOD main(String[] args)

INITIALIZE int arr[][] = new int[3][]

INITIALIZE arr[0] = new int[3]

INITIALIZE arr[1] = new int[4]

INITIALIZE arr[2] = new int[2]

INITIALIZE int count = 0

FOR (int i=0; i<arr.length; i++)

FOR(int j=0; j<arr[i].length; j++)

INITIALIZE arr[i][j] = count++

28 | P a g e
FOR (int i=0; i<arr.length; i++)

FOR (int j=0; j<arr[i].length; j++)

PRINT(arr[i][j]+" ")

CLOSE FOR (INNER)

PRINTLN()

CLOSE FOR (OUTER)

CLOSE METHOD

CLOSE CLASS

PROGRAM
class TestJaggedArray{

public static void main(String[] args){

//declaring a 2D array with odd columns

int arr[][] = new int[3][];

arr[0] = new int[3];

arr[1] = new int[4];

arr[2] = new int[2];

//initializing a jagged array

int count = 0;

for (int i=0; i<arr.length; i++)

for(int j=0; j<arr[i].length; j++)

arr[i][j] = count++;

//printing the data of a jagged array

for (int i=0; i<arr.length; i++){

for (int j=0; j<arr[i].length; j++){

System.out.print(arr[i][j]+" ");

29 | P a g e
System.out.println();//new line

VARIABLE DECRIPTION
Name Data type Use

arr int input the array elements and


store
count int Counting the number of
elements
i int outer loop control variable

j char inner loop control variable

QUESTION:2
Java Program to Display Transpose Matrix

ALGORITHM
CREATE CLASS Transpose

CREATE METHOD main(String args[])

INITIALIZE int[][] arr = new int[3][3]

PRINT("enter the elements of matrix")

FOR (int i = 0; i < 3; i++)

FOR (int j = 0; j < 3; j++)

INITIALIZE arr[i][j] = sc.nextInt();

CLOSE FOR (INNER)

CLOSE FOR (OUTER)

30 | P a g e
PRINT("Matrix before Transpose ")

FOR (int i = 0; i < 3; i++)

FOR (int j = 0; j < 3; j++)

PRINT(" " + arr[i][j])

CLOSE FOR

PRINT()

PRINT("Matrix After Transpose ")

FOR (int i = 0; i < 3; i++)

FOR(int j = 0; j < 3; j++)

System.out.print(" " + arr[j][i])

CLOSE FOR

PRINT()

CLOSE METHOD

CLOSE CLASS

PROGRAM
import java.util.*;

public class Transpose

public static void main(String args[])

Scanner sc = new Scanner(System.in);

// initialize the array of 3*3 order

int[][] arr = new int[3][3];

31 | P a g e
System.out.println("enter the elements of matrix");

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

arr[i][j] = sc.nextInt();

System.out.println("Matrix before Transpose ");

// display original matrix

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print(" " + arr[i][j]);

System.out.println();

System.out.println("Matrix After Transpose ");

// transpose and print matrix

for (int i = 0; i < 3; i++) {

for (int j = 0; j < 3; j++) {

System.out.print(" " + arr[j][i]);

System.out.println();

32 | P a g e
}

VARIABLE DECRIPTION
Name Data type Use

arr[][] int Input array and compute


transpose
i int outer loop control variable

j int inner loop control variable

QUESTION:3
Write a program to display upper triangular matrix

ALGORITHM
CREATE class UpperTriangular

CREATE METHOD main(String[] args)

INITIALIZE int rows, col

INITIALIZE int a[][] = {

{1, 2, 3},

{8, 6, 4},

{4, 5, 6}

};

COMPUTE rows = a.length

COMPUTE cols = a[0].length

IF(rows != cols)

PRINT("Matrix should be a square matrix")

ELSE

33 | P a g e
PRINT("Upper triangular matrix: ")

FOR(int i = 0; i < rows; i++)

FOR(int j = 0; j < cols; j++)

IF(i > j)

PRINT("0 ")

ELSE

PRINT (a[i][j] + " ")

CLOSE FOR (INNER)

PRINT()

CLOSE FOR (OUTER)

CLOSE METHOD

CLOSE CLASS

PROGRAM
public class UpperTriangular

public static void main(String[] args)

int rows, cols;

//Initialize matrix a

int a[][] = {

{1, 2, 3},

{8, 6, 4},

{4, 5, 6}

};

//Calculates number of rows and columns present in given matrix

rows = a.length;

34 | P a g e
cols = a[0].length;

if(rows != cols){

System.out.println("Matrix should be a square matrix");

else {

//Performs required operation to convert given matrix into upper triangular matrix

System.out.println("Upper triangular matrix: ");

for(int i = 0; i < rows; i++){

for(int j = 0; j < cols; j++){

if(i > j)

System.out.print("0 ");

else

System.out.print(a[i][j] + " ");

System.out.println();

VARIABLE DECRIPTION
Name Data type Use

35 | P a g e
rows int Input string from user
col int Counting the number of letters

i int store size of array

j int loop control variable

a[][] int array used to calculate the


upper triangle

QUESTION:4
Write a program to rotate a matrix anticlockwise in java.

ALGORITHM
CREATE CLASS RotateMatrixAniclockwise

CRREATE public static void main(String args[])

INITIALIZE int a[][]= {{1,2,3},{4,5,6},{7,8,9}}

PRINT("Original Matrix: \n")

FOR(int i=0;i<3;i++)

FOR(int j=0;j<3;j++)

PRINT(" "+a[i][j]+"\t")

PRINT("\n")

PRINT("Rotate Matrix by 90 Degrees Anti-clockwise: \n");

FOR(int i=2;i>=0;i--)

FOR(int j=0;j<=2;j++)

PRINT(""+a[j][i]+"\t")

CLOSE FOR (INNER)

PRINT("\n");

CLOSE FOR (OUTER)

CLOSE METHOD

CLOSE CLASS

36 | P a g e
PROGRAM
public class RotateMatrixAniclockwise

public static void main(String args[])

int a[][]= {{1,2,3},{4,5,6},{7,8,9}};

System.out.println("Original Matrix: \n");

for(int i=0;i<3;i++)

for(int j=0;j<3;j++)

System.out.print(" "+a[i][j]+"\t");

System.out.println("\n");

System.out.println("Rotate Matrix by 90 Degrees Anti-clockwise: \n");

for(int i=2;i>=0;i--)

for(int j=0;j<=2;j++)

System.out.print(""+a[j][i]+"\t");

System.out.println("\n");

VARIABLE DECRIPTION

37 | P a g e
Name Data type Use

i int loop control variable


j int loop control variable

a[][] int array used for input and


rotation

PROGRAMS ON DATA STRUCTURE


QUESTION:1
Queue is an entity which can hold a maximum of 100 integers. The queue enables the user to
add integers from the rear and remove integers from the front.

ALGORITHM
CREATE CLASS Queue

DECLARE protected int Que[]

DECLAREprotected int front,rear

DECLARE protected int size

CREATE METHOD Queue( int mm)

INITIALIZE size=mm

INITIALIZE front=-1

INITIALIZE rear=-1

INITIALIZE Que=new int[size]

CLOSE METHOD

CREATE METHOD boolean isEmpty()

RETURN front==-1

CREATE void addele(int v)

IF (rear==-1)

INITIALIZE front=0

38 | P a g e
INITIALIZE rear = 0

INITIALIZE Que[rear]= v

ELSE IF ( rear+1 < Que.length)

INITIALIZE Que[++rear] =v

ELSE

PRINT ("OVERFLOW!!")

METHOD CLOSE

CREATE int delele ()

DECLARE int elemnt

IF(isEmpty())

RETURN 9999

ELSE

INITIALIZE elemnt=Que[front]

IF(front==rear)

INITIALIZE front=rear=-1

ELSE

front++

RETURN elemnt

CLOSE METHOD

CREATE METHOD void display()

FOR(int i=front;i<=rear;i++)

System.out.println(Que[i])

CLOSE FOR

39 | P a g e
CLOSE METHOD

CLOSE CLASS

PROGRAM
public class Queue

protected int Que[];

protected int front,rear;

protected int size;

public Queue( int mm)

size=mm;

front=-1;

rear=-1;

Que=new int[size];

boolean isEmpty()

return front==-1;

public void addele(int v)

if (rear==-1)

front=0;

rear = 0;

Que[rear]= v;

40 | P a g e
}

else if( rear+1 < Que.length)

Que[++rear] =v;

else

System.out.println("OVERFLOW!!");

public int delele ()

int elemnt;

if(isEmpty())

return 9999;

else

elemnt=Que[front];

if(front==rear)

front=rear=-1;

else

front++;

return elemnt;

public void display()

for(int i=front;i<=rear;i++)

{System.out.println(Que[i]);

41 | P a g e
}

VARIABLE DESCRIPTION
Name Datatype Use
Que[] int Array to input and store
elements
front int To point the index of the front
rear int To point the index of the rear
size int Stores the size of the array
mm int Inputs size
v int Initializes que
elemnt int Element to be deleted

QUESTION:2
WordPile is an entity which can hold maximum of 20 characters. The restriction is that a
character can be added or removed from one end only.

ALGORITHM
CREATE Class WordPile

DECLARE char[] ch

DECLARE int capacity

DECLARE int top

CREATE METHOD WordPile(int cap)

INITIALIZE capacity = cap

INITIALIZE top = -1

INITIALIZE ch=new char[cap]

CLOSE METHOD

CREATE METHOD pushChar(char v)

IF (top== capacity -1)

PRINT ("WordPile is full.")

42 | P a g e
ELSE

INCREMENT top++

INITIALIZE ch[top] = v

CLOSE METHOD

CREATE METHOD char popChar()

IF (top == -1)

COMPUTE return '\\'

ELSE

INITIALIZE char c = ch[top]

DECREMENT top--

RETURN c

CLOSE METHOD

CLOSE CLASS

PROGRAM
public class WordPile

char[] ch;

int capacity;

int top;

public WordPile(int cap)

capacity = cap;

43 | P a g e
top = -1;

ch=new char[cap];

void pushChar(char v)

if (top== capacity -1)

System.out.println("WordPile is full.");

else

top++;

ch[top] = v;

char popChar()

if (top == -1)

return '\\';

else

char c = ch[top];

top--;

return c;

44 | P a g e
VARIABLE DESCRIPTION
Name Datatype Use
ch[] char Character array to store the
character elements
capacity int Integer variable to store the
maximum capacity
top int To point to the index of the
topmost element
cap int Initialize data member
capacity
v char Used as a formal variable

QUESTION:3
A double-ended queue is a linear data structure which enables the user to add and remove
integer from either ends, i.e., from front or rear.

ALGORITHM:
CREATE Class Dequeue

DECLARE int arr[]

DECLARE int lim, front, rear

CREATE METHOD Dequeue(int l)

INITIALISE lim = l

INITIALISE front = rear = 0

INITIALISE arr =new int[l]

COSE METHOD

CREATE METHOD addfront (int val)

IF ( front > 0)

INITIALIZE arr[front] = val

45 | P a g e
DECREMENT front--

Else

PRINT ("Overflow from front. ")

CLOSE METHOD

CREATE METHOD addrear( int val)

IF (rear < lim -1)

INCREMENTN ++rear

INITIALIZE arr[rear] = val

ELSE

PRINT ( "Overflow from rear. ")

CLOSE METHOD

CREATE METHOD int popfront()

IF (front != rear)

INITIALZE int val = arr[front]

INCREMENT ++front

RETURN val

ELSE

RETURN -9999

CLOSE METHOD

46 | P a g e
CLOSE CLASS

PROGRAM
public class Dequeue

int arr[];

int lim, front, rear;

public Dequeue(int l)

lim = l;

front = rear = 0;

arr new int[l];

void addfront (int val)

if ( front > 0)

arr[front] = val;

front--;

else

System. out.println("Overflow from front. ");

void addrear( int val)

if (rear < lim -1)

47 | P a g e
{

++rear;

arr[rear] = val;

else

System.out.printIn ( "Overflow from rear. ");

int popfront()

if (front != rear)

int val = arr[front];

++front;

return val;

else

return -9999;

VARIABLE DESCRIPTION
Name Datatype Use
arr[] int Array to store up to 100
integer elements
lim int Stores the limit of the
dequeue
front int To point to the index of the
front end
rear int To point to the index of the
rear end
l int Formal variable that initializes
data members
val int Used to add integer from the
rear

48 | P a g e
QUESTION:4
NIC institute’s resource manager has decided to network the computer resources like printer,
storage media, etc. so that minimum resources and maximum sharing could be availed.
Accordingly printers are linked to a centralized system and the printing jobs are done on a
‘first cum first served’ basis only. This is like the first person’s printing job will get done first
and the next person’s job will be done as the next job in the list and so on.

ALOGORTITHM
CREATE Class Printjob

DECLARE protected int job[ ]

DECLARE protected int front, rear

DECLARE protected int Capacity

DECLARE protected int Newjob

CREATE METHOD Printjob()

INITIALZE Capacity = 20

INITIALIZE front =-1

INITIALIZE rear =1

CALL METHOD createJob()

CLOSE METHOD

CREATE METHOD createJob()

INITIALIZE job =new int[Capacity]

CLOSE METHOD

CREATE METHOD boolean isEmpty()

RETURN front = = -1

CLOSE METHOD

CREATE METHOD addJob()

49 | P a g e
INITIALIZE int id = 0

PRINT ("Enter the job id of new print job:")

CREATE SCANNER OBJECT

TRY

INPUT id=sc.nextInt()

CATCH(Exception e)

PRINT(e)

INITIALIZE Newjob = id

IF ( rear == -1)

INITIALIZE front rear = 0

INITIALIZE job[rear] = id

ELSE IF ( rear+1 < job.length)

INITIALIZE job[++rear] = id

METHOD CLOSE

CREATE METHOD removeJob ()

DECLARE int elem

IF ( isEmpty() )

PRINT ("Printjob is empty")

ELSE

INITIALIZE elem= job[front]

IF ( front == rear)

INITIALIZE front rear = -1

ELSE

INCREMENT front ++

PRINT ("The print job removed is:" + elem)

50 | P a g e
CLOSE METHOD

CLOSE CLASS

PROGRAM
import java.util.Scanner;

public class Printjob

protected int job[ ];

protected int front, rear;

protected int Capacity;

protected int Newjob;

public Printjob()

Capacity = 20;

front -1;

rear =1;

createJob();

private void createJob()

job new int[Capacity];

boolean isEmpty()

return front = = -1;

public void addJob()

51 | P a g e
int id = = 0;

System.out.println("Enter the job id of new print job:");

Scanner in = new Scanner(System.in);

try

id = in.nextInt ();

catch(Exception e)

System.out.println(e);

Newjob = id;

if ( rear == -1)

front rear = 0;

job[rear] = id;

else if( rear+1 < job.length)

job[++rear] = id;

public void removeJob ()

int elem;

if( isEmpty() )

System.out.println ("Printjob is empty");

else

52 | P a g e
elem job[front] ;

if ( front == rear)

front rear = -1;

else

front ++

System.out.println("The print job removed is:" + elem);

VARIABLE DESCRIPTION
Name Datatype Use
Job[] int Array of integers to store the
printing jobs
Newjob int To add a new printing job into
the array
Capacity int The maximum capacity of the
integer array
front int To point to the index of the
front
rear char To point to the index of the
rear
id int To initialize

PROGRAMS ON OPERATION ON FILES


QUESTION:1
Read names of 5 students through keyword and store them in file names.txt.

ALGORITHM
CREATE Class I0

INITIALIZE String fileName = ("names.txt")

CREATE StreamReader OBJECT

CREATE BufferedReader OBJECT

public static void main(String[ ] args)

53 | P a g e
TRY

CREATE FileWriter OBJECT

CREATE BufferedWriter OBJECT

CREATE Printwriter OBJECT

for (int i = 0; i< 5; i++)

START FOR LOOP

PRINT ("Enter Name ")

INPUT String name = stdin.readLine( )

outFile.println(name)

CLOSE FOR LOOP

outFile.close()

CATCH(IOException e)

PRINT (e)

CLOSE CLASS

PROGRAM
import java.io.* ;

public class I0

static String fileName = ("names.txt") ;

static InputStreamReader isr = new InputStreamReader(System.in) ;

static BufferedReader stdin = new BufferedReader (isr) ;

public static void main(String[ ] args)

try

FileWriter fw = new FileWriter (fileName);

54 | P a g e
BufferedWriter bW = new Bufferedwriter (fw);

Printwriter outFile = new PrintWriter(bw);

for (int i = 0; i< 5; i++)

System.out.print("Enter Name ");

String name = stdin.readLine( );

outFile.println(name);

outFile.close();

catch(IOException e)

System.err.println(e);

VARIABLE DESCRIPTION
Name Datatype Use
name String to input name of file
i int loop control variable

QUESTION:2
Read rollno and marks of 5 students and write them on a file namely “stu.dat”.

ALGORITHM
CREATE Class BinaryOutput

CREATE String fileName = "stu.dat"

CREATE InputStreamReader OBJECT

55 | P a g e
CREATE BufferedReader OBJECT

public static void main(String[ ] args)

TRY

DECLARE int rno

DECLARE int float marks

CREATE FileOutputStream OBJECT

CREATE DataOutputStream OBJECT

FOR (int i = 0; i<5;i++)

START FOR LOOP

PRINT(“Enter Rollno :”)

INPUT rno=sc.nextInt()

PRINT(“Enter Marks :”)

INPUT marks=sc.nextInt()

dw.writeInt(rno)

dw.writeFloat(marks)

CLOSE FOR LOOP

CLOSE dw

CLOSE fw

CATCH(IOException e)

PRINT(e)

CLOSE CLASS

PROGRAM
import java.io.* ;

public class BinaryOutput

static String fileName = "stu.dat";

static InputStreamReader isr = new InputStreamReader (System.in);

static BufferedReader stdin = new BufferedReader (isr) ;

56 | P a g e
public static void main(String[ ] args)

try

int rno; float marks ;

FileOutputStream fw = new FileOutputStream(fileName) ;

DataoutputStream dw = new Dataoutputstream(fw);

for (int i = 0; i<5;i++)

System.out.print(“Enter Rollno :”);

rno=Integer.parseInt(stdin.readLine());

System.out.print(“Enter Marks :”);

marks=Float.parseFloat(stdin.readLine());

dw.writeInt(rno);

dw.writeFloat(marks);

dw.close();

fw.close();

catch(IOException e)

System.err.println(e);

VARIABLE DESCRIPTION
Name Datatype Use

57 | P a g e
marks float to input marks of student
rno int to input roll number
i int loop control variable

QUESTION:3
Input a string and separate words in it. Process the string as a character array.

ALGORITHM
CREATE Class StringProcessing

CREATE InputStreamReader OBJECT

CREATE static BufferedReader OBJECT

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

PRINT ("Input a string")

INPUT String data=keyboardInput.readLine()

INPUT int numberCharacters= data.length( )

PRINT( "Number of characters ="numberCharacters "\n)

FOR (int counter 0; counter < numberCharacters ; counter++)

START FOR LOOP

INPUT char character = data.charAt (counter)

IF(character = = ')

PRINT

ELSE

PRINT (character)

CLOSE FOR LOOP

PRINT(“\n”)

CLOSE CLASS

PROGRAM

58 | P a g e
import java.io.*;

import java.util.*;

class StringProcessing

static InputStreamReader input = new InputStreamReader (System. in);

static BufferedReader keyboardInput = new BufferedReader (input);

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

System.out.printin("Input a string") ;

String data = keyboardInput.readLine();

int numberCharacters data.length( );

System.out.println( "Number of characters ="numberCharacters "\n);

for (int counter 0; counter < numberCharacters ; counter++)

char character = data.charAt (counter) ;

if(character = = ')

System.out.printIn() ;

else

System.out.print(character);

System.out.println(“\n”);

VARIABLE DESCRIPTION
Name Datatype Use
data String Used to input a string
counter Int loop control variable

QUESTION:4

59 | P a g e
Read data from text file “names.txt” and display it on monitor.

ALGORITHM
CREATE Class FileIO

CREATE FileReader OBJECT

CREATE BufferedReader OBJECT

DECLARE String test

INITILIZE int i=0

WHILE((test = fileInput.readLine())!= null)

START WHILE LOOP

INCREMENT i++

PRINT(“Name “ + i + “ : “)

PRINT(text)

CLOSE WHILE LOOP

CLOSE FILE

CLOSE CLASS

PROGRAM
import java.io.*;

class FileIO

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

FileReader file = new FileReader(“names.txt”);

BufferedReader fileInput = new BufferedReader(file);

String text;

Int i=0;

while((text = fileInput.readLine())!=null)

60 | P a g e
i++;

System.out.print(“Name “ + i + “ : “);

System.out.println(text);

fileInput.close();

VARIABLE DESCRIPTION
Name Datatype Use
text String used to input text and store it
in file
i Int loop control variable

MISCELLANEOUS PROGRAMS (DATE PROGRAMS)


QUESTION:1
Write a program to input day number and year and display date.

ALGORITHM
CREATE Class DayNumberToDate

public static void main(String args[])

CREATE Scanner OBJECT

PRINT ("Enter day number")

INPUT int n=sc.nextInt()

PRINT ("Enter year")

INPUT int y=sc.nextInt()

COMPUTE int ar[]={31,y%4==0?29:28,31,30,31,30,31,31,30,31,30,31}

INITIALIZE int i=0

WHILE (ar[i]<n)

START WHILE LOOP

61 | P a g e
INITIALIZE n-=ar[i]

INCREMENT i++

END WHILE LOOP

INITIALIZE int d=n

INITIALIZE int m=i+1

PRINT (d+"/"+m+"/"+y)

CLOSE CLASS

PROGRAM
import java.util.*;

class DayNumberToDate

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter day number");

int n=sc.nextInt();

System.out.println("Enter year");

int y=sc.nextInt();

int ar[]={31,y%4==0?29:28,31,30,31,30,31,31,30,31,30,31};

int i=0;

while(ar[i]<n)

n-=ar[i];

i++;

int d=n;

62 | P a g e
int m=i+1;

System.out.println(d+"/"+m+"/"+y);

VARIABLE DESCRIPTION
Name Datatype Use
n int To store the number of days
y int To store the year which is
entered by the user
ar[] int To check the month
i int To initialize
d int To store the number of days
m int To store the month

QUESTION:2
Write a program to input a date in dd/mm/yyyy format and print next date. Assume that
entered date is valid.

ALGORITHM
CREATE Class NextDate

public static void main(String args[])

CREATE Scanner OBJECT

PRINT ("Enter date (dd/mm/yyyy)")

INITIALIZE String date=sc.next()

CRAETE Scanner OBJECT 2 (date)

sc2.useDelimiter("/")

INPUT int d=sc2.nextInt()

INPUT int m=sc2.nextInt()

INPUT int y=sc2.nextInt()

COMPUTE int ar[]={31,(y%4==0?29:28),31,30,31,30,31,31,30,31,30,31}

63 | P a g e
IF (d<ar[m-1])

START OUTER IF

INCREMENT d++

CLOSE OUTER IF

ELSE

IF (m<12)

START INNER IF

INITIALIZE d=1

INCREMENT m++

END INNER IF

ELSE

INITIALIZE d=1

INITIALIZE m=1

INCREMENT y++

PRINT (d+"/"+m+"/"+y)

CLOSE CLASS

PROGRAM
import java.util.*;

class NextDate

public static void main(String args[])

Scanner sc=new Scanner(System.in);

System.out.println("Enter date (dd/mm/yyyy)");

String date=sc.next();

64 | P a g e
Scanner sc2=new Scanner(date);

sc2.useDelimiter("/");

int d=sc2.nextInt();

int m=sc2.nextInt();

int y=sc2.nextInt();

int ar[]={31,(y%4==0?29:28),31,30,31,30,31,31,30,31,30,31};

if(d<ar[m-1])

d++;

else

if(m<12)

d=1;

m++;

else

d=1;

m=1;

y++;

System.out.println(d+"/"+m+"/"+y);

65 | P a g e
}

VARIABLE DESCRIPTION
Name Datatype Use
date String To store date
d int To store date which is entered
by the user
m int To store month which is
entered by the user
y int To store year which is entered
by the user
ar[] int To check the month

PROGRAMS ON INHERITANCE
QUESTION:1
In the below program of inheritance, class Bicycle is a base class, class MountainBike is a
derived class that extends Bicycle class and class Test is a driver class to run program.

ALGORITHM
CREATE CLASS Bicycle

DECLARE int gear

DECLARE int speed

CREATE METHOD Bicycle(int gear, int speed)

INITITALIZE this.gear = gear

INITIALIZE this.speed = speed

CLOSE METHOD

CRAETE METHOD void applyBrake(int decrement)

COMPUTE speed -= decrement

66 | P a g e
CLOSE METHOD

CREATE METHOD void speedUp(int increment)

COMPUTE speed += increment

CLOSE METHOD

CREATE METHOD String toString()

RETURN("No of gears are " + gear + "\n"

+ "speed of bicycle is " + speed)

CLOSE METHOD

CLOSE CLASS

CREATE CLASS MountainBike extends Bicycle

DECLAREpublic int seatHeight;

CREATE METHOD MountainBike(int gear, int speed,

int startHeight)

super(gear, speed);

seatHeight = startHeight;

CLOSE METHOD

CREATE METHOD public void setHeight(int newValue)

INITIALIZE seatHeight = newValue

CLOSE METHOD

67 | P a g e
CREATE METHOD @Override public String toString()

return (super.toString() + "\nseat height is "

+ seatHeight);

CLOSE METHOD

CLOSE CLASS

CREATE CLASS Test

CREATE METHOD main(String args[])

CALL MountainBike mb = new MountainBike(3, 100, 25);

PRINT(mb.toString())

CLOSE METHOD

CLOSE CLASS

PROGRAM
class Bicycle

public int gear;

public int speed;

public Bicycle(int gear, int speed)

68 | P a g e
this.gear = gear;

this.speed = speed;

public void applyBrake(int decrement)

speed -= decrement;

public void speedUp(int increment)

speed += increment;

public String toString()

return ("No of gears are " + gear + "\n"

+ "speed of bicycle is " + speed);

class MountainBike extends Bicycle {

public int seatHeight;

69 | P a g e
public MountainBike(int gear, int speed,

int startHeight)

super(gear, speed);

seatHeight = startHeight;

public void setHeight(int newValue)

seatHeight = newValue;

@Override public String toString()

return (super.toString() + "\nseat height is "

+ seatHeight);

public class Test {

public static void main(String args[])

70 | P a g e
MountainBike mb = new MountainBike(3, 100, 25);

System.out.println(mb.toString());

VARIABLE DESCRIPTION
Name Datatype Use
gear int used to input gear

speed int used to input speed and


increment and decrement it
seatHeight int used to set seat height

QUESTION:2
Create a class named Animal and use it to categorize the names of various animals using
inheritance.

ALGORITHM
CREATE CLASS Animal

INITITALIZE String name

CREATE METHOD void eat()

PRINT("I can eat")

CLOSE METHOD

CREATE CLASS Dog extends Animal

CREATE METHOD public void display()

PRINT("My name is " + name)

71 | P a g e
CREATE METHOD main(String[] args)

CRAETE OBJECT Dog labrador = new Dog()

INITIALIZE labrador.name = "Rohu"

labrador.display()

labrador.eat()

CLOSE METHOD

CLOSE CLASS

PROGRAM
class Animal {

String name;

public void eat() {

System.out.println("I can eat");

class Dog extends Animal {

public void display() {

72 | P a g e
System.out.println("My name is " + name);

class Main {

public static void main(String[] args) {

Dog labrador = new Dog();

labrador.name = "Rohu";

labrador.display();

labrador.eat();

VARIABLE DESCRIPTION
Name Datatype Use
name int to input name of animal

QUESTION:3
Create a class calculator with the methods addition(int a, b) , multiplication(int a , b), etc. and
use it by inheritance for calculation of two numbers.

ALGORITHM
CREATE CLASS Calculation

DECLARE int z

73 | P a g e
CREATE METHOD public void addition(int x, int y)

COMPUTE z = x + y

PRINT("The sum of the given numbers:"+z)

CLOSE METHOD

CRAETE METHOD void Subtraction(int x, int y)

COMPUTE z = x - y

PRINT("The difference between the given numbers:"+z)

CLOSE METHOD

CLOSE CLASS

CREATE CLASS My_Calculation extends Calculation

CREATE METHOD void multiplication(int x, int y)

COMPUTE z = x * y

System.out.println("The product of the given numbers:"+z)

CLOSE METHOD

CREATE METHOD main(String args[])

INITIALIZE int a = 20, b = 10

CALL My_Calculation demo = new My_Calculation()

demo.addition(a, b)

demo.Subtraction(a, b)

demo.multiplication(a, b)

CLOSE METHOD

CLOSE CLASS

PROGRAM

74 | P a g e
class Calculation {

int z;

public void addition(int x, int y) {

z = x + y;

System.out.println("The sum of the given numbers:"+z);

public void Subtraction(int x, int y) {

z = x - y;

System.out.println("The difference between the given numbers:"+z);

public class My_Calculation extends Calculation {

public void multiplication(int x, int y) {

z = x * y;

System.out.println("The product of the given numbers:"+z);

public static void main(String args[]) {

int a = 20, b = 10;

My_Calculation demo = new My_Calculation();

demo.addition(a, b);

demo.Subtraction(a, b);

demo.multiplication(a, b);

75 | P a g e
}

VARIABLE DESCRIPTION
Name Datatype Use
a int actual variable used to send
inputs to calling class
b int actual variable used to send
inputs to calling class
x,y,z int used as formal variables while
calculation

QUESTION:4
Create a class Player and inherit class SoccerPlayer use this to name and categorize the player
if he plays soccer.

ALGORITHM
CREATE CLASS Player

  INITIALIZE String name

  CREATE METHOD Player(String name)

    INITIALIZE this.name = name

  CLOSE METHOD

  CREATE METHOD public void run()

    PRINTname + " is running")

CLOSE METHOD

CLOSE NAME

CREATE CLASS SoccerPlayer extends Player

  CREATE METHOD SoccerPlayer(String name)

    CALL super(name)

  CLOSE METHOD

  CREATE METHOD void kick()

    PRINT(name + " is kicking the ball");

76 | P a g e
  CLOSE METHOD

CLOSE CLASS

 PROGRAM
public class InheritanceExample

  public static void main(String[] args)

    SoccerPlayer soccerPlayer = new SoccerPlayer("John");

    // Calling base class method

    soccerPlayer.run();

    // Calling subclass method

    soccerPlayer.kick();

  }

class Player

  String name;

  Player(String name)

    this.name = name;

  }

  public void run()

    System.out.println(name + " is running");

  }

77 | P a g e
// SoccerPlayer class inherits features from Player

class SoccerPlayer extends Player {

  SoccerPlayer(String name) {

    super(name);

  }

  public void kick() {

    System.out.println(name + " is kicking the ball");

  }

public class InheritanceExample

  public static void main(String[] args)

    SoccerPlayer soccerPlayer = new SoccerPlayer("John");

    // Calling base class method

    soccerPlayer.run();

    // Calling subclass method

    soccerPlayer.kick();

  }

VARIABLE DESCRIPTION
Name Datatype Use
name String used to input and pass the
name of the player

78 | P a g e

You might also like