Variables and Datatypes in JAVA

Variables and Datatypes in JAVA

In this tutorial we are going to learn about variables and datatypes in Java Programming

So let’s have look at the picture below for understanding the anatomy of a basic Java Program again


Now, let's get back to the point---

Just like we have some rules that we follow to speak English (the grammar), we have some rules to follow while writing a JAVA program. The set of the rules is called Syntax (Vocabulary & Grammar of JAVA).

VARIABLES:

A variable is a container that stores a value. This value can be changed during execution of the program.

Example:

                int number = 8

Here int is a DATATYPE; number is a Variable name; 8 is the value which the variable has stored.

Rules for declaring a Variable name:

We can choose a name while declaring a JAVA variable if the following rules are allowed.

  1. Must not begin with a digit. (int 1var; is invalid)
  2. Name is case sensitive. (Coder and coder are different)
  3. Should not be a keyword. (Like; void, static)
  4. White spaced are not allowed. (int data types; is invalid)
  5. Can contain alphabets, $characters, _character, and digits if the other conditions are met.


DATATYPES:

Data Types in JAVA fall under the following categories:

  1. Primitive Data Types. (Intrinsic)
  2. Non Primitive Data Types. (Derive)
    • PRIMITIVE DATA TYPES:
JAVA is statically typed (Variables must be declared before use). There are 8 Primitive Data Types supported by JAVA:
  1. byte ---  
      • Value ranges from -128 to 127.
      • Takes 1 byte.
      • Default value is 0.
  2. short ---
      • Value ranges from [ -(2^16)/2 to (2^16)/2 -1 ]
      • Takes 2 bytes.
      • Default value is 0.
  3. int ---
      • Value ranges from [ -(2^32)/2 to (2^32)/2 -1 ]
      • Takes 4 bytes.
      • Default value is 0.
  4. float ---
      • Value ranges from (See docs)
      • Takes 4 bytes.
      • Default value is 0.0f
  5. long ---
      • Value ranges from  [ -(2^64)/2 to (2^64)/2 -1 ]
      • Takes 8 bytes.
      • Default value is 0.
  6. double ---
      • Value ranges from (See docs)
      • Takes 8 bytes.
      • Default value is 0.0d
  7. char ---
      • Value ranges from [ 0 to 65535(2^10-1) ]
      • Takes 2 bytes. (because it supports unicode)
      • Default value is '\u0000' (or 0)
  8. boolean ---
      • Value can be true or false.
      • Size depends on JVM.
      • Default value is false.

Comments

Popular posts from this blog

JAVA Practice Set 2

Java Practice Set 4

Java Practice Set 3