Computer Project by Aditi Singh of Class 12-b

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 85

COMPUTER PROJECT

- ADITI SINGH

- XII-B

INDEX
Topic Page Number Signature
1|Page
PROGRAMS ON STRINGS
Write a program to check 5-7
if the two given string are
anagram or not.
Write a Java program
which accepts string from 7-9
user and displays vowel
characters, digits and
blank space separately.
Write a program to find
duplicate character in a 9-11
string and count the
number of occurrences.
Write a program to count
the number of words in 11-13
given string.
PROGRAMS ON RECURSION
Write a recursive function 13-15
to calculate and return
GCD of two numbers.
Write a recursive to count
and return number of 15-17
digits of a number given
as argument.
Create a program to
display the Fibonacci 17-19
series using recursion.
Write a program in java to
accept a number and 19-21
count its even digits using
recursive functions.
PROGRAMS ON NUMBERS
Write a program to check 21-24
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.
Write a program to accept
a number and check 24-26
whether the number is a
Palindrome or not.
Write a program to check
whether a number is a 26-29
perfect number or not
using a do-while loop.
Write a program to accept
a long integer and check if 29-32
it is an Armstrong
number.

2|Page
PROGRAMS ON ARRAYS
Write a program to create 32-34
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.
Java Program to Display
Transpose Matrix 34-37
Write a program to
display upper triangular 37-40
matrix
Write a program to rotate
a matrix anticlockwise in 40-42
java.
PROGRAMS ON DATA
STRUCTURE 42-47
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.
WordPile is an entity
which can hold maximum 47-50
of 20 characters. The
restriction is that a
character can be added or
removed from one end
only.
A double-ended queue is a
linear data structure 50-54
which enables the user to
add and remove integer
from either ends, i.e., from
front or rear.
NIC institute’s resource
manager has decided to 54-59
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’

3|Page
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.
PROGRAMS ON
OPERATION ON FILES 59-61
Read names of 5 students
through keyword and
store them in file
names.txt.
Read rollno and marks of
5 students and write them 61-63
on a file namely “stu.dat”.
Input a string and
separate words in it. 63-65
Process the string as a
character array.
Read data from text file
“names.txt” and display it 65-67
on monitor.
MISCELLANEOUS
PROGRAMS(DATE 67-69
PROGRAMS)
Write a program to input
day number and year and
display date.
Write a program to input
a date in dd/mm/yyyy 69-72
format and print next
date. Assume that entered
date is valid.
PROGRAMS ON
INHERITANCE 72-77
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.
Create a class named
Animal and use it to 77-80
categorize the names of
various animals using
inheritance.
Create a class calculator
with the methods 80-83
addition(int a, b) ,
multiplication(int a , b),
etc. and use it by

4|Page
inheritance for calculation
of two numbers.
Create a class Player and
inherit class SoccerPlayer 83-86
use this to name and
categorize the player if he
plays soccer.

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.

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)
          

5|Page
               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
{
     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)
          {

6|Page
               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


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[])


     

7|Page
          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 ");
     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);

8|Page
               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
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

9|Page
         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)
     {
          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++;

10 | P a g e
               }
               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

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

11 | P a g e
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);
    }
}

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

12 | P a g e
i,j int loop control variable

PROGRAM ON RECURSION
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)

CREATE METHOD main(String args[])

CREATE Scanner OBJECT

PRINT("Enter first number")

INPUT int n1=sc.nextInt()

13 | P a g e
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);

public static void main(String args[])

Scanner sc=new Scanner(System.in);

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

14 | P a g e
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:2
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)

RETURN 1

ELSE

15 | P a g e
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

return countDigits(n/10) + 1;

