Gadgets

Monday, 2 February 2015

Data types in java

In java every variable and every expression should has some type and every type is clearly define.
Each and every assignment should be checked by compiler for type compatibility hence java language considered as strongly typed programming language because type checking is very strong and type is very important.
Java is not considered as pure object oriented programming language because several OOP’s features are not supported by java (like operator overloading, multi threading, ect.) moreover we depending on primitive data types which are non objects.
Except Boolean and char remaining data types are considered as signed data types because we can represent both positive (+ve) and negative (-ve) numbers.
In java, there are 2 types of data types
 1. Primitive data types
2. Non primitive data types



byte:-
Byte is the best suitable, if we want to handle data in term of streams from the file or from the network
Size: 1byte (8bits), Range:  -128 to +127(-27 to +27-1)
+ve or _ve sign
26
25
24
23
22
21
20

64+32+16+8+4+2+1=127
Note:- the most significant bit as the sign bit ‘0’ mean +ve and ‘1’ mean –ve
byte b=10;  //Correct         byte b=127;  //Correct
byte b=128;  //Wrong(out of the byte range)   
Compile time error (jdk6 version):- possible loss of precision
                                                             found: int
                                                             required: byte

byte b=10.5; Wrong(it is float type value so we can’t assign float type to the byte type)
compile time error:- possible loss of precision
                                      found: double
                                      required: byte
byte b=true;  Wrong(‘true’ is Boolean type not byte type)
compile time error:- incompatible types
                                      found: boolean
                                      required: byte
byte b=”java”;  Wrong(“java” is String type not byte type)
compile time error:- incompatible types
                                      found: double
                                      required: byte



Note:- In jdk6 version we get an error message as like below
found:int
requied:byte
In jdk7 version we get an error message as below:
required:byte
found:int

short:-
The mostly rarely used data type in java is ‘short’. This data type is best suitable for 16bit processor like 8086 processor but these processors are outdated and hence the corresponding ‘short’ data type also outdated data type.
Size: 2bytes (16 bits), Range: -32768 to +32767(-215 to +215-1)
Example:-
class Test{
public static void main(String arg[]){
short a=32767;  //Correct
short b=32768; // Wrong(value is out the short range)
short c=10.3;  // Wrong(value is float type, we can’t assign it to the short type)
short d=true;// Wrong(value is boolean type, we can’t assign it to the short type)

}
}



int:-
The most commonly used data type in java is ‘int’.
Size: 4byte (32bits), Range: -2147483648 to +2147483647(-231 to +231-1)
Example:-
class Test{
public static void main(String arg[]){
int a=2147483647;  //Correct
int b=2147483648L; // Wrong
int c=10.3;  // Wrong
int d=true;  // Wrong
int e=”hello”;  // Wrong
}
}



long:-
Sometimes ‘int’ may not enough to hold big value then we should use ‘long’ data type.
Size: 8byte (64bits), Range: -263 to 263-1
Example:-
To hold amount of distance travelled by light in 1000daysat that time ‘int’ may not enough so we should use ‘long’ data type.
long l=126000*60*60*24*1000miles;
To hold number of characters in a big file ‘int’ may not enough then we use type of length() method.
long l=f.length();
Floating point data types:-
Note:- by default every floating point literal is double type, we can’t assign directly to float type. We can assign float type by suffixed with f or F;
float f=123.456; //Wrong(we should specify suffixed with f or F to the float value like 123.456f)
float f=123456; //Correct
double b=123.456;  //Correct
float f=123.456f; or float f=123.456F;    //Correct
Float:-
If we want declare 5 to 6 decimal points to a number then we should take ‘float’ data type.
Size:-  4 bytes(32bits), Range:-  -3.4e38 to 3.4e38.
Example:-  float f=10.01f;
Double:-
If we want declare 14 to 15 decimal points to a number then we should take ‘double’ data type.
Size:- 8byte(64bits), Range:-  -1.7e308 to 1.7e308.
Example:- double b=10.01;
Boolean:-
Size:- size is not applicable(virtual machine dependency).
Range:- not applicable but it allowed values are true or false.
Examples:-
boolean b=true;        //Correct
boolean b=True;      // Wrong(here ‘T’ is upper case so Boolean type is not allowed it)


boolean b=0;     //Wrong(zero is number, we can’t assign it to boolean)



boolean b=”true”;     //Wrong (“true” is string type, we can’t assign it to Boolean type)



Example:-  
class Test1
{
public static void main(String arg[])
{
boolean b=0;
if(b){
System.out.println("hello");
}
else{
System.out.println("hi");
}
}
}


Char data type:-
Old languages(c,c++) are ASCII code bits and the number of different allowed ASCII characters are less than or equal 256(<=256) to represent these characters 8 bits(1byte) are enough hence the size ‘char’ in old language is 1 byte(8bits).
Java Unicode based and the number of Unicode characters are greater than 256 and less than or equal 65536(>256 and <=65536) to represent these characters 16bits (2byte) are required in java and 8bits (1byte) not enough.
Size:-  2byte (16bits)    Range:-  0 to 65535.
Summary table of java primitive data types:-
Data type
Size
Range
Corresponding wrapper class
Default value
byte
1byte
-27 to 27-1
 (-128 to 127)
