data-types-in-java

Data types in Java

There are majorly two types of languages.

  • Initial, one is Statically composed language where every factor and articulation type is now known at accumulate time. When a variable is announced to be of a specific data type, it can’t hold estimations of other data types.

Example: C, C++, Java.

  • The other is Dynamically composed languages. These dialects can get diverse data types after some time.

Example: Ruby, Python

Java is statically composed and furthermore a specifically language because, in Java, each kind of data, (for example, whole number, character, hexadecimal, pressed decimal, etc) is predefined as a feature of the programming language and all constants or factors characterized for a given program should be portrayed with one of the data types.

Data Types in Java

 

Java has two categories of data: 

  • Primitive Data Type: such as boolean, char, int, short, byte, long, float, and double
  • Non-Primitive Data Type or Object Data type: such as String, Array, etc.

Primitive Data Type

Primitive data are only single values and have no special capabilities.

There are 8 primitive data types:
1. boolean: boolean data type represents only one bit of information either true or false, but the size of the boolean data type is virtual machine-dependent. Values of type boolean are not converted implicitly or explicitly (with casts) to any other type. But the programmer can easily write conversion code.

  • Syntax:
boolean booleanVar;
  • Size:
virtual machine dependent
  • Values:
true, false
  • Default Value:
false

 

// Java program to demonstrate boolean data type
class GeeksforGeeks {
    public static void main(String args[])
    {
        boolean b = true;
        if (b == true)
            System.out.println("Hi Geek");
    }
}
Output:

Hi Geek

2. byte: The byte data type is an 8-bit signed two’s complement integer. The byte data type is useful for saving memory in large arrays.

  • Syntax:
byte byteVar;
  • Size:
1 byte ( 8 bits )
  • Values:
-128 to 127
  • Default Value:
0
// Java program to demonstrate byte data type in Java
class GeeksforGeeks {
    public static void main(String args[])
    {
        byte a = 126;
        // byte is 8 bit value
        System.out.println(a);
        a++;
        System.out.println(a);
        // It overflows here because
        // byte can hold values from -128 to 127
        a++;
        System.out.println(a);
        // Looping back within the range
        a++;
        System.out.println(a);
    }
}
Output:

126
127
-128
-127

3. short: The short data type is a 16-bit signed two’s complement integer. Similar to byte, use a short to save memory in large arrays, in situations where the memory savings actually matters.

  • Syntax:
short shortVar;
  • Size:
2 byte ( 16 bits )
  • Values:
-32, 768 to 32, 767 (inclusive)
  • Default Value:
0

4. int: It is a 32-bit signed two’s complement integer.

  • Syntax:
int intVar;
  • Size:
4 byte ( 32 bits )
  • Values:
-2, 147, 483, 648 to 2, 147, 483, 647 (inclusive)
  • Default Value:
0
  • Note: In Java SE 8 and later, we can use the int data type to represent an unsigned 32-bit integer, which has value in the range [0, 232-1]. Use the Integer class to use int data type as an unsigned integer.

5. long: The long data type is a 64-bit two’s complement integer.

  • Syntax:
long longVar;
  • Size:
8 byte ( 64 bits )
  • Values:
-9, 223, 372, 036, 854, 775, 808 
          to 
9, 223, 372, 036, 854, 775, 807
      (inclusive)
  • Default Value:
0
  • Note: In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. The Long class also contains methods like comparing Unsigned, divide Unsigned, etc to support arithmetic operations for unsigned long.

6. float: The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float (instead of double) if you need to save memory in large arrays of floating-point numbers.

  • Syntax:
float floatVar;
  • Size:
4 byte ( 32 bits )
  • Values:
upto 7 decimal digits
  • Default Value:
0.0

7. double: The double data type is a double-precision 64-bit IEEE 754 floating-point. For decimal values, this data type is generally the default choice.

  • Syntax:
double doubleVar;
  • Size:
8 byte ( 64 bits )
  • Values:
upto 16 decimal digits
  • Default Value:
0.0
  • Note: Both float and double data types were designed especially for scientific calculations, where approximation errors are acceptable. If accuracy is the most prior concern then, it is recommended not to use these data types and use BigDecimal class instead.
    Please see this for details: Rounding off errors in Java

8. char: The char data type is a single 16-bit Unicode character.

  • Syntax:
char charVar;
  • Size:
2 byte ( 16 bits )
  • Values:
'\u0000' (0) to '\uffff' (65535)
  • Default Value:
'\u0000'

Why is the size of char is 2 byte in java..? 

In different dialects like C/C++ utilizes just ASCII characters and to speak to all ASCII characters 8-pieces is sufficient,

However, java utilizes the Unicode framework not the ASCII code framework and to speak to Unicode framework 8 cycle isn’t sufficient to speak to all characters so java utilizes 2 bytes for characters.

Unicode defines a completely global character set that can speak to a large portion of the world’s composed dialects. It is a unification of many character sets, for example, Latin, Greeks, Cyrillic, Katakana, Arabic, and some more.

 

