1byte = 8bits=2^8=256 place but start from0 till 255. Type Description Size byte stores an integer value between -128 and 127 1 byte short uses 16 bits to store an integer 2 bytes int uses 32 bits to store an integer 4 bytes long uses 64 bits to store an integer 8 bytes float stores a floating-point (decimal) value 4 bytes double stores a floating point value with double the precision of a float 8 bytes char stores a unicode character value 2 bytes boolean stores a value either true or false 1 byte
Data types are used to define the type of variable and constants stored. The following program declares a variable number which is a byte, then assigns the value 100 in it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 /* a Program to demonstrate variable declaration and * usage */ public class TestVariables {
public static void main(String[] args) {
byte number; number = 100;
System.out.println("number = " + number); }
}
Task 1: Run the program above and check what is displayed.-----number=100 Task 2: What happens if you assign a value of 500 instead of 100 in line 9? Copy the error message that appears here: cannot convert from int to byte
Task 3: In line 8, declare number as a short instead. What are the maximum and minimum values that can be stored in a short variable? Write your answer here: -32768 to 32767 (Hint: a short uses 2 bytes) Task 4: Practice declaring number as int or long. Task 5: You can declare and initialize a variable in one statement. For example, replace lines 8 and 9 in a single statement: int number = 500; Task 6: Is it possible to assign a value of 500.0 to number? Why/why not? Copy any error message that appears here: cannot convert from double to int Task 7: Can we try to declare number as a float then? Why/why not? Copy any error message that appears here: Task 8: The literal value 500.0 is automatically defined as a double. In order to store as a float, use the suffix F or f float number = 500.0F;
Task 9: Similarly, integer values are automatically stored as int (using 4 bytes of memory). In order to store as a long, use the suffix L or l (but we usually use the capital letter for easier readability) long number = 500L;
Task 10: We will usually store floating point numbers as double and integer values as int. Now modify the program to declare a double variable dnum and an integer variable inum. Assign the value of 150.4 to dnum and the value of 5 to inum. Task 11: Add these two lines to your program. Which is legal? Why? dnum = inum; inum = dnum;
Continue to answer the questions in Tutorial 1a and 1b. Write java statements to help you answer the questions.