Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Data types in java
Logicmojo - Updated Jan 15, 2023

A Data type is a way to data set together. It communicates the programmer's intended use of the variables or procedure to the compiler or interpreter. All computer programming languages depend heavily on data types. To create a flawless and functional program, a programmer must ensure that data types are assigned correctly while creating computer software. The type, nature, and set of operations for the value that a data type stores are represented by that value.

Let us also address the fact that there are primarily two types of languages, which are as follows:

🚀 The first is a statically typed language, in which each variable and expression type is known at compile time.
When a variable is defined to be of a specific data type, it cannot include values of other data types. For instance, C, C++, and Java.
🚀 Dynamically typed languages are the second option. These languages may acquire a variety of data formats throughout time. For instance, Ruby and Python.

Learn More

Data Types in Java

Overveiw

Java is a statically typed and strongly typed programming language because each type of data (such as integer, character, hexadecimal, packed decimal, and so on) is specified as part of the programming language and all constants or variables defined for a given program must be represented with one of the data types.
Primitive and Non-Primitive are the two classifications of data types that exist in Java.


Data Types in Java

In Java, data types define how variables' values are kept in memory. Each variable has a data type that determines the type of value it will store. Primitive Data Types are also applied to define the return type of functions.
Data types in Java are divided into two groups.
🚀 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.


Data Types in Java


Primitive Data Types

Primitive data types are the building blocks of data manipulation in the Java programming language. There are 8 types of primitive data types:

 Primitive Data Types in Java

1. boolean type

A boolean data type can only store True or False values. They can be used to determine whether two values are equal (basically in conditional statements to return True or False).
It is most commonly used as a flag variable to identify true or false conditions.
False is the default boolean value. Furthermore, the size of the boolean type is determined by the Java Virtual Machine. Therefore, it fluctuates on different platforms.

🚀 Syntax : boolean booleanVar;
🚀 Size : Virtual machine dependent

Example of Abstraction :

public class Main {
  public static void main(String[] args) {
    boolean EightPrimitiveDataTypes = true;
    boolean TwoPrimitiveDataTypes = false;    
    System.out.println(EightPrimitiveDataTypes);
    System.out.println(TwoPrimitiveDataTypes);
  }
}


2. byte type

The smallest data type between all integer data types is the byte (8-bit signed two’s complement integer) It can store full numbers from -128 to 127.
Data Types in Java
🚀 Syntax : byte byteVar;
🚀 Default Value : 0

Example

public class Main {
  public static void main(String[] args) {
    byte count = 115;
    System.out.println(count);
  }
}


3. short type

The short data type (16-bit signed two’s complement integer) can store whole numbers from -32768 to 32767.
🚀 Syntax : short shortVar;
🚀 Default Value : 0


Example :

public class Main {
  public static void main(String[] args) {
    short count = 6512;
    System.out.println(count);
  }
}

4. int type

The int data type (32-bit signed two’s complement integer) can store whole numbers from -2147483648 (-2^31) to 2147483647 (2^31 -1)
🚀 Syntax : int intVar;
🚀 Default Value : 0

Example :

public class Main {
  public static void main(String[] args) {
    short count = 1800000;
    System.out.println(count);
  }
}

5. long type

The longest data type among all integer data types is the long (64-bit two’s complement integer). The long data type can store values from -9223372036854775808 (-2^63) to 9223372036854775807 (2^63 -1).
This is used when int datatype is insufficient to store the value. Keep in mind that the value should finish with a "L or l".
🚀 Syntax : long longVar;
🚀 Default Value : 0L

Example :

public class Main {
  public static void main(String[] args) {
    long count = 18000000L;
    System.out.println(count);
  }
}

6. float type

It is a form of floating-point data that stores values with decimal precision. It isn't used for precise data like currencies or analysis.
A Float value is a single-precision 32-bit or 4 bytes IEEE 754 floating-point and have a 7-digit decimal precision. Keep in mind that the value should finish with a "F or f."
🚀 Syntax : float floatVar;
🚀 Default Value : 0.0(0.0f)

Example :

