Type Declaration
Part of the Fundamentals section of Coddy's Java journey — lesson 9 of 73.
Once a variable is declared with a certain type, it can only hold values of that type. For instance, an int variable can only hold integer values, and a String variable can only hold text.
For example:
int age = 25; // Can only hold whole numbers
String str = "abc"; // Can only hold textThese would cause errors:
age = "defg"; // Error: can't put text in an int variable
str = 25; // Error: can't put a number in a String variableThese are valid:
age = 26; // OK: assigning a new integer
str = "Jane"; // OK: assigning a new text stringChallenge
BeginnerDeclare the following variables with their corresponding types and values:
- An
intvariable namedcountwith the value10. - A
doublevariable namedtotalwith the value150.75. - A
charvariable namedgradewith the value'A'. - A
booleanvariable namedisActivewith the valuefalse. - A
Stringvariable nameduserNamewith the value"Bob123".
After declaring these variables, use System.out.println() to output the values of the variables to the console in the following format:
Count: [value of count]
Total: [value of total]
Grade: [value of grade]
Active: [value of isActive]
User Name: [value of userName]Cheat sheet
In Java, variables have specific types and can only hold values of that type:
int age = 25; // Can only hold whole numbers
String str = "abc"; // Can only hold textType mismatches cause errors:
age = "defg"; // Error: can't put text in an int variable
str = 25; // Error: can't put a number in a String variableValid reassignments must match the variable's type:
age = 26; // OK: assigning a new integer
str = "Jane"; // OK: assigning a new text stringTry it yourself
public class Main {
public static void main(String[] args) {
// Declare variables here
// Output the values
System.out.println("Count: " + count);
System.out.println("Total: " + total);
System.out.println("Grade: " + grade);
System.out.println("Active: " + isActive);
System.out.println("User Name: " + userName);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Fundamentals
4Operators Part 1
Arithmetic OperatorsModulo OperatorIncrement/DecrementPost Increment/DecrementArithmetic ShortcutsComparison OperatorsString Comparison5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Logical Operators Part 43Variables Part 2
ConstantsNaming ConventionsRecap - Initialize VariablesType Casting Part 1Type Casting Part 26Decision Making
If StatementIf - ElseSwitch StatementTernary OperatorRecap - If ElseNested If - Else