Q:

Java program to store the date in a single integer variable

belongs to collection: Java Basic Programs

0

Java program to store the date in a single integer variable

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

In this program, we will read ddmmyyyy variables from the user and store input date into a single integer variable using bitwise operators. Then we will also extract the date and store it into ddmmyyyy variables.

Program/Source Code:

The source code to store the date in a single integer variable is given below. The given program is compiled and executed successfully.

// Java program to store the date in a 
// single integer variable

import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    Scanner SC = new Scanner(System.in);

    int dd, mm, yy;
    int date;

    System.out.printf("Enter date (dd mm yyyy) format: ");
    dd = SC.nextInt();
    mm = SC.nextInt();
    yy = SC.nextInt();

    System.out.printf("\nEntered date is: %02d/%02d/%04d\n", dd, mm, yy);

    date = 0;

    //dd storing in byte 0
    date |= (dd & 0xff);

    //mm storing in byte 1
    date |= (mm & 0xff) << 8;

    //yy storing in byte 2 and 3
    date |= (yy & 0xffff) << 16;

    System.out.printf("Date in single variable: %d [Hex: %08X] \n", date, date);

    //Now extract date from an integer variable

    //dd from byte 0
    dd = (date & 0xff);

    //mm from byte 1
    mm = ((date >> 8) & 0xff);

    //yy from byte 2 and 3
    yy = ((date >> 16) & 0xffff);

    System.out.printf("Date after extracting: %02d/%02d/%04d\n", dd, mm, yy);
  }
}

Output:

Enter date (dd mm yyyy) format: 14 08 1988

Entered date is: 14/08/1988
Date in single variable: 130287630 [Hex: 07C4080E] 
Date after extracting: 14/08/1988

Explanation:

In the above program, we imported the "java.util.Scanner" package to read input from the user. And, created a public class Main. It contains a static method main().

The main() method is an entry point for the program. Here, we read the date (dd mm yyyy) from the user. Then we stored the input date into single variable using bitwise operators. After that, we also extracted the values for date's (dd mm yyyy) variables and printed the result.

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Java Basic Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Java program to store the time in a single integer... >>
<< Java program to check a given Email address is val...