Java: Variables: int

In this tutorial I will explain the int. To do that I will use this file.


package net.tutorial.src;

public class Tutorial 
{
public static void main(String[] args)
{
System.out.println(“Hello World!”);
}
}


Like all other variables an int has to be created somewhere inside of a class.
An int is a number ranging from -2^31 up to 2^31 – 1. The second number can be rewritten as 2147483647. So almost every normal number you will use can be put into an int. There is one big restriction to the int. It can only be a whole number like 2, 8 or 16. Numbers like 4,5 or 6,027492 can not be saved in an int. If you want to have numbers like that you will have to use another variable.
An int is also the most commenly used variable when someone wants to use a number in java.
If you want to use an int in java you need to code it like this.


int number = 6;


The first part in this line is the type of variable. In this case an int.
The second part in this line of code is the name of the variable. In this case number.
The last part of this line of code is the thing number will be. In this case number will be 6.
If you want to print out a number in the console you have to use a line of code like this.


System.out.println(number);


Because this bit of the code is in the main method and the main method is static you have to add the word static in front of int. Why that is and how you should use that is something for a later tutorial though.


package net.tutorial.src;

public class Tutorial 
{
static int number = 6;

public static void main(String[] args)
{
System.out.println(number);
}
}


 

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">