.
Steps
- 1Create a simple Java program. An example is provided called Hello.java :
public class Hello { public static void main(String[] args) { System.out.println("Hello World!");
- 2Scroll to a place where you want to insert the variable. Remember: If you place a variable in the main class, you can reference it anywhere. Choose the type of variable you need.
- Integer data types : Used to store integer values like 3, 4, -34 etc
- byte
- short
- int
- long
- Floating Point data type : Used to store numbers having fractional part like 3.479
- float
- double
- Character data type: Used to store characters like 's', 'r', 'g', 'f' etc
- char
- Boolean data types : Can store either of the two values: true and false
- boolean
- Reference data types : Used to store references to objects
- Array types
- Object types like String
- 3
- 4Understand how this works. It is basically "type name = value".
- 5Protect variables from being edited later, optionally, by adding "final type name" between the parentheses in the second line of your code (public static void main).
- final int someNumber = 35; Adding the 'final' here means that the variable 'someNumber' cannot be changed the variable from the user in Java?Try using a scanner. There are more detailed instructions in this article: Get Input from a User in Java.
Tips
- Each variable in a program must have a unique name or you'll bump into errors.
- In Java, all lines of instructions must end in ;
- Different variables can have the same name in certain circumstances. For example: A variable inside a method can have the same name as that of an instance variable.
Things You'll Need
- JDK. This task is so simple that any version is suitable.
- A text editor that can save the text in 'plain text' format.
- An IDE like NetBeans to make things easier.
Article Info
In other languages:
Español: crear una variable en Java, Русский: создать переменную в Java, Italiano: Creare una Variabile in Java, Português: Criar uma Variável em Java, Deutsch: In Java eine Variable erstellen
Thanks to all authors for creating a page that has been read 120,670 times.