Java Variable Types

Now that you know how to code a simple program, its time to start declaring types of variables.

There are 5 commonly used types of Variables in Java.

int – This stores a whole number Integer value

double – this stores a decimal number

boolean – this stores a true/false statement

char – stores a character value

String – stores a string

All of these values can be declared and initialized with actual values.

Declaring a variable is just telling Java to save a space for a value and to call it by a certain name.

Initializing a variable is assigning a value to a variable.

To declare a variable, you have to say the type of variable that it is, and then the name (again with no spaces).

For example:

int x;

double y;

boolean guilty;

String animal;

//End

The to initialize a variable, you need to have the assignment operator ( a.k.a. ‘=’) and then a value that matches that data type.

For example:

int x = 3;

//or

int x;

x = 3;

//End 

They both do the same thing, just in different context. If you assign a variable with a type that is not compatible, and error will occur.

For Example:

int x = gorilla;

//End

Obviously a gorilla is not an integer. So it will give you an error message!

A way to test this out is to open up your first program, then change one little part.

/*

*..Your heading..

*/

public class HelloWorld

{

public static void main (String [] args)

{

String hello = “Hello”;

String world = “World”;

char exclamationPoint = ‘!’;

System.out.println(hello + world + exclamationPoint);

}

}

//End

This would produce the same thing as the other program, but it is just the one string broken up into three separate variables. You can try this with other things to display, such as numbers. I will talk about operators and simple math in my next article, and then how to make your own simple text-based calculator!

comments powered by Disqus
Loading