Loading
0x10Lesson 2 of 6

Name values and choose types

Store numbers, text, and true/false values in variables.

14 min 4-question quiz 1 code exercise
By the end of this lesson you can
  • 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.

Main.java
1int count = 3;
2double price = 2.5;
3String name = "Ada";
4boolean ready = true;
5System.out.println(name + ": " + (count * price));
Output
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.

Exercise 1

Double an integer

+25 XP

Read an integer with Scanner and print twice its value. Use nextInt() to read the input.

  • Input 4
  • Input -3
Main.java
Loading editor…

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…

Did you like the lesson? 😆👍
Consider a donation to support our work: