Introduction
This article will explain what variables are and how you can declare and use them. It is part of the Programming Basics series, so be sure to read the previous ones, if you haven’t done so already. You can find the table of contents at the end of this article.
Solution to the last exercise
At the end of the last part I gave you an assignment:
So try to write your own method that takes a text as parameter and prints this text. Then call your custom method in the main method, instead of calling the println-method directly! The solution to this exercise will be presented in the next part of the series.
Here is the solution to this exercise:
public class MyFirstClass { private static String yourName = "nerdhut"; private static void printString(String s) { System.out.println(s); }
public static void main(String[] args) { printString("Hello " + yourName); } }
Access modifiers
We have used several access modifiers already, even though you might not know what they are. Take a look at the solution of the homework. Each method and the variable has a keyword at the very beginning of the respective line (e.g. private, public). This is the access modifier.
As the name states, access modifiers determine what parts of a program have access to a field or method. The following table shows you, what classes can use a resource that is marked with a specific modifier:
Modifier | Package | Subclass | Any class |
public | Y | Y | Y |
protected | Y | Y | N |
no modifier (default modifier) |
Y | N | N |
private | N | N | N |
Please note that obviously a field or method is always visible to the class that declares it, that’s why there is no extra column in the table for the class, the field/method is in.
An example: If a field is marked as protected, any class, that is in the same package or is a subclass of the one, the field is declared in, can access the field. All other classes can’t see the field.
You’ll see how useful access modifiers are, when we get to classes and objects. For now just remember that there are different ones and that they limit the access to a field or method from outside the class they are declared in.
Variables
The sections in this article will focus on the so called primitive data types, we’ll discuss objects in a separate article.
Each variable needs to be declared and initialized in order to use it. A variable declaration consists of the following elements (in this order):
- access modifier
We discussed this one above. - type
Because Java is a statically-typed language, you’ll have to define what type of variable you want to declare. The type determines how much memory the variable will occupy and the values you can save in the variable. There are primitive and object types, the primitive types are described below. - name
Fields need a unique name. Names can be any alphanumeric character, currency symbols, underscore and dash. - value
Variables need to be initialized. This can be done in an extra step, but I tend to initialize the variable in one line with the declaration.
Let’s look at some examples:
private int yourAge = 30;
public boolean flag = true;
char sex = 'm'; //Has the default access modifier
Primitive datatypes
You have already seen some primitive datatypes in the example above. Here comes a complete list with the available primitive types in Java, their sizes and what values you can save in them:
- byte
It has a length of 8 bits and can hold values from -128 to 127. You can use bytes to save memory space if you have a lot of variables. - short
This 16 bit long variable can hold values from -32,768 to -32,767. - int
This is one of the most used datatypes. It has a length of 32 bits and stores whole numbers. - long
The same as an integer, but with two times the memory space of an int. - float
Single precision 32 bit floating point number. - double
Double precision 64 bit floating point number.
- boolean
One bit that stores true or false. - char
Can store a single 16 bit unicode character. Characters are declared with single quotes.// Example char char c = 'c';
Besides these datatypes there is the string, which basically is not a primitive. However the way they are handled in Java make them feel like they are. Strings are instantiated in a different way to other objects, you can initialize them with double quotes:
// Example String String s = "nerhut.de";
Variables might be marked as final (constant) variables. This means that you have to assign a value immediately and you can not change it later. This is useful for defining constant values that will never change, like Pi:
public final float pi = 3.1416f;
However, Java also has some constants already built in:
Math.PI;
Casting
Casting is the process of changing a primitive variable’s type into a different one. For example: You have a byte variable and want to save it’s value into a float.
There are two types of casting: implicit and explicit casting. Implicit casting happens automatically, without you having to do anything. This only works, when a smaller type is converted to a larger one:
// i is an integer and therefore 32 bits large int i = 123; // d is a double and has a size of 64 bits
// as its larger than an integer, you can assign // i's value to it without any casting. double d = i; // Will print out 123.0 System.out.println(d);
Explicit casting is a bit different. You have to explicitly tell the compiler that you want to cast a larger datatype into a smaller one. Keep in mind that this type of casting can cause a loss of data (or precision). For example: If you cast a float into an integer, everything behind the comma will get lost. The following example demonstrates explicit casting:
// Larger double
double d = 123.45678;
// Casted into a smaller integer
int i = (int)d;
// Will print out 123
// Data is lost due to the conversion
System.out.println(i);
Basically you can always do an explicit casting, even if it is not needed. The syntax is:
newdatatype name = (newdatatype)oldvalue;
There are some special cases and I want to show you the most common one:
By typing a floating point number (like 123.45678), Java assumes that you have typed in a double. If you want to declare a float-type field, you’ll get a compiler error (because of data-loss):
// Will throw a compiler error
float f = 123.45678;
So you have to cast the floating point number (because it is assumed to be a double) to a float:
float f = (float)123.45678;
There is a short version, so you don’t have to write the long one over and over again:
float f = 123.45678f;
That f behind the number indicates, that you want the number you typed in, to be a float. You can read about the other special cases in the official documentation.
Casting a string to a numeric datatype
Well this is another special case. As you already know, a string is not a real primitive datatype. It is an object, and therefore it’s text value cannot be casted into a number by simply doing the following:
String s = "123";
// Won't work!
int i = (int)s;
Luckily, there are built-in functions that come with java, which allow you to convert a string into numerical formats:
String s = "123";
int i = Integer.parseInt(s);
double d = Double.parseDouble(s);
float f = Float.parseFloat(f);
...
User input
Okay so now that you know what variables and casting are, let’s add some interaction to our first program we wrote! We want the user to input a name to display on the screen. How can we do that?
// Create a new scanner object // Don't worry, we'll learn about objects later Scanner reader = new Scanner(System.in); // Inform the user about what he has to do System.out.println("Enter your name: "); // The code will halt here until the user made // an input and pressed enter. Afterwards the // input is saved in the username variable String username = reader.nextLine();
The code above will ask a user for his name in the command window (or in our case: the console of our IDE). The user can input anything and press enter, the reader will then read one complete line and save it into the username string.
If you want a numeric input, you can either convert a string input, made by the user, or you can use a special method, provided by the scanner class, that looks for numbers in the input, made by the user:
Scanner reader = new Scanner(System.in); System.out.println("Enter your age: "); int age = reader.nextInt(); System.out.println("Enter your size: "); float size = reader.nextFloat();
You can read more about the scanner’s methods in the API!
I want to show you one more way to read a user’s input. The example above used the command line to read the input. You can also create a GUI window to read the user’s input if you want to make your program look nicer. However you have to import more classes, which might be an overhead for inputs only. We’ll learn more about GUIs later.
String input = javax.swing.JOptionPane.showInputDialog(null, "Enter your name:");
This will produce the following window:

Exercise
Now play around with the inputs and create a simple calculator! Make the user input two floating point numbers after each other, add them together, cast the result to an integer and print out the result!
Have fun!
Table of contents
Part 1 – MyFirstProgram
Part 2 – Access Modifiers and Variables (You are here)
Part 3 – Methods
Part 4 – Arrays
Part 5 – Control flow
Part 6 – Classes and Objects
Part 7 – Exceptions and exception handling
Addendum 1 – IntelliJ QuickTip
Addendum 2 – Important programming concepts explained
Hi! I wanted to learn programming for a time and I like watching videos on youtube about this. But your articles summarize them perfectly and I love to use them as a reference. I subscribed your page. Thanks!
LikeLiked by 2 people
You are welcome Leonie! I’m glad you liked the articles.
LikeLiked by 1 person