Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Chapter 1

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Variables and Datatypes

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 these rules is called syntax.

Variables

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

Example :

Int number = 8; -- value it stores!

^ ^

Data type variable name

Rules for declaring a variable name

We can choose a name while declaring a java variable if the following rules are followed :

1. Must not being with a digit -- int 1array; -- is invalid !


2. Name in case sensitive -- kunal and Kunal are different !
3. Should not be a keyword (like void)
4. While space not allowed. – int k u n a l -- is invalid !
5. Can contain alphabets, $ character, _ character and digits if the other condition are met.

Data Types

Data types in java fall under the following categories

1. Primitive Data Types(Inteinsic)


2. Non – Primitive Data Types (Derived)

Primitive Data Type

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 2 bytes
Default value is 0
2. Short = value range from –(2^16)/2 to (2^16)/2 -1
Takes 2 bytes
Default value is 0

3. Int = value range from –(2^32)/2 to (2^32)/2 -1


Takes 4 bytes
Default value is 0

4. Float = Takes 4 bytes


Default value is 0.0f

5. Long = Takes 8 bytes


Default value is 0

6. Double=Takes 8 bytes
Default value is 0.0d

7. Char = value ranges from 0 to 65535


Takes 2 bytes
Default value is ‘\U000’

8. Boolean= value can be true or false


Size depends on JVM
Default value is false

Quick Que :

write a java program to add three numbers.

In order to choose the data type we first need to find the type of data we want to store after that we
need to anally the

Min & max value we might use

Literals

A constant value which can be assigned to the variable is called as a literal

101 -- Integer literal

10.1f – float literal


10.1 -- double literal

‘A’ -- character literal

True -- Boolean literal

“kunal” -- string literal

Keywords

Words which are reserved and used by the java compiler. They cannot be used as an identifier.

Reading data from the keyboard

In order to read data from the keyboard java has a scanner class

Scanner class has a bt of method to read the data from the keyboard

Example :

Scanner S = new Scanner(System.in); -- Read from the keyboard

Int a = s.nextInt(); -- Method to read from the keyboard (integer in this case)

You might also like