Write a program that does the following: Create seven variables, one for each of
ID: 3796499 • Letter: W
Question
Write a program that does the following: Create seven variables, one for each of the primitive number types in Java, and initialize each variable with any appropriate value. Print out the name of each variable and its value. Modify the value of each variable with an assignment statement and print out the names of the variables and their new values.
Next, create seven constants, one for each of the primitive number types in Java. Print the name of the constant and its value.
What happens if you try to assign a value to a constant? Write the answer in a comment at the end of your program.
Explanation / Answer
import java.lang.Math; // headers MUST be above the first class
public class IdentifierDemo
{
public static void main(String[] args)
{
boolean bln = true; // booleans can only be 'true' or 'false'
byte b = 20;
short s = 500;
char c = '%'; // must use single quotes to denote characters
int i = 1000000; // decimal notation
float f = 1.5f; // trailing 'f' distinguishes from double
long l = 2000000L; // trailing 'L' distinguishes from int
System.out.println("bln="+bln);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("i="+i);
System.out.println("f="+f);
System.out.println("s="+s);
System.out.println("l="+l);
bln = false; // booleans can only be 'true' or 'false'
b = 70;
s = 800;
c = 't'; // must use single quotes to denote characters
i = 23; // decimal notation
f = 3.0f; // trailing 'f' distinguishes from double
l = 5600000L; // trailing 'L' distinguishes from int
System.out.println();
System.out.println("bln="+bln);
System.out.println("b="+b);
System.out.println("c="+c);
System.out.println("i="+i);
System.out.println("f="+f);
System.out.println("bln="+bln);
System.out.println("l="+l);
final double pi = 3.141592653589793; // doubles are higher precision
final boolean bln1 = true; // booleans can only be 'true' or 'false'
final byte b1 = 20;
final short s1 = 500;
final char c1 = '%'; // must use single quotes to denote characters
final int i1 = 1000000; // decimal notation
final float f1 = 1.5f; // trailing 'f' distinguishes from double
final long l1 = 2000000L;
System.out.println("pi="+pi);
System.out.println("bln="+bln1);
System.out.println("b="+b1);
System.out.println("c="+c1);
System.out.println("i="+i1);
System.out.println("f="+f1);
System.out.println("s="+s1);
pi=2.12334; //suppose if we assign value to pi
}
}
/* if you try to assign a value to a variable then it will throw error:
"error: cannot assign a value to final variable pi
pi=2.12334;
^
1 error
*/
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.