Java - Data Types

ZoneTechPro
By -
0

Introduction

We will explore the various data types supported by Java.


Data Types
Introduction of Data Types


1. Data Types

In programming, every value has an associated type known as a data type. Java supports two main categories of data types:

  • Primitive Data Types
  • Non-Primitive Data Types


Primitive Data Types:

Primitive data types are predefined by Java and include:

  • boolean
  • char
  • byte
  • short
  • int
  • long
  • float
  • double

These data types define how values are stored and manipulated in a program. For example, mathematical operations can be performed on numeric data types.

Boolean :

A Boolean represents one of two possible values, such as true or false.

class Main {

    public static void main(String[] args) {

        boolean canLearn = true;

        System.out.println(canLearn);

    }

}

Output: true

Char:

The char data type stores a single character and must be enclosed in single quotes.

char alphabet = 'A';

Byte:

The byte data type stores small integer values within the range -128 to 127.

byte points = 100;

Short:

The short data type stores integers from -32,768 to 32,767.

short number = 28745;

Int:

The int data type is commonly used to store whole numbers.

int distance = 2036372;

Long:

The long data type stores large integer values and requires an L suffix.

long area = 203637254L;

Float:

The float data type stores decimal values with up to 7 digits of precision and requires an f suffix.

float height = 5.10f;

Double:

The double data type stores decimal values with up to 16 digits of precision.

double length = 5.112;

double breadth = 9.2345D;

Non-Primitive Data Types:

Non-primitive data types store multiple values and are defined by the programmer. Common non-primitive types include:

  • String
  • Class
  • Array

String:

A String is a sequence of characters enclosed in double quotes.

String name = "Raj";

Common Mistake:

Using single quotes instead of double quotes for String values will result in an error:

class Main {

    public static void main(String[] args) {

        String name = 'Raj'; // Incorrect

        System.out.println(name);

    }

}

Output: Compilation error: unclosed character literal

Corrected Code:

class Main {

    public static void main(String[] args) {

        String name = "Raj";

        System.out.println(name);

    }

}

Output: Raj

Summary

  • Primitive Data Types: boolean, char, byte, short, int, long, float, double.
  • Non-Primitive Data Types: String, Array, Class.

These data types form the foundation of Java programming, allowing efficient data storage and manipulation.

 


Tags:

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!