Java : Variables & Data Types

Java : Variables & Data Types

- VINAYAK PANCHAL

Introduction

Before understanding what are variables and datatypes in Java, lets first understand why the heck do we need them at first place? What is their significance? Why are we studying about them in the first place? So, Variables are of outmost importance because they enable programmers to write flexible programs. Rather than entering data directly into a program, a programmer can use variables to represent the data. Coming to various Datatypes, they are especially important in Java because it is a strongly typed language. This means that all operations are type-checked by the compiler for type compatibility. Illegal operations will not be compiled. Thus, strong type checking helps prevent errors and enhances reliability.

Variables: Definition

A variable is a container that stores a value. It is the basic unit of storage. It acts as a container and is used to hold data values. The values held by the variable can be changed during the execution of the program. Every variable is assigned a data type. Variable, in simpler terms, is a name given to a memory location.

Variable type (1).png

BEFORE GOING INTO DATA TYPES, LET'S UNDERSTAND RULES FOR DECLARING A VARIABLE NAME

1) Names can contain letters, digits, underscores, and dollar signs

2) Names must begin with a letter

3) Names should start with a lowercase letter and it cannot contain whitespace

4) Names can also begin with $ and _ ( I consider it to be not a good practice)

5) Names are case sensitive ("myVar" and "myvar" are different variables)

6) Reserved words ( such as int or boolean ) cannot be used as names.

DATA TYPES : DEFINITION

In Java, Datatypes are of two types :-

Variable type (2).png

In Java variables are declared before there are used. The reason behind this is that Java is a statically type language. There are 8 primitive types of data :-

Variable type (4).png

As it turns out, first we need to understand which type of data we want to store and then choose the datatype given above. String which is one of the popular datatype is a non-primitive data type. Non-primitive data types are called reference types because they refer to objects.

THE DIFFERENCE B/W PRIMITIVE AND NON-PRIMITIVE DATA TYPES :-

1) Primitive types are already defined in Java. Non-primitive types are created by the programmer (except for String).

2) Only Non-primitive types can be used to call methods to perform certain operations.

3) A primitive type has always a value, while non-primitive types can be null when required.

4) A primitive type starts with a lowercase letter, while non-primitive types starts with uppercase letter.

Some examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.

THANKS FOR READING MY ARTICLE📄 HOPE THAT IT ADDS VALUE⤴️

FOLLOW ME ON HASHNODE VINAYAK PANCHAL