Java: Variables: short

In this tutorial I will explain the short. 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 a short has to be created somewhere inside of a class.
The short is a smaller number in Java. It can be a number from -2^15 up to 2^15 -1. In normal numbers the highest value is 32,767. Just like with an int you can only use whole numbers like 2, 8 or 16. Numbers like 4,5 or 6,027492 can not be saved in a short.
The reason why people want to use a short instead of an int, which is able to save higher numbers, is that a short is faster. The short uses half the amount of bits which means that it can’t have as high numbers, but is faster. There are situations where you have a great number of variables. In those situations a short will make a pretty big performance difference from an int.
If you want to use a short in java you need to code it like this.


short number = 6;


The first part in this line is the type of variable. In this case an short.
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 short. Why that is and how you should use that is something for a later tutorial though.


package net.tutorial.src;

public class Tutorial 
{
static short 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="">