Byte
0
short
2bytes
-215 to 215-1
(-32768 to 32767)
Short
0
int
4bytes
-231 to 231-1 (-2147483648 to 2127483647)
Integer
0
long
8bytes
-263 to 263-1
Long
0
float
4bytes
-3.4e38 to 3.4e38
Float
0.0
double
8bytes
-1.7e308 to 1.7e308
Double
0.0
boolean
Not applicable
Not applicable but allowed values are true and false
Boolean
False (in ‘C’ language ‘true’)
char
2bytes
0 to 65535
Character
0(represent space character)

Note:- ‘null’ is the default value for object reference, we can’t use ‘null’ value for primitive data types. If we use ‘null’ value for primitive data types we will get compile time error.
Example:-
class Test
{
public static void main(String arg[]){
int i=null;
}
}
Output:-

Java Language Fundamentals

1. Language Fundamentals:-

·        Identifiers
·        Reserved words
·        Datatypes
·        Literals
·        Arrays
·        Types of variables
·        Var-arg methods
·        Main method
·        Command line argument
·        Java coding standards


Identifiers:

           A name in java program is called identifier, which can use for identification purpose. It can be class name, method name, variable name or label name.
Example:-
class Student
{
public static void main(String arg[])
{
int a=10;
}
}
In the above program we have 5 identifiers (Student, main, String, arg, a)

Rules for java identifiers:-

·         The only allowed characters in java identifiers are 
A to Z, a to z, 0 to 9, $, _
By mistake if we use other character, we will get an error at compile time

·         Identifier should not start with digit(0-9)
Example:-  int name123=10;     //Correct
                   int 123name=10;    //wrong

·         Java identifiers are case sensitive
Example:-
class Student
{
int number=10;       //Correct
int Number=10;      //Correct
int NUMBER=10;     //Correct
int total=number+Number+NUMBER;    // Correct
}
In the above program that three variables are different
·         There is no length limit for identifiers but it is not good programming
                     int a=10;      //Correct
                     int aaaaaaaabbbbbbbbcccccccccc=10;     //Correct but not good programming

·         we can’t use a java reserved word as an identifier. If we use java reserved keyword as an identifier, we will get an error at compile time.
                    int a=10;        //Correct
                    int while=10;     //wrong(while is reserved keyword)
“while” is java reserved keyword.

·         All predefine java classes or interfaces can be used as identifiers.
Example:-
class Text
{
public static void main(String arg[])
{
int String=10;
int Runnable=20;
System.out.println(String+” “+Runnable);
}
}
Output:- 10 20
In the above example program String is class and Runnable is interface but we used as identifiers.

Examples of valid and invalid identifiers

student_name      Correct
Name#        wrong
student@name
number123name     Correct
name$         Correct
_$name     Correct
int      wrong(int is a data type)
Int     Correct
Integer     Correct

Reserved Words:-

In java some words are reserved to represent some meaning or functionalities, such type of words are called reserved words.





Keywords for data types (8):-
byte, short, int, long, float, double, boolean, char
Keywords for flow control (11):-
if, else, switch, case, default, for, while, do, break, continue, return
Keywords for modifiers (11):-
public, private, protected, final, abstract, synchronized, native, static, strictfp (jdk1.2 keyword), transient, volatile
Keywords for exception handling (6):-
try, catch, finally, throw, thrown, assert(jdk1.4 keyword)
Class related keywords (6):-
class, interface, package, import, extends, implements
Object related keywords (4):-
new, super, this, instanceof
void return type keyword:-
In java return type is mandatory, method should be declare with void return type
Note:- In “C” language return type is optional and default return type is “int”.
Unused Keywords:-
goto, const.
Usage of goto keyword creates several problems in old languages and hence sun engineers ban this keyword in java.
We use “final”  keyword instead of “const”.
Note:- goto and const are unused keywords in java and we are not allowed to use these keywords in our program. If we are trying to use then we will get compile time error.
Reserved Literals:-
True,false --- these keywords values for Boolean type.
 Null --- this keyword default value for any object reference.
enum keyword (jdk1.5 keyword):-
If we want to define a group of named constants then we should go for enum.

Note***:-
·         All 53 reserved keywords in java contain only lower case of alphabets.
·         Newly added keywords are strictfp(jdk1.2 version), assert(jdk1.4 version), enum(jdk1.5 version).
·         In java we have “new” keyword for create object but we don’t have “delete” keyword for delete useless object because distraction of useless object is the responsibility of garbage collector.

Common mistakes:-

Correct                                          wrong
const                                          constant
instanceof                                  instanceOf
strictfp                                       strictFp
synchronized                            synchronize 
 extends                                     extend
 implements                               implement
import                                       imports