public class Main {
  public static void main(String[] args) {
    float count =  -9.99f;
    System.out.println(count);
  }
}


7. double type

The double data type resembles the float data type. The difference between the two is that in the case of decimal precision, it double twice the float. It, like float, is used for decimal values and should not be utilised for precise quantities.
A double value is a double-precision 64-bit or 8 bytes IEEE 754 floating-point and upto 16-digit decimal precision.
🚀 Syntax : double doubleVar;
🚀 Default Value : 0.0 (0.0d)

Example :

public class Main {
  public static void main(String[] args) {
    double count =   -92.45;
    System.out.println(count);
  }
}



8. char type

The char data type is a single 16-bit Unicode character and is used to store a single character.It stores both lower case and upper case characters which must be enclosed in single quotes.
Its value range is from '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).
🚀 Syntax : char charVar;
🚀 Default Value : '\u0000'

Example :

public class Main {
  public static void main(String[] args) {
    char ClassSection =   'C';
    System.out.println(count);
  }
}


You're simply thinking why the size of char in Java is 2 bytes?
So, in other languages, such as C/C++, just ASCII characters are used, and 8-bits are sufficient to represent all ASCII letters. However, java uses the Unicode system rather than the ASCII coding system, and because 8 bits are insufficient to represent all characters in the Unicode system, java uses 2 bytes for characters.
Unicode defines a truly worldwide character set capable of representing the vast majority of the world's written languages. It is a synthesis of dozens of letter sets, including Latin, Greek, Cyrillic, Katakana, Arabic, and many others.

Non-Primitive or Reference Data Types in Java

Non-primitive data types are called reference types because they refer to objects.
They are unable to immediately store the value of a variable in memory. They save the variable's memory address.
Non-primitive data types, as opposed to primitive data types, are user-defined.
They are generated by programmers and can be set to null. All non-primitive data types are of similar size.



1: Strings

Strings are defined as an array of characters. In Java, the distinction between a character array and a string is that a string is intended to retain a sequence of characters in a single variable, but a character array is a collection of individual char type entities.
In contrast to C/C++, Java strings do not end with a null character. String literals are enclosed in double-quotes.  Primitive Data Types in Java
🚀 Syntax : (String_Type) (string_variable) = “(sequence_of_string)”;


Example :

public class Main {
  public static void main(String[] args) {
    string S = 'DataTypesOfJava';
    System.out.println(S);
  }
}


2. Array

An array is a collection of variables with similar types that share a name. Arrays in Java act differently than arrays in C/C++.
The following are some significant points about Java arrays.
🚀All arrays in Java are allocated dynamically.
🚀Because arrays are objects in Java, we can use member length to determine their length. This is different from C/C++ where we find length using size.
🚀A Java array variable can be declared similarly to other variables by adding [] after the data type.
🚀The variables in the array are ordered and each has an index beginning from 0.
🚀A static field, a local variable, or a method parameter can all be utilised with a Java array.
🚀The length of an array must be provided by an int number and not long or short.
🚀The immediate superclass of an array type is Object.

 Primitive Data Types in Java

🚀 Syntax : dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

Example :

public class Main {
  public static void main(String[] args) {
    int[] count = {5, 10, 15, 20};
    System.out.println(count[1]);
  }
}



3: Class

A class is a data type that is defined by the user and from which objects are formed. Class are similar to object constructors in that they allow you to create objects. A group of objects is referred to as a class. Logic quantities are said to be classes. Classes do not take up any memory space. A class is sometimes known as an object's template. Fields, methods, and constructors are examples of class members. Both static and instance initializers exist in a class.


 Primitive Data Types in Java
A class declaration consists of the following elements:

🚀 Modifiers : Public or default access options are available.
🚀 Class Name : Initial letter of the class name.
🚀 Superclass : A class can only extend (subclass) one parent (superclass).
🚀 Interface : Multiple interfaces can be implemented by a single class.
🚀 Body: Braces encircle the entire body.
To construct a class, use the class keyword. The following is a simplified generic form of the class definition:

