Programming Using Java Assignment Week 2


Programming Using Java

Week 2 Assignment


Programming Using Java Assignment Week 2

WEEK 2 ASSIGNMENT PROGRAMMING USING JAVA


1.A manufacturing company has classified its executives into four levels for the benefit of certain perks. The levels and corresponding perks are shown below.


Level

Perks

Conveyance Allowance

Entertainment Allowance

Manager

1000

500

Project Leader

750

200

Software Engineer

500

100

Consultant

250

-

 

Write a program that will read an executives job number, level number and basic pay and then compute the net salary.

Procedure:

Design a simple class called as “Employee” with the following variables

  • Level as String
  • Job_number as integer
  • Gross, Basic, House_rent, Perks, Net, Incometax as double
  • Initialize the allowance as CA1=1000, CA2=750, CA3=500, CA4=250, EA1=500, EA2=200, EA3=100, EA4=0


2. Get job number, Level and Basic pay from user (hint: use scanner class to get input from user)
3. Calculate the perks for different levels (hint: use switch case to select between levels)
4. Calculate gross, House_rent, Incometax and Net as per Specification given.
5. Display Level, Job_number, Gross pay, Tax and Net salary.

Specification:

  • HRA at 25% of basic pay
  • Perks = CA1+EA1 (for Manager) etc.
  • Gross salary = basic pay+ HRA + Perks
  • Net salary = Gross Salary – Income Tax

To calculate Income Tax use the following information


Gross Salary

Tax Rate

Gross <= 2000

No tax

2000 < Gross <= 4000

3%

4000 < Gross <= 5000

5%

Gross > 5000

8%


Input

 
import java.util.Scanner;

class Employee {
    String level;
    int jobNumber;
    double gross, basic, houseRent, perks, net, incomeTax;

    // Initialize the allowance values
    static final double CA1 = 1000, CA2 = 750, CA3 = 500, CA4 = 250;
    static final double EA1 = 500, EA2 = 200, EA3 = 100, EA4 = 0;

    // Calculate perks for different levels
    void calculatePerks() {
        switch (level) {
            case "Manager":
                perks = CA1 + EA1;
                break;
            case "Project Leader":
                perks = CA2 + EA2;
                break;
            case "Software Engineer":
                perks = CA3 + EA3;
                break;
            case "Consultant":
                perks = CA4 + EA4;
                break;
            default:
                System.out.println("Invalid level.");
                perks = 0;
                break;
        }
    }

    // Calculate gross salary, house rent, income tax, and net salary

    void calculateSalary() {
        gross = basic + 0.25 * basic + perks;
        houseRent = 0.25 * basic;
        if (gross <= 2000) {
            incomeTax = 0;
        } else if (gross <= 4000) {
            incomeTax = 0.03 * (gross - 2000);
        } else if (gross <= 5000) {
            incomeTax = 0.05 * (gross - 4000) + 0.03 * (4000 - 2000);
        } else {
            incomeTax = 0.08 * (gross - 5000) + 0.05 * (5000 - 4000) + 0.03 * (4000 - 2000);
        }
        net = gross - incomeTax;
    }

    // Display level, job number, gross pay, tax, and net salary

    void displaySalary() {
        System.out.println("Level: " + level);
        System.out.println("Job number: " + jobNumber);
        System.out.println("Gross pay: " + gross);
        System.out.println("Tax: " + incomeTax);
        System.out.println("Net salary: " + net);
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter job number: ");
        int jobNumber = scanner.nextInt();
        System.out.print("Enter level (Manager/Project Leader/Software Engineer/Consultant): ");

        String level = scanner.next();
        System.out.print("Enter basic pay: ");
        double basic = scanner.nextDouble();
        Employee emp = new Employee();
        emp.level = level;
        emp.jobNumber = jobNumber;
        emp.basic = basic;
        emp.calculatePerks();
        emp.calculateSalary();
        emp.displaySalary();
        scanner.close();
    }
}{codeBox}

 
Output

Enter job number: 123
Enter level (Manager/Project Leader/Software Engineer/Consultant): Manager
Enter basic pay: 5000
Level: Manager
Job number: 123
Gross pay: 7125.0
Tax: 370.0
Net salary: 6755.0{codeBox}

 
2.Think of an application which is capable of demonstrating the use of almost all data types. Do write a java program.

Input

public class DataTypesDemo {
    public static void main(String[] args) {
        // boolean
        boolean flag = true;
        System.out.println("flag = " + flag);

        // byte
        byte b = 127;
        System.out.println("b = " + b);

        // short
        short s = -32768;
        System.out.println("s = " + s);

        // int
        int i = 1234567890;
        System.out.println("i = " + i);

        // long
        long l = 9876543210L;
        System.out.println("l = " + l);

        // float
        float f = 3.14f;
        System.out.println("f = " + f);

        // double
        double d = 3.14159265359;
        System.out.println("d = " + d);

        // char
        char c = 'A';
        System.out.println("c = " + c);

        // String
        String str = "Hello, World!";
        System.out.println("str = " + str);

        // array
        int[] arr = {1, 2, 3, 4, 5};
        System.out.print("arr = ");

        for (int j : arr) {
            System.out.print(j + " ");
        }
        System.out.println();

        // null
        Object obj = null;
        System.out.println("obj = " + obj);
    }
}{codeBox}


Output

flag = true
b = 127
s = -32768
i = 1234567890
l = 9876543210
f = 3.14
d = 3.14159265359
c = A
str = Hello, World!
arr = 1 2 3 4 5
obj = null{codeBox}


Explanation