16 | P a g e
}

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 staticintfibonacci(intn)
       IF(n <= 1) {
            returnn;
        returnfibonacci(n-1) + fibonacci(n-2)
   
    CREATE METHODmain(String[] args)

17 | P a g e
        INITIALIZE intnumber = 10
  
        PRINT ("Fibonacci Series: First 10 numbers:");
       FOR(inti = 1; i<= number; i++)
        
            PRINT (fibonacci(i) + " ")
        CLOSE FOR
  
CLOSE METHOD
CLOSE CLASS

PROGRAM

public classMain
{
    //method to calculate fibonacci series
    staticintfibonacci(intn) {
        if(n <= 1) {
            returnn;
        }
        returnfibonacci(n-1) + fibonacci(n-2);
    }
    publicstaticvoidmain(String[] args) {
        intnumber = 10;
  
        //print first 10 numbers of fibonacci series
        System.out.println ("Fibonacci Series: First 10 numbers:");
        for(inti = 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

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

ALGORITHM
CREATE CLASSEvenDigits

CREATE METHOD static int countEvenDigits(int n)

IF(n/10==0)

RETURN n%2==0?1:0

ELSE

RETURNcountEvenDigits(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)

19 | P a g e
{

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

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
20 | P a g e
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.

ALGORITHM
CREATE CLASS NivenNumber

CREATE METHOD static booleanisNiven (int num)

INITIALIZE int sumofDigits=0

¬INITIALIZE int temp = num

WHILE(temp != 0)

COMPUTE int digit = temp % 10

COMPUTE sumofDigitssumofDigits + 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))
21 | P a g e
PRINT(number + is a Niven number")

ELSE

PRINT(number + is NOT a Niven number")

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

INPUT number = keyboard.nextInt()

PRINT("Exiting...")

CLOSE METHOD

CLOSE CLASS

PROGRAM
/*NivenNumber.java*/

import java.util.Scanner;

public class NivenNumber

static booleanisNiven (int num)

int sumofDigits=0;

int temp = num;

while(temp != 0)

int digit = temp % 10;

sumofDigitssumofDigits + digit;

temp = temp/ 10;

22 | P a g e
}

return(num % sumOfDigits == 0);

public static void main(String args[])

Scanner keyboard = new Scanner(System.in);

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
23 | P a g e
num int used to input number
digit int used to calculate digit
number boolean formal variable used to call
the value of num

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 intnum= keyboard.nextInt()

INITIALIZE numOrginal = num

WHILE (num> 0)

COMPUTE int digit = ( int )num % 10

COMPUTE numReverse = numReverse * 10 + digit

24 | P a g e
COMPUTE num = num / 10

IF (numReverse == numOrginal)

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

ELSE

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

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;

25 | P a g e
num = num / 10;

if (numReverse == numOrginal)

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

else

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

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”)

26 | 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;

27 | P a g e
int i = 1;

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();

VARIABLE DESCRIPTION
Name Data Type Use
sum int used to calculate sum of
digits

28 | P a g e
i int loop control variable
num int used to store number from
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 numkeyboard.nextInt();

INITIALIZE numOrginal= num

WHILE (num ! = 0)

INCREMENT totalDigits++

COMPUTE num = num/10

CLOSE WHILE

29 | P a g e
INITIALIZE num = numOrginal

WHILE(num> 0)

COMPUTE int digit = (int)num % 10;

COMPUTE longdigitPower = (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;

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

long numkeyboard.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();

31 | 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
CLASSTestJaggedArray

CREATE METHOD main(String[] args)

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

INITIALIZE arr[0] = new int[3]

INITIALIZEarr[1] = new int[4]

INITIALIZEarr[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++)

32 | P a g e
INITIALIZEarr[i][j] = count++

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++){

33 | P a g e
System.out.print(arr[i][j]+" ");

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 METHODmain(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();

34 | P a g e
CLOSE FOR (INNER)

CLOSE FOR (OUTER)

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

35 | P a g e
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];

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 ");

36 | P a g e
// 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();

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 METHODmain(String[] args)

INITIALIZE int rows, col

INITIALIZE int a[][] = {

{1, 2, 3},

{8, 6, 4},

{4, 5, 6}

37 | P a g e
};

COMPUTE rows = a.length

COMPUTE cols = a[0].length

IF(rows != cols)

PRINT("Matrix should be a square matrix")

ELSE

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

38 | P a g e
int a[][] = {

{1, 2, 3},

{8, 6, 4},

{4, 5, 6}

};

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

rows = a.length;

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();

39 | P a g e
}

VARIABLE DECRIPTION
Name Data type Use
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 CLASSRotateMatrixAniclockwise

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")

40 | P a g e
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

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");

41 | P a g e
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
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

42 | P a g e
CREATE METHOD Queue( int mm)

INITIALIZE size=mm

INITIALIZE front=-1

INITIALIZE rear=-1

INITIALIZE Que=new int[size]

CLOSE METHOD

CREATE METHOD booleanisEmpty()

RETURN front==-1

CREATE void addele(int v)

IF (rear==-1)

INITIALIZE front=0

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

43 | P a g e
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

CLOSE METHOD

CLOSE CLASS

PROGRAM
public class Queue

protected int Que[];

protected int front,rear;

protected int size;

public Queue( int mm)

size=mm;

44 | P a g e
front=-1;

rear=-1;

Que=new int[size];

booleanisEmpty()

return front==-1;

public void addele(int v)

if (rear==-1)

front=0;

rear = 0;

Que[rear]= v;

else if( rear+1 <Que.length)

Que[++rear] =v;

else

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

public int delele ()

int elemnt;

if(isEmpty())

return 9999;

45 | P a g e
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]);

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

46 | P a g e
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.")

ELSE

INCREMENT top++

INITIALIZE ch[top] = v

CLOSE METHOD

CREATE METHOD char popChar()

47 | P a g e
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;

top = -1;

ch=new char[cap];

void pushChar(char v)

if (top== capacity -1)

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

48 | P a g e
else

top++;

ch[top] = v;

char popChar()

if (top == -1)

return '\\';

else

char c = ch[top];

top--;

return c;

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

49 | P a g e
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

DECREMENT front--

Else

50 | P a g e
PRINT ("Overflow from front. ")

CLOSE METHOD

CREATE METHOD addrear( intval)

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

CLOSE CLASS

PROGRAM

51 | P a g e
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( intval)

if (rear <lim -1)

++rear;

52 | P a g e
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

53 | 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 booleanisEmpty()

RETURN front = = -1

CLOSE METHOD

54 | P a g e
CREATE METHOD addJob()

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

55 | P a g e
INCREMENT front ++

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

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];