// Java program to demonstrate
// primitive data types in Java
class GeeksforGeeks {
    public static void main(String args[])
    {
        // declaring character
        char a = 'G';
        // Integer data type is generally
        // used for numeric values
        int i = 89;
        // use byte and short
        // if memory is a constraint
        byte b = 4;
        // this will give error as number is
        // larger than byte range
        // byte b1 = 7888888955;
        short s = 56;
        // this will give error as number is
        // larger than short range
        // short s1 = 87878787878;
        // by default fraction value
        // is double in java
        double d = 4.355453532;
        // for float use 'f' as suffix
        float f = 4.7333434f;
        System.out.println("char: " + a);
        System.out.println("integer: " + i);
        System.out.println("byte: " + b);
        System.out.println("short: " + s);
        System.out.println("float: " + f);
        System.out.println("double: " + d);
    }
}
Output:

char: G
integer: 89
byte: 4
short: 56
float: 4.7333436
double: 4.355453532


Non-Primitive Data Type or Reference Data Types

The Reference Data Types will contain a memory address of variable worth in light of the fact that the reference types won’t store the variable worth straightforwardly in memory. They are strings, objects, arrays, and so on

  • String: Strings are characterized as a variety of characters. The contrast between a character exhibit and a string in Java is, the string is intended to hold a succession of characters in a solitary variable while, a character cluster is an assortment of independent scorch type elements.
  • Dissimilar to C/C++, Java strings are not ended with an invalid character.The following is the essential linguistic structure for announcing a string in Java programming language.

Syntax:

<String_Type> <string_variable> = “<sequence_of_string>”;

  • Example:
// Declare String without using new operator 
String s = "GeeksforGeeks"; 

// Declare String using new operator 
String s1 = new String("GeeksforGeeks"); 


  • Class: A class is a client characterized outline or model from which articles are made. It speaks to the arrangement of properties or techniques that are normal to all objects of one sort. By and large, class assertions can incorporate these segments, all together:
  1. Modifiers: A class can be public or has default access (Refer this for subtleties).
  2. Class name: The name should start with an underlying letter (promoted by show).
  3. Superclass(if any): The name of the class’ parent (superclass), assuming any, went before by the catchphrase expands. A class can just broaden (subclass) one parent.
  4. Interfaces(if any): A comma-isolated rundown of interfaces executed by the class, assuming any, went before by the catchphrase actualizes. A class can execute more than one interface.
  5. Body: The class body surrounded by supports, { }.
  • Article: It is an essential unit of Object-Oriented Programming and speaks to the genuine elements. A common Java program makes numerous articles, which as you probably are aware, cooperate by summoning techniques. An item comprises of :
  1. State: It is spoken to by traits of an item. It additionally mirrors the properties of an item.
  2. Conduct: It is spoken to by strategies for an article. It likewise mirrors the reaction of an item with different articles.
  3. Character: It gives a novel name to an article and empowers one item to communicate with different articles.
  • Interface: Like a class, an interface can have strategies and factors, however the techniques proclaimed in an interface are of course dynamic (just strategy signature, no one).
  1. Interfaces indicate what a class should do and not how. It is the diagram of the class.
  2. An Interface is about abilities like a Player might be an interface and any class executing Player should have the option to (or should actualize) move(). So it indicates a bunch of techniques that the class needs to execute.
  3. On the off chance that a class actualizes an interface and doesn’t give technique bodies to all capacities indicated in the interface, at that point the class should be proclaimed dynamic.
  4. A Java library model is, Comparator Interface. On the off chance that a class executes this interface, at that point it very well may be utilized to sort an assortment.
  • Array: An cluster is a gathering of like-composed factors that are alluded to by a typical name. Exhibits in Java work uniquely in contrast to they do in C/C++. Coming up next are some significant focuses about Java clusters.
  1. In Java, all clusters are powerfully assigned. (examined underneath)
  2. Since exhibits are objects in Java, we can discover their length utilizing part length. This is not quite the same as C/C++ where we discover length utilizing size.
  3. A Java exhibit variable can likewise be pronounced like different factors with [] after the data type.
  4. The factors in the cluster are requested and each has a file starting from 0.
  5. Java exhibit can be likewise be utilized as a static field, a nearby factor or a strategy boundary.
  6. The size of an exhibit should be indicated by an int esteem and not long or short.
  7. The immediate superclass of an exhibit type is Object.
  8. Each exhibit type executes the interfaces Cloneable and java.io.Serializable.

 

Test on Data Type in Java

This article is contributed by Shubham Agrawal. In the event that you like GeeksforGeeks and might want to contribute, you can likewise compose an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article showing up on the GeeksforGeeks fundamental page and help different Geeks.

If you don’t mind compose remarks in the event that you discover anything off base, or you need to share more information about the point examined previously.

Consideration peruser! Try not to quit adapting now. Get hold of the relative multitude of important Java Foundation and Collections ideas with the Fundamentals of Java and Java Collections Course at an understudy amicable cost and become industry prepared.