Java Operators

Java Control Statements

Object Oriented Programming

Java Built-in Classes

Java File Handling

Java Error & Exceptions

Java Multithreading

Java Synchronization

Java Networking

Java Collections

Java Interfaces

Java Data Structures

Java Collections Algorithms

Advanced Java

Java Miscellaneous

Java APIs & Frameworks

Java Class References

Java Useful Resources

Java - short datatype



short datatype is one of the eight primitive datatype supported by Java. It provides means to create short type variables which can accept a short value. Following are the characteristics of a short data type.

  • Short data type is a 16-bit signed two's complement integer

  • Minimum value is -32,768 (-2^15)

  • Maximum value is 32,767 (inclusive) (2^15 -1)

  • Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an integer

  • Default value is 0.

  • Example: short s = 10000, short r = -20000

A short variables represents a reserved memory locations to store short values. This means that when you create a variable you reserve some space in the memory.

Based on the data type of a variable, the operating system allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to variables, you can store short values in short variables.

Example 1

Following example shows the usage of short primitive data type we've discussed above. We've created a short variable as shortValue and assigned it a short value. Then this variable is printed.

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      short shortValue = 2;
      System.out.println("short: " + shortValue);	  
   }
}

Output

short: 2

Example 2

Following example shows the usage of short primitive data type in an expression. We've created two short variables and assigned them short values. Then we're creating a new short variable shortResult to assign it the sum of short variables. Finally result is printed.

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      short shortValue1 = 2;
      short shortValue2 = 4;
      short shortResult = (short)(shortValue1 + shortValue2);

      System.out.println("short: " + shortResult);
   }
}

Output

short: 6

Example 3

Following example shows the usage of short variable with an invalid value. We've created a short variable as shortValue and assigned it an out of range value.

package com.tutorialspoint;

public class JavaTester {
   public static void main(String args[]) {
      short shortValue = 32770;
      System.out.println("short: " + shortValue);
   }
}

Output

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
	Type mismatch: cannot convert from int to short

	at com.tutorialspoint.JavaTester.main(JavaTester.java:5)
Advertisements