booleanisEmpty()

return front = = -1;

56 | P a g e
}

public void addJob()

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;

57 | P a g e
if( isEmpty() )

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

else

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.

58 | P a g e
ALGORITHM
CREATE Class I0

INITIALIZE String fileName = ("names.txt")

CREATE StreamReader OBJECT

CREATE BufferedReader OBJECT

public static void main(String[ ] args)

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") ;

59 | P a g e
static InputStreamReaderisr = new InputStreamReader(System.in) ;

static BufferedReader stdin = new BufferedReader (isr) ;

public static void main(String[ ] args)

try

FileWriterfw = new FileWriter (fileName);

BufferedWriterbW = new Bufferedwriter (fw);

PrintwriteroutFile = 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

60 | P a g e
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

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

61 | P a g e
CATCH(IOException e)

PRINT(e)

CLOSE CLASS

PROGRAM
import java.io.* ;

public class BinaryOutput

static String fileName = "stu.dat";

static InputStreamReaderisr = new InputStreamReader (System.in);

static BufferedReader stdin = new BufferedReader (isr) ;

public static void main(String[ ] args)

try

int rno; float marks ;

FileOutputStreamfw = new FileOutputStream(fileName) ;

DataoutputStreamdw = 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();

62 | P a g e
fw.close();

catch(IOException e)

System.err.println(e);

VARIABLE DESCRIPTION
Name Datatype Use
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 intnumberCharacters= data.length( )

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

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

63 | P a g e
START FOR LOOP

INPUT char character = data.charAt (counter)

IF(character = = ')

PRINT

ELSE

PRINT (character)

CLOSE FOR LOOP

PRINT(“\n”)

CLOSE CLASS

PROGRAM
import java.io.*;

import java.util.*;

class StringProcessing

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

static BufferedReaderkeyboardInput = new BufferedReader (input);

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

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

String data = keyboardInput.readLine();

int numberCharactersdata.length( );

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

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

char character = data.charAt (counter) ;

if(character = = ')

64 | P a g e
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
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

65 | P a g e
CLOSE CLASS

PROGRAM
import java.io.*;

class FileIO

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

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

BufferedReaderfileInput = new BufferedReader(file);

String text;

Int i=0;

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

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)


66 | P a g e
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

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

67 | P a g e
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;

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

68 | P a g e
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}

IF (d<ar[m-1])

START OUTER IF

INCREMENT d++

CLOSE OUTER IF

ELSE

IF (m<12)

START INNER IF

69 | P a g e
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();

Scanner sc2=new Scanner(date);

sc2.useDelimiter("/");

int d=sc2.nextInt();

int m=sc2.nextInt();

int y=sc2.nextInt();

70 | P a g e
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);

VARIABLE DESCRIPTION
Name Datatype Use
date String To store date
d int To store date which is
entered by the user

71 | P a g e
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

CLOSE METHOD

CREATE METHOD void speedUp(int increment)

COMPUTE speed += increment

72 | P a g e
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

CREATE METHOD @Override public String toString()

73 | P a g e
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)

this.gear = gear;

this.speed = speed;

74 | P a g e
}

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;

75 | 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

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

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

77 | P a g e
CREATE METHOD public void display()

PRINT("My name is " + name)

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");

78 | P a g e
}

class Dog extends Animal

public void display()

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();

79 | P a g e
}

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

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)

80 | P a g e
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
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;

81 | P a g e
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);

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

82 | P a g e
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 CLASSSoccerPlayer extends Player

  CREATE METHOD SoccerPlayer(String name)

    CALL super(name)

  CLOSE METHOD

  CREATE METHOD void kick()

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

  CLOSE METHOD

CLOSE CLASS

 PROGRAM
public class InheritanceExample

83 | P a g e
{

  public static void main(String[] args)

    SoccerPlayersoccerPlayer = 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");

  }

// SoccerPlayer class inherits features from Player

class SoccerPlayer extends Player

84 | P a g e
  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)

    SoccerPlayersoccerPlayer = 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

85 | P a g e

You might also like