AP Notes, Outlines, Study Guides, Vocabulary, Practice Exams and more!

Java Lesson 3 – Variables

Jul 18, 2009

Java Lesson 3 – Variables

Welcome to the third Java lesson in the series. This time I want to introduce the idea of variables. Variables are a universal concept in all programming languages. The basic idea of a variable is a way for your program to remember information for later use. A good way to think about it is that it is a lot like coming across a dollar on the floor, then saving it in some kind of jar. At any time, you can look in that jar to see how much money you have.

There are different kinds of variables. In Java, before you make a variable you need to specify the kind of information you are saving. Here is a table with the different data types.
Java Data Types
Name Use Example
int Holds integers; whole positive and negative numbers. 1, 129, -50, -1000
double Holds real numbers with decimal values. 5.3, -10.2, 204.6
float Holds small ints or doubles, but must include some form of decimal. 10.00, -3.00, 1.10, -33.04
char Holds a single character surrounded in single quotes. ‘A’, ‘c’, ‘w’, ‘X’
String Holds words, phrases, and sentences in double quotes. “Hello World!”, “3, 2, 1 GO”, “Yeehaw”

Example
Here’s an example program to demonstrate.
public class VariableExample
{
public static void main(String[] args)
{
int score = 1;
double change = 10.2;
float speed = -1.00;
char middleInitial = ‘A’;
String message = “Variables rule!”;

System.out.println(s);
}
}
When we declare variables, we first specify the variable type, then the reference name we want to call it. You don’t need to specify the variables contents when you declare it, but to set a variable to something, use an equals sign. Notice how in the System.out.println() I used s instead of a raw string.

Need Help?

We hope your visit has been a productive one. If you're having any problems, or would like to give some feedback, we'd love to hear from you.

For general help, questions, and suggestions, try our dedicated support forums.

If you need to contact the Course-Notes.Org web experience team, please use our contact form.

Need Notes?

While we strive to provide the most comprehensive notes for as many high school textbooks as possible, there are certainly going to be some that we miss. Drop us a note and let us know which textbooks you need. Be sure to include which edition of the textbook you are using! If we see enough demand, we'll do whatever we can to get those notes up on the site for you!