class classname {
type instance variable 1;
type instance variable 2;
.
.
.
type instance variable n;

type methodname 1 (parameter list) {
// body od method 
}

type methodname 2 (parameter list) {
// body od method 
}

type methodnamen (parameter list) {
// body od method 
}

Instance variables are variables or data that are defined within a class. The methods are always full of code. As a result, members of a class refer to the methods and variables declared within it. These methods are not defined as static or public, and they all have the same form as main().

4. Object

An object is any entity that has state and behaviour. For instance, a chair, pen, table, keyboard, bicycle, and so forth. It could be physical or conceptual in nature.
An instance of a class can be defined as an Object. An object holds an address and occupies memory space. Objects can communicate even if they are unaware of one other's data or code. The only thing that matters is the type of message that is accepted and the type of response that the objects provide.

 Primitive Data Types in Java

A dog, for example, is an object since it has states such as colour, name, breed, and activities such as waving the tail, barking, and eating.
A typical Java application creates a large number of objects, which interact via invoking methods. An object is made up of the following elements:

    🚀 State : The state of an item is represented by its characteristics. It also reflects an object's attributes.
    🚀 Behaviour : The behaviour of an object is represented by its methods. It also reflects an object's interaction with other objects.
    🚀 Identity : It gives a thing a unique name and allows it to communicate with other objects.

Assume we've constructed a class called Car, and we've used the term new to indicate the class name followed by the object name.
Example 1 :

Public class Car {
    int y=100;
    Public static void main (String args []) {
    Car Carobj= new Car ();
    System.out.println(CarObj.y);
  }
}

A new object is created in the above example, and it returns the value of y, which may be the number of cars.

Car Carobj= new Car ();

This is the statement that is used to make objects.
We can also construct numerous objects in the same class and access objects created in one class from another. This strategy is utilised for better class organisation, and it is important to note that the java file name and the class name are the same.


5. Interfaces

An interface can have variables and methods, much like a class, but by default, the methods declared in an interface are abstract (only method signature, no body).
Interfaces define what a class must perform rather than how it must do it. It is the blueprint of the class.
a lot of the time in the world (). As a result, it provides a set of methods that the class must implement.
If a class implements an interface but does not include method bodies for all of the interface's functions, the class must be designated abstract.




 Primitive Data Types in Java

// interface
interface Bird {
  public void BirdVoice(); // interface method (does not have a body)
  public void look(); // interface method (does not have a body)
}

6. enum

An enum is a type of "class" that represents a collection of constants (unchangeable variables, like final variables).
Use the enum keyword (rather than class or interface) to build an enum, then separate the constants with a comma. It should be noted that they should be written in capital letters.




 Primitive Data Types in Java

Example :

enum Level {
  LOW,
  MEDIUM,
  HIGH
}

public class Main { 
  public static void main(String[] args) { 
    Level var = Level.HIGH; 
    System.out.println(var); 
  } 
}
 


Difference between Primitive and Non-Primitive Data Types

The main difference between primitive and non-primitive data types are:
🚀 In Java, primitive types are predefined (predefined). Non-primitive types are specified by the programmer rather than by Java (except for String).
🚀 Non-primitive types can invoke methods that execute specific actions, whereas primitive types cannot.
🚀 Non-primitive types can be null, whereas primitive types always have a value.
🚀 Non-primitive types begin with an uppercase letter, whereas primitive types begin with a lowercase letter.
🚀 A primitive type's size is determined by the data type, whereas non-primitive types all have the same size.



🚀Conclusion

We have now reached the end of this page. Data types serve as the foundation for computer languages. Before going on to deeper Java ideas, it is critical to understand Java data types. A solid understanding of data types will aid you in the development of any application or software and it's in fact recommended to hone your programming skills with small practice.
There is no way to cover all the information you need to be a successful programmer in one course. In fact, programming is a constant learning process, regardless of whether you are a seasoned professional developer or a newbie.


Good luck and happy learning!

<>


logicmojoContact

HAVE A QUESTION? GIVE US A CALL OR CONTACT US - WE'D LOVE TO HEAR FROM YOU

PHONE: +91 80889-75867

WhatsApp : Click Here...

FEEDBACKFORM