Type Declaration
Parte da seção Fundamentos do Journey de Java da Coddy — lição 9 de 73.
Uma vez que uma variável é declarada com um certo tipo, ela só pode conter valores desse tipo. Por exemplo, uma variável int só pode conter valores inteiros, e uma variável String só pode conter texto.
Por exemplo:
int age = 25; // Can only hold whole numbers
String str = "abc"; // Can only hold textIsso causaria erros:
age = "defg"; // Error: can't put text in an int variable
str = 25; // Error: can't put a number in a String variableEstes são válidos:
age = 26; // OK: atribuindo um novo inteiro
str = "Jane"; // OK: atribuindo uma nova string de textoDesafio
InicianteDeclare as seguintes variáveis com seus tipos e valores correspondentes:
- Uma variável
intchamadacountcom o valor10. - Uma variável
doublechamadatotalcom o valor150.75. - Uma variável
charchamadagradecom o valor'A'. - Uma variável
booleanchamadaisActivecom o valorfalse. - Uma variável
StringchamadauserNamecom o valor"Bob123".
Após declarar essas variáveis, use System.out.println() para exibir os valores das variáveis no console no seguinte formato:
Count: [value of count]
Total: [value of total]
Grade: [value of grade]
Active: [value of isActive]
User Name: [value of userName]Folha de consulta
Em Java, as variáveis têm tipos específicos e só podem conter valores desse tipo:
int age = 25; // Só pode conter números inteiros
String str = "abc"; // Só pode conter textoIncompatibilidades de tipo causam erros:
age = "defg"; // Erro: não é possível colocar texto em uma variável int
str = 25; // Erro: não é possível colocar um número em uma variável StringReatribuições válidas devem corresponder ao tipo da variável:
age = 26; // OK: atribuindo um novo inteiro
str = "Jane"; // OK: atribuindo uma nova string de textoExperimente você mesmo
public class Main {
public static void main(String[] args) {
// Declare as variáveis aqui
// Exibe os valores
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);
}
}Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.
Todas as lições de Fundamentos
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