Page 200 - CTS - CSA TP - Volume 2
P. 200

COMPUTER SOFTWARE APPLICATION - CITS




           Explanation:
           1  Package Declaration (package p2;): Specifies that the Sub class belongs to the p2 package.
           2  Import Statement (import java.util.Scanner;): Imports the Scanner class from the java.util package, which
              is used for reading user input.
           3  Class Definition (public class Sub { ... }): Defines the Sub class.
           4  Instance Variable (int d;): Declares an instance variable d to store the difference between two numbers.
           5  Method Definition (public void diff() { ... }): Defines a method named diff that calculates and displays the
              difference between two numbers.
           6  Scanner Initialization (Scanner scan = new Scanner(System.in);): Creates a Scanner object to read input
              from the console.
           7  User Input and Calculation (int x = scan.nextInt();, int y = scan.nextInt();, d = x - y;): Prompts the user to
              enter two numbers, reads the input, and calculates the difference.

           8  Output Display (System.out.println(“Difference = “ + d);): Displays the calculated difference.
           9  Resource Cleanup (scan.close();): Closes the Scanner object to release system resources.
           10 Main Method (public static void main(String[] args) { ... }): The entry point of the program. Creates an instance
              of the Sub class and calls the diff method for testing.

           Output:



















           This program demonstrates basic input/output operations and the use of the Scanner class to interact with the
           user.



           TASK 2: Example: Using a Package (Another Example)
           Step 1: Create a Package

           Create a folder named myPackage and save two Java files inside it.
           Step 2: Create Classes inside the Package
           1.  MyMath.java
           // Inside the ‘myPackage’ folder
           package myPackage;

           public class MyMath {
               public static int add(int a, int b) {
                   return a + b;
               }






                                                           185

                              CITS : IT & ITES - Computer Software Application - Exercise 115
   195   196   197   198   199   200   201   202   203   204   205