How to Create a Variable in Java

Variables are one of the most important concepts in computer programming. They store information such as letters, numbers, words, sentences, true/false, and more. This will give you an introduction into using variables in Java. It is not intended as a complete guide, but as a stepping stone into the world of the computer programmer.

[edit] Steps

  1. Create 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!");
}}

  1. Scroll 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.
  2. Choose the type of variable you need:
    • int -- Stores a whole number
    • double -- Stores a decimal
    • float -- Stores a floating point number
    • boolean -- Stores a true/false value
    • String -- Stores a collection of characters. Note that this type name starts with a capital letter
    • char -- Stores a single character
  3. Create the variable. Here are examples of how to create and assign a value to each type.
    • int someNumber = 0;
    • double someDouble = 635.29;
    • float someDecimal = 4.43f;
    • boolean trueFalse = true;
    • String someSentence = "My dog ate a toy";
    • char someChar = 'f';
  4. Understand how this works. It is basically "type name = value".
  5. Protect 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 later


[edit] Tips

  • In Java, all lines of instructions must end in ;
  • Each variable in a program must have a unique name or you'll bump into errors.


[edit] 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.
  • A computer


[edit] Related wikiHows


Embed this: Republish this entire article on your blog or website.

Was this article accurate? Yes No

Edit This Page E-mail this to a Friend Printable version
Discuss This Page Thank the Authors Write an Article
Categories:Programming

Authors

Happygoat, Rojo Don Poho, Choicefresh, Tom Viren, Lone wolf, Audriusa, Wolfrat
Thanks to all authors for creating a page that has been read 495 times.

Related wikiHows



Hide These Ads
Show Ads

Navigation

Editing Tools

My Pages