Name values and choose types
Store numbers, text, and true/false values in variables.
- Declare variables using Java’s common primitive and reference types.
Java is statically typed: a variable declaration includes its type. Common primitive types include int for whole numbers, double for decimals, and boolean for true/false values. String is a class used for text. A variable can be reassigned to another value of a compatible type.
1int count = 3;
2double price = 2.5;
3String name = "Ada";
4boolean ready = true;
5System.out.println(name + ": " + (count * price));Ada: 7.5
A type helps Java check how a value is used. Converting from a wider numeric type to a narrower one may lose information and sometimes requires an explicit cast. String values are objects, while int, double, and boolean are primitives.
Key takeaways
Declare variables using Java’s common primitive and reference types.
Java checks types as it compiles your source.
Use compiler messages as clues about what needs fixing.
Lesson quiz
4 questions · pass with 3 correct · up to 50 XP
Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.
Practice: write Java
Write Java in the editor and run it against sample input with a remote compiler. Your code is sent to Compiler Explorer to compile and run.
Double an integer
Read an integer with Scanner and print twice its value. Use nextInt() to read the input.
- Input 4
- Input -3
Java is compiled and run by Compiler Explorer (godbolt.org), a free public service. Your source code and test input are sent to that service.
Questions about this lesson
Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.
Loading posts…