In this program, we have demonstrated the use of the following data types:

  • boolean: represents true/false values.
  • byte: represents 8-bit signed integers.
  • short: represents 16-bit signed integers.
  • int: represents 32-bit signed integers.
  • long: represents 64-bit signed integers.
  • float: represents single-precision floating-point numbers.
  • double: represents double-precision floating-point numbers.
  • char: represents a single Unicode character.
  • String: represents a sequence of characters.
  • array: represents a collection of values of the same data type.
  • null: represents a reference to no object.


3.Differentiate between implicit and explicit conversion.


Answer:

In programming, implicit and explicit conversions are used to convert values between different data types. The key difference between the two is that implicit conversion happens automatically by the compiler, whereas explicit conversion is done by the programmer explicitly in the code.

Here's a brief explanation of each:

Implicit Conversion:

Implicit conversion (also called coercion) occurs when the compiler automatically converts a value from one data type to another data type without requiring any explicit conversion code from the programmer. Implicit conversion is performed when the conversion is safe and does not result in loss of data. For example, assigning an int value to a double variable will result in implicit conversion as double can hold larger values than int.

Here's an example of implicit conversion:

int x = 10;
double y = x; // implicit conversion from int to double{codeBox}

In the above code, the integer value of 10 is automatically converted to a double value of 10.0 by the compiler.

Explicit Conversion:

Explicit conversion (also called casting) occurs when the programmer explicitly converts a value from one data type to another data type using type casting operator. Explicit conversion is performed when the conversion is not safe and might result in loss of data. For example, assigning a double value to an int variable will result in loss of decimal part of the value, so explicit conversion is required.

Here's an example of explicit conversion:

double d = 3.14;
int i = (int) d; // explicit conversion from double to int{codeBox}

In the above code, the double value of 3.14 is explicitly converted to an int value of 3 by the programmer. The (int) is the casting operator that tells the compiler to convert the double value to an integer value.

 

4.Declare and initialize the array variable using new keyword.


Answer:

In Java, you can declare and initialize an array variable using the new keyword in two different ways:

Declare and Initialize an Array in One Line:

// Declare and initialize an array of integers with 5 elements
int[] arr = new int[] { 1, 2, 3, 4, 5 };{codeBox}

In the above example, the new keyword is used to allocate memory for an array of integers with 5 elements. The curly braces {} are used to initialize the array with initial values.

Declare an Array First, Then Initialize:

// Declare an array of integers with 5 elements
int[] arr = new int[5];

// Initialize the array with values

arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;{codeBox}

In the above example, the new keyword is used to allocate memory for an array of integers with 5 elements. The array is declared first with the size of 5 elements. Then, each element is initialized with a separate statement.

Note that you can also use a loop to initialize the array with values:

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

This loop initializes each element of the array with consecutive integer values from 1 to 5.


5.What is the effect of converting an integer to byte? Justify.


Answer:

In Java, converting an integer to byte involves narrowing the data type, which means reducing the size of the data type. When an integer is converted to a byte, the least significant 8 bits of the integer value are retained, and the remaining bits are discarded.

For example, if we have an integer value of 255, which is represented in binary as 11111111, and we convert it to a byte, only the least significant 8 bits (11111111) will be retained, and the remaining bits will be lost. This will result in a byte value of -1, because in two's complement representation, the byte value 11111111 represents -1.

Here's an example:

int i = 255; // integer value
byte b = (byte) i; // convert integer to byte
System.out.println(b); // prints -1{codeBox}

The output of the above code is -1, because the integer value of 255 is converted to a byte value of -1, which is the expected result.

However, if the integer value is outside the range of byte (-128 to 127), then the value will be truncated to fit into a byte, and the result will be incorrect. For example, if we have an integer value of 300 and we convert it to a byte, the result will be incorrect because the value cannot be represented as a byte. In this case, the value will be truncated to fit into a byte, and the result will be different from the original value.

Here's an example:

int i = 300; // integer value
byte b = (byte) i; // convert integer to byte
System.out.println(b); // prints 44 (incorrect result){codeBox}

In the above example, the integer value of 300 is converted to a byte value of 44, which is an incorrect result because the value cannot be represented as a byte.

Therefore, when converting an integer to byte, it is important to ensure that the integer value is within the range of byte to avoid incorrect results.


6.How negative numbers are represented in Java? Justify with an example


Answer:

In Java, negative numbers are represented using the two's complement notation. In this notation, the most significant bit of a signed data type, such as byte, short, int, or long, is used to represent the sign of the number. If the most significant bit is 0, the number is positive, and if it is 1, the number is negative.

To represent a negative number using the two's complement notation, we first invert all the bits of the positive number and then add 1 to the result. For example, to represent the number -5 as a 4-bit signed integer using two's complement notation, we follow these steps:

Represent the absolute value of the number in binary form. In this case, the absolute value of -5 is 5, which is represented as 0101 in binary.

Invert all the bits of the binary representation. In this case, inverting all the bits of 0101 gives 1010.

Add 1 to the result. In this case, adding 1 to 1010 gives 1011.

Therefore, the binary representation of -5 as a 4-bit signed integer using two's complement notation is 1011.

Here's an example of how negative numbers are represented in Java:

byte b = -5; // assign the value -5 to a byte variable
System.out.println(b); // prints -5{codeBox}

In the above example, we assign the value -5 to a byte variable named b. When we print the value of b, it correctly prints -5. This is because Java uses two's complement notation to represent negative numbers, and the byte data type has a range of -128 to 127, which includes -5.

In summary, Java represents negative numbers using the two's complement notation, which allows negative numbers to be represented using the same binary operations as positive numbers. The most significant bit of a signed data type is used to represent the sign of the number, with 0 indicating a positive number and 1 indicating a negative number.


Post a Comment