PRIMITIVE TYPES - JAVA: Learn JAVA Quickly (2017)

JAVA: Learn JAVA Quickly (2017)

CHAPTER 1. PRIMITIVE TYPES

Primitive types are most basic data types that are used in Java. They are stored in variables. Variable is nothing but reserved memory. Size of memory depends of primitive type. All primitive types have their default value. Sizes are:

Primitive type

Size

Minimum

Maximum

Boolean

1-bit

-

-

char

16-bit

Unicode 0

Unicode 216- 1

byte

8-bit

-128

+127

short

16-bit

-215

+215 – 1

int

32-bit

-231

+231 – 1

long

64-bit

-263

+263 – 1

float

32-bit

IEEE754

IEEE754

double

64-bit

IEEE754

IEEE754

DECLARATION AND INITIALIZATION OF PRIMITIVE TYPES

inta;

inta = 1;

inta,b;

inta = 2; intb = 2;

finalinta = 15;//constant

Declaration means to give variable type along with name: inta; So, our variable is type of integer and have name a;Initialization is process of adding value to primitive type, in this case: inta = 0; Before this int have default value. For boolean default value is false, for char is '\u0000', for rest is zero (0).

CONVERSATION OF PRIMITIVE TYPES

IMPLICIT

inta = 1;

doubleb;

b = a;

EXPLICIT

longa = 4l;

intb = a;//mistake

intc = (int)a;

Note: This is called cast operator. Operators will be covered next.

OPERATORS

ARITHMETIC OPERATORS

Main operators are: +, -, *, /, %

y = 5; OperatorResult

x = y + 1y = 6

x = y – 1y = 4

x = y % 2y = 1

x = ++yx = 6; y = 6

x = y++x = 5; y = 6

x = --yx = 4; y = 4

x = 6

y = 3Operator Same as Result

x = yx = 3

x + = y x = x + y x = 9

x - = yx = x – y x = 3

x * = y x = x * y x = 18

x / = y x = x / yx = 2

x % = y x = x % y x = 0

RELATIONAL OPERATORS

Main operators are: <, >, <=, >=, ==, !=

x = 3

y = 2Operator Result

x < yfalse

x > y true

x <= yfalse

x >= ytrue

x == yfalse

x != ytrue

Arithmetic operators are commonly used, as you guess, in math operations. Modulo (%) can be used to check if number is even or odd for example. Relational operators are very simple. ==and !=are common used for comparisons. Operator + can be used to concatenate two Strings also.

LOGICAL OPERATORS

Logical operators

Main operators are: && (logical AND), || (logical OR), ! (logicalNOT)

&&false true ||false true!

falsefalse falsefalse falsetruefalsetrue

truefalse truetrue true truetruefalse

x = 2

y = 4Operator Result

((x< 1) && (y > 3))false

((x< 5) || (y = 5))true

!(x > y)true