JavaIntellectualTricks

Arrays

  1. Introduction
  2. Array Declaration
  3. Array Creation
  4. Array Initialization
  5. Array Declaration, creation and initialization in a single line
  6. length vs length()
  7. Anonymous Arrays
  8. Array Element Assignments
  9. Array variable Assignments
Introduction:-

  • An array is an indexed collection of fixed number of homogeneous data elements.
The main advantage of arrays is , we can represent huge number of values by using single variable. So that readability of the code will be improved, but the main disadvantage of the arrays is fixed in size i.e once we creates an array there is no chance of increasing or decreasing in the size based on the requirement.
Hence to use arrays concept, compulsory we should know the size in advance , which may not possible always.
Array Declaration:-

One Dimensional Array Declaration:-
int[] x ; //valid and recommended because name is clearly separated from type.
int []x; //valid but not recommended.
int x[]; //valid but not recommended.

At the time of declaration we can't specify the size , otherwise we ll get compile time error.
Example: int[6] x; //Invalid

Two Dimensional Array Declaration:-
int[][] x ; //valid and recommended because name is clearly separated from type.
int [][]x; //valid but not recommended.
int x[][]; //valid but not recommended.
int[] []x; //valid but not recommended.
int[] x[]; //valid but not recommended.
int []x[]; //valid but not recommended.

Q.Which of the followings are valid?
  1. int[] a,b; // valid ,a's dimension=1 & b's dimension=1
  2. int[] a[],b; //valid ,a's dimension=2 & b's dimension=1
  3. int[] a[],b[]; //valid ,a's dimension=2 & b's dimension=2
  4. int[] []a,b; //valid, a's dimension=2 & b's dimension=2
  5. int[] []a,b[]; //valid, a's dimension=2 & b's dimension=3
  6. int[] []a,[]b; //Invalid

  • If we want to specify dimension before the variable, that facility is applicable only for first variable in a declaration. If we are trying to apply for remaining variables ,we ll get compile time error. Ex: int[] []a (valid), []b (Invalid), []c (Invalid);
Three Dimensional Array Declaration:-
int [][][]a; //valid
int [][][]a; //valid
int a[][][]; //valid
int[] [][]a; //valid
int[] a[][]; //valid
int[] []a[]; //valid
int[][] []a; //valid
int[][] a[]; //valid
int [][]a[]; //valid
int []a[][]; //valid

Array Creation:-
Every array in java is an object only,hence we can create arrays by using 'new' operator.
Example:
int[] a=new int[3];
For every array type, corresponding classes are available and these classses are part of java language and not available to the programmer level.

int[] a=new int[3];
System.out.println(a.getClass().getname()); // o/p: [I
ArrayType
Corresponding Class Name
int[]
[I
int[][]
[[I
double[]
[D
short[]
[S
byte[]
[B
boolean[]
[Z
Points:
  1. At the time of array creation , compulsory we should specify the size, Otherwise we ll get compile time error.
    Example:- int[] x=new int[]; // Invalid
            int[] x=new int[6]; //valid
  1. It is legal to have an array with size zero in java.
    Example: int[] x=new int[0]; //valid
  2. If we are trying to specify array size with some negative int value, then we ll get Run time Exception saying NegativeArraySizeException.
    Example: int[] x=new int[-6]; //No Compile Time Error
  3. To specify array size , the allowed data types are byte,short,char,int. If we are trying to specify any other type, then we ll get compile time error.
    Example: int[] x=new int[10]; // valid
    int[] x=new int['a']; //valid
    byte b=20;
    int[] x=new int[b]; //valid
    short s=10;
    int[] x=new int[10l]; //Invalid C.E possible loss of precession, found: long, required: int
  4. The maximum allowed array size in java is 2147483647, which is the maximum value of int data type.
    Example: (i) int[] x=new int[2147483647]; //valid
             (ii) int[] x=new int[2147483648]; // C.E. Integer Number too large
Even in the (i) case we may get a Run time Exception if sufficient heap memory is not available.

Two Dimensional Array Creation:-
In java 2 D array is not implemented by using matrix style. Sun people followed array of arrays approach for multi dimensional array creation.
The main advantage of this approach is memory utilization will be improved.
Example:-
Student No
Math
Physics
Chemistry
Bio
1
45
12
23
12
2
56
64
Not appeared
Not appeared
3
85
Not appeared
Not appeared
Not appeared
Here “Not appeared” memory locations are wasted, so SUN people followed array of arrays approach i.e.
Here memory is optimized.
Example-1:
int[][] x=new int [2][];
x[0]=new int[2];
x[1]=new int[3];
                                                                        (Example-1)

Example-2:
int[][][] x=new int [2][][];
x[0]=new int[3][];
x[0][0]=new int[1];
x[0][1]=new int[2];
x[0][2]=new int[3];
x[1]=new int[2][2];
x[1][0]=new int[2];
x[01[1]=new int[2];

                                                                          (Example-2)

Q.Which of the following array declarations are valid ?

1. int[] a= new int[]; //Invalid, at least base size must be specified
2. int[] a= new int[3]; //valid
3. int[][] a= new int[][]; //Invalid, at least base size must be specified
4. int[][] a= new int[3][]; //valid
5. int[][] a= new int[][4]; //Invalid, base size must be specified
6. int[][] a= new int[3][4]; //valid
7. int[][][] a= new int[3][4][5]; //valid
8. int[][][] a= new int[3][4][]; //valid
9. int[][][] a= new int[3][][5]; //Invalid; without 2nd dimension we can't assign 3rd dimension
10.int[][][] a= new int[][4][5]; //Invalid; without 1st dimension we can't assign 2nd and 3rd dimension

Array Initialization:
Once we creates an array, every element by default initialized with default values.
Example-1:
Int[] x=new int[3];
System.out.println(x); // [I@8d00ce
System.out.println(x[0]); //0
Example-2:
Int[][] x=new int[2][3];
System.out.println(x); // [[I@8d00ce
System.out.println(x[0]); // [I@7f00de
System.out.println(x[0])[0]; //0
Example-3:
Int[][] x=new int[2][];
System.out.println(x); // [[I@8d00ce
System.out.println(x[0]); // null
System.out.println(x[0])[0]; //NullPointerException

Note: If we are trying to perform any operation on null, then we ll get run time exception saying “NullPointerException”.

Once we creates an array, every array element by default initialized with default values.
If we are not satisfied with default values,then we can override these values with our customized values.
int[] x=new int[6];
x[0]=10;
x[1]=20;
x[2]=30;
x[3]=40;
x[4]=50;
x[5]=60;
x[6]=70; // ArrayIndexOutOfBoundsException
x[-6]=80; // ArrayIndexOutOfBoundsException
x[2.5]=90; // Compilation Error, Possible loss of precission, found :double, required :int

Note: If we are trying to access array element with out of range index (either +ve or -ve int value), then we ll get runtime exception saying “ArrayIndexOutOfBoundsException”.

 Array Declaration,Creation and Initialization in a single line:-

we can declare, create and initialize an array in a single line(shortcut representation)
Example:-
int [] x;
x=new int[3];
x[0]=10;
x[1]=20;
x[2]=30;
 //Alternate way
int [] x={10,20,30};
char[] ch={'a','e','i','o','u'};
String [] s={"A","AA","AAA"};
We can use this shortcut for multidimensional arrays also.

Example 1:
int[][] x={{10,20}{30,40,50}};
see the below figure for memory representation.
(Example-1)
Example 2:
int [][][] x={{{10,20,30},{40,50,60}},{{70,80},{90,100,110}}};
                                                                   (Example-2)
System.out.println(x[0][1][2]);//60
System.out.println(x[1][0][1]);//80
System.out.println(x[2][0][0]);//ArrayIndexOutsOfBoundsException
System.out.println(x[1][2][0]);//ArrayIndexOutsOfBoundsException
System.out.println(x[1][1][1]);//100
System.out.println(x[2][1][0]);//ArrayIndexOutsOfBoundsException
 case:1
 If we want to use this shortcut compulsory we should perform all activities in a single line. If we are trying to divide into m multiple lines , then we will get compile time error.
 Example 1:
int x=10; == int x; x=10;
int [] x={10,20,30}; == int [] x;(correct) x={10,20,30};(illegal start of expression)

 length vs length( ):-

length:
length is a final variable applicable for arrays.
length variable represents the size of the array.
Example:
int [] x=new int[6];
s.o.p(x.length());//C.E. can't find symbol method length() location class int[]
s.o.p(x.length);//6
length( ):
length( ) is a final method applicable for String objects.
length( ) returns number of characters present in the String.
 Example:
 String s="purna";
s.o.p(s.length);//can't find symbol variable length location class java.lang.String
s.o.p(s.length());//5

Note:length variable applicable for arrays but not for String objects where as length() applicable for String objects but not for arrays.
 String [] s={"A","AA","AAA"};
s.o.p(s.length); // correct
s.o.p(s.length()); //C.E can't find symbol ,symbol: variable length(), location: class String[]
s.o.p(s[0].length); //C.E can't find symbol ,variable length, location: class- java.lang.String
s.o.p(s[0].length()); //correct
Example:
int [][] x=new int [6][3];
System.out.println(x.length);//6
System.out.println(x[0].length);//3
Note: In multi dimensional length variable represents only base size but not total size.
There is no direct to way to find out total length of multi dimensional array but indirectly we can find as follows:
x[0].length+x[1].length+x[2].length+...........

Anonymous Array:
Sometimes we can declare an array without name, such type of name less arrays are called anonymous arrays.
The main purpose of anonymous arrays is just for instant use(one time usage).
Declaration:
we can create anonymous array as follows: new int[]{10,20,30,40}
1.while creating anonymous arrays we can't specify the size, otherwise we will get compile time error.
Example:
new int[4]{10,20,30,40} //invalid
new int[]{10,20,30,40} //valid

class Test{
public static void main(String [] args){
sum(new int[]{10,20,30,40});
}

public static void sum(int [] x){
int total=0;
for(int x1: x){
total=total+x1;
}
System.out.println(“The sum is”+ total);
}
}
In the above example just to call sum(), we require an array, but after completing sum() method call we are not using that array anymore. Hence for this one requirement anonymous array is the best choice.
2. We can create multi dimensional anonymous arrays also.
new int []{{10,20},{30,40,50}}
3.Based on our requirement we can give the name for anonymous array, then it is no longer anonymous.
new int[{10,20,30}] //anonymous
Int [] x= new int[{10,20,30}]; //not anonymous

 Array element assignments:-
Case 1:
In the case of primitive type arrays as array elements, we can provide any type,which can be implicitly promoted to declared type.
Example:
int [] x= new int[5];
x[0]=10;
x[1]='a';
byte b=20;
x[2]=b;
short s=30;
x[3] =s;
x[4]=10l; //C.E. Possible loss of precision found long required :int
In the case of float type arrays, the allowed data types are byte,short,int,long,char,float.
Case 2:
In the case of Object type arrays as array elements ,we can provide either declared type objects or it's child class objects.
Example 1:
Object [] a=new Object[10];
a[0]=new Object();
a[1]=new String(“purna”);
a[2]=new Integer(10);
Example 2:
Number [] n=new Number[10];
n[0]=new Integer(10);
n[1]=new Double(10.5);
n[2]=new String(“purna”); // C.E. Incompatible types: found java.lang.String, required: java.lang.Number
Case 3:
For interface type arrays as array elements,it's implementation class objects are allowed.
Runnable [] r = new Runnable[10];
r[0]=new Thread(); //Here: Class Thread implements Runnable
r[1]=new String(“purna”); //C.E. Incompatible type found: java.lang.String required java.lang.Runnable.
Array Type Allowed element type
Primitive Arrays Any type which can be implicitly promoted to declared type.
Object type Arrays Either declared type or its child class objects
Abstract class type Arrays It's child class objects
Interface type Array It's implementation class objects
Array variable Assignments:

Case 1:
Element level promotions are not applicable at array level.
char element can be promoted to int type, where as char [] can't be promoted to int[].
Example:
int [] a={10,20,30,40};
char [] ch={'a','b','c','d'};
int [] b=a; //valid
int [] c=ch; //invalid C.E Incompatible type found char[] required: int[]

Q.Which of the following promotions will be performed automatically?
1. char --> int //valid
2. char[] -->int[] //invalid
3. int --> double //valid
4. int[] --> double[] //invalid
5. float --> int //invalid
6. float[] --> int[] //invalid
7. String --> Object //valid
8.String[] --> Object[] //valid

Note: But in the case of object type array, the child class type array can be promoted to parent class type array.
String [] s={“A”,”B”,”C”};
Object [] a=s; //valid

Case 2:
Whenever we are assigning one array to another array, internal elements won't be coppied, just reference variables will be reassigned.
int[] a={10,20,30,40,50};
int[] b={60,70,80};
  1. a=b; //valid
  2. b=a; //valid
Case 3:
Whenever we are assigning one array to another array, the dimensions must be matched. For example in the place of one dimensional int array we should provide one dimensional int array only.
If we are trying to provide any other dimension, then we will get compile time error.

int[][] a= new int[3][];
a[0]= new int[4][3]; // C.E Incompatible type found int[][], required int[]
a[0]=10; // C.E Incompatible type found int, required int[]
a[0]=new int[2]; //valid
Note: Whenever we are assigning one array to another array, both dimensions and type must be matched but sizes are not required to match.
Example 1:
class Test{
public static void main(String [] args){
for(int i=0;i<args.length;i++){

System.out.println(args[i]);
}
}
}
java Test A B C // O/P- A B C ArrayIndexOutOfBoundsException
java Test A B // O/P- A B ArrayIndexOutOfBoundsException
java Test // O/P- ArrayIndexOutOfBoundsException

Example 2:
class Test{
public static void main(String [] args){
String [] argh ={“A”,”B”,”C”};
args=argh;
for(String s:args ){
System.out.println(s);
}
}
}
java Test A B C // O/P- X Y Z
java Test A B // O/P- X Y Z
java Test // O/P- X Y Z
Example 3:
int[][] a= new int[4][3]; // Here 5 objects are created
a[0]= new int[4]; // Here 1 object is created
a[1]= new int[2]; // Here 1 object is created
a= new int[3][2]; // Here 4 objects are created
Total How many Objects are created here ? Ans- 11
Total How many Objects are eligible for garbage collected ? Ans- 7

Literals

Any Constant value which can be assigned to a variable.
Example: int x=10;
Here, int represents Data Type/Key Word, x represents Variable/Identifier, 10 represents Constant/Literal.

Integral Literal:
For Integral data types (byte, short, int , long) we can specify literal value in the following ways.

1.Decimal Literals (Base 10)
Allowed digits are 0 to 10
Example: int x=10;

2.Octal Literal (Base 8)
Allowed digits are 0 to 8
Literal value should be prefixed with zero(0).
Example: int x=010;

3.Hexadecimal Literal( Base 16)
Allowed digits are 0 to 9, a to f
Literal value should be prefixed with 0X or 0x
Example 1 : int x=0X10;

For extra digit ( a to f ) , we can use both lower case and upper case character. This is one of very few area where java is not case sensitive.

These are only possible ways to specify literal values for integral data types.

Q. Which of the following declarations are valid?

int x=10; (valid)
int x=0786; (in valid C.E. Integer number too large)
int x=0777; (valid)
int x= 0XFace; (valid)
int x=0XBeef; (valid)
int x=0XBeer; (C.E ; expected)

Example 2:
class Test{
public static void main (String [] args){
int x=10;
int y=010;
int z=0X10;
System.out.println(x+“ ”+y+” ”+z);
}
}
o/p- 10 8 16

Note: If we are giving the values as decimal, octal, hexadecimal then by default JVM internally converts all the values in to decimal form and gives the o/p as decimal form.

  • By default every integral literal is of int type, but we can specify explicitly as long type by suffixed with l or L.
int x=10; (valid)
long l=10L; (valid)
int x=10L; C.E Possible loss of Precesion required int, found long
long l=10; (valid as int value can be stored in long variable i.e 32 bit value can be stored in 64 bit allocating variable)
  • There is no direct way to specify byte and short literals explicitly, but indirectly we can specify. When ever we are assigning integral literal to the byte variable and if the value with in the range of byte, then compiler treats it automatically as byte literal. Similarly short literal also.
byte b=10; valid
byte b=127; valid
byte b=128; Possible loss of Precision found int, required byte

short s=32767; valid
short s=32768; Possible loss of Precision found int, required short

Floating Point Literal:
By default every floating point literal is of double type and hence we can't assign directly to the float variable.
But we can specify floating point literal as float type by suffixed with f or F.
Example:
float f=123.456; //possible loss of Precision found double ,required float
float f=123.456f; //valid
double d=123.456; //valid
we can specify explicitly floating point literal as double type by suffixed with d or D.
Of course this convention is not required.
Example:
double d=123.456d;
float f=123.456d; // C.E possible loss of  precision found double , required float.

We can specify floating point literals only in decimal form and we can't specify in octal and hexadecimal forms.
Example:
double d=123.456; //valid
double d=0123.456; // valid as this is the decimal literal not octal literal as 0 before floating value is not considered and considered as decimal.
double d=0X123.456 //C.E. Malformed floating point literal

We can assign integral literal directly to floating point variables and that integral literal can be specified either in decimal, octal or hexadecimal forms.
Example:
double d=0786; //invalid, integer value too large
double d=0XFace; // valid
double d=0786.0; //valid
double d=0XFace.0; // invalid
double d=0777; //valid
double d=10; //valid

We can't assign floating point literals to integral types.
Example:
double d=10; // valid
int x=10.0; // possible loss of precision found double , required int

We can specify floating point literal even in exponential form(scientific notation)
Example:
double d=1.2e3; // valid and o/p=1200.0 ( since 1.2*10^3)
float f=1.2e3; // C.E possible loss of precision found double, required float.
float f=1.2e3; // valid

boolean Literal:

The only allowed values for boolean data type are true or false.
Examples:
boolean b=true; (valid)
boolean b=0; (invalid, gives compile time error, “incompatible type”, found int, required boolean)
boolean b=True; (invalid, gives compile time error, “can't find symbol”, class Test)
boolean b=”True”; (invalid, gives compile time error, “incompatible type”, found java.lang.String, required boolean)

Ex.1                                                                      Ex. 2
class Test{                                                            class Test{
public static void main(String []args){                public static void main(String []args){
int x=10;                                                               while(1){
if(x){                                                                     System.out.println(“Hello”);
System.out.println(“Hello”); }
}                                                                            }
else{                                                                      }
System.out.println(“Hello”);
}
}
}
These two programs are valid in case of c & c++, but in java it gives error.
Here both the program will give compilation error “Incompatible Types ” found int, required boolean. Because if and while loop condition needs a boolean value only in case of java, and as java is strongly typed programming language this is not supported in java.

char Literal:
We can specify char literal as single character with in single quotes.
Example:
char ch='a'; // valid
char ch=a; // C.E. Can't find symbol, symbol: variable a, class Test
char ch=”a”; // C.E. Incompatible type found java.lang.String required char
char ch='ab'; //C.E 1 unclosed charcter literal
//C.E 2 unclosed charcter literal
//C.E 3 not a java statement

We can specify char literal as integral literal which represents UNICODE value of the character and that integral literal can be specified either in decimal or octal or hexadecimal forms, But allowed range is 0 to 65535.
Example:
char ch=97; System.out.println(ch); // o/p- a
char ch=0XFace; //valid
char ch=0777; // valid
char ch=65535; //valid
char ch=35536; // Invalid C.E. Possible loss of precesion, found : int required :char

Note: follow www.unicode.org to get all the respected symbol of characters between 0 to 65535.

We can represent char literal in UNICODE representation which is nothing but '\uXXXX' where XXXX stands for 4 digit hexadecimal number.
Example:
char ch='\u0061'; System.out.println(ch); // o/p- a
Every escape character is a valid char literal.
Example:
char ch='\n' // valid
char ch='\t' // valid
char ch='\m' // Invalid C.E Illegal Escape character


Escape character
Description
1
\n
New Line
2
\t
Horizontal Tab
3
\r
Carriage Return
4
\b
Back Space
5
\f
Form Feed
6
\'
Single Quote
7
\''
Double Quote
8
\\
Back Slace
Q. Which of the following are the valid char literal?
char ch=65536; //Invalid due to out of Range
char ch=0XBeer; //Invalid due to r symbol
char ch=\uface; // Invalid due to single quote missed
char ch='\m'; //Invalid C.E. Illegal Escape character
char ch='iface'; //Invalid due to i symbol
char ch='ubeef'; //valid

String Literal:

Any sequence of characters with in double quotes is treated as String Literal.

Example:
String s=”purnachandra”;

1.7 Enhanced features to Literals:

Binary Literal:

For integral data types until 1.6 versions we can specify Literal values in the following ways.
1. Decimal form
2. Octal form
3. Hexadecimal form
But from 1.7 version on wards we can specify Literal values even in binary form also.
Allowed digits are 0 and 1..
Literal value should be prefixed with 0b or 0B.

Example:
int x=0B1111; System.out.println(x); // o/p- 15

Usage of _(underscore) in literal:
From 1.7 version on wards we can use _ symbol between digits of numeric literals.

Example:
double d= 123456789;

double d=1_2_3_456.7_8_9; //Indian standard
double d=123_456.7_8_9; //US standard

The main advantage of this approach is the readability of the code will be improved.

At the time of compilation these underscore symbols will be removed automatically, Hrnce after compilation the above lines ll become

double d=123456.789;
We can use more than one underscore symbol also between the digits.

double d= 1___23_4_5___6.7_8_9;

We can use the underscore symbol only between the digits .If we are using any where else we ll get compile time error.

double d=_1_23_456.7_8_9; //Invalid
double d=1_23_456_/7_8_9; //Invalid
double d= 1_23_456.7_8_9_; //Invalid


Note:
1. 8 byte long value we can assign to 4 byte float variable because both are following different memory representation internally.
float f=10 l;
System.out.println(f); o/p- 10.0

2. char and short data types both occupy same 2 bytes memory space , even though we can't able to store char value in short data type, because char does n't have signed value (-ve value), but byte contain signed values. So the maximum value of char(65535) cant be stored in byte variable.

Data Type

In java every variable and every expression has some type.
Each and every data type is clearly defined .
Every assignment should be checked by compiler for type compatibility.
Because of above reasons, we can conclude java language is strongly typed programming language.

Example:
int x=10.5; (invalid due to java is strongly typed , here the provided value type and expected value type both should be same for achieving strongly type.)
boolean b=0; (invalid due to java is strongly typed , here the provided value type and expected value type ,both should be same for achieving strongly type.)
But these two are valid in C Language as C Language is a loosely typed programming language.

Question: 
Is java a pure object oriented language?

Answer- Yes/No

Yes point of view:- (if u compare with old object oriented language)
As compare to old languages like c++ java has some more oop features like multiple inheritance.
So in a comparison based java is said to be a pure object oriented language.

No point of view:-(If u consider as alone)(Recommended Answer)
Java is not considered as pure object oriented programming language because several oop features are not satisfied by java (like operator overloading, multiple inheritance etc)
Moreover we are depending on primitive data types which are non objects.

Types of Data Types:

Except boolean and char the remaining data types are considered as signed data types because we can represent both positive and negative numbers.

Integral Data Types:

byte:
  1. size= 1 byte= 8 bits
  2. signed data type
Max Value --> +127 Min Value --> -128 Range --> -128 to +127

The most significant bit acts as sign bit.
0 means +ve number and 1 means -ve number.
+ve numbers will be represented directly in the memory where as – ve numbers will be represented in 2's complement form. i.e 2's complement of 01111111 is 10000000 so
1^7 + 0^6 + 0^5 + 0^4 + 0^3 + 0^2 + 0^1 + 0^0= 128 (Hence min -ve value= -128)

Example:
  1. byte b=10; (valid)
  2. byte b=127; (valid)
  3. byte b=128; (invalid, gives compile time error, “possible loss of precession”, found int, required byte)
  4. byte b=10.5; (invalid, gives compile time error,” possible loss of precession”, found double, required byte)
  5. byte b= true; (invalid, gives compile time error, “incompatible type”, found boolean, required byte)
  6. byte b= “purna”; (invalid, gives compile time error, “incompatible type”, found java.lang.String, required byte)
Note: byte is the best choice if we want to handle data in terms of streams either from the file or from the network.(file supported form and network supported form is byte)

short:
  • This is the most rarely used data type in java
  • size=2bytes(16 bits)
  • range= -2^15 to 2^15-1
    = -32768 to 32767
Example:
  1. short s=32767 (valid)
  2. short s=32768 (invalid, gives compile time error, “possible loss of precession”, found int, required short)
  3. short s=10.5 (invalid, gives compile time error, “possible loss of precession”, found double, required short)
  4. short s=true (invalid, gives compile time error, “incompatible type”, found boolean, required short)

Note: short data type is best suitable for 16 bits processors like 8085 but these processors are completely outdated and hence corresponding short data type is also outdated data type.

int:

  • The most commonly used data type in java is int.
  • Size= 4bytes(32bits)
  • Range- -2^31 to 2^31-1 i.e -2,147,483,648 to 2,147,483,647
Example:
  1. int x=2,147,483,647; (valid)
  2. int x=2,147,483,648; (invalid,gives compile time error, “integer number too large”)
  3. int x=2,147,483,648 L;(invalid, gives compile time error, “possible loss of precession”, found long, required int)
  4. int x=true; (invalid, gives compile time error, “incompatible type”, found boolean, required int)

long:

Sometimes int may not enough to hold big values, then we should go for long type.

Example 1: The amount of distance traveled by light in 1000 days, to hold this value int may not enough, we should go for long data type.

Long l=1026000*60*60*24*1000 miles

Example 2: The number of characters present in a big file may exceed int range , hence the return type of length() is long but not int.
File f=new File();
Long l=f.length();

size=8 bytes(64 bits)
Range= -2^63 to 2^63-1

Note: All the above data types (byte,short,int,long) meant for representing integral values.
If we want to represent floating point values , then we should go for floating point data types.

Floating Point Data Types:


float
double
1
size is 4 bytes.
size is 8 bytes
2
if we want 5 to 6 decimal places of accuracy, then we should go for float.
If we want 14 to 15 decimal places of accuracy, then we should go for double.
3
float follows single precission.
double follows double precession.
4
Range: -3.4e38 to 3.4 e38
Range: -1.7e308 to 1.7e308

boolean Data Type:
  • Size not applicable(virtual machine dependent.).
  • Range not applicable(but allowed values are true or false).
Example:
  1. boolean b=true; (valid)
  2. boolean b=0; (invalid, gives compile time error, “incompatible type”, found int, required boolean)
  3. boolean b=True; (invalid, gives compile time error, “can't find symbol”, class Test)
  4. boolean b=”True”; (invalid, gives compile time error, “incompatible type”, found java.lang.String, required boolean)
Ex.1                                                                             Ex. 2
class Test{                                                                   class Test{
public static void main(String []args){                        public static void main(String []args){
int x=10;                                                                       while(1){
if(x){                                                                             System.out.println(“Hello”);
System.out.println(“Hello”);                                        }

else{                                                                          }
System.out.println(“Hello”);
}                                                                                  
}


These two programs are valid in case of c & c++, but in java it gives error.

Here both the program will give compilation error “Incompatible Types ” found int, required boolean. Because if and while loop condition needs a boolean value only in case of java, and as java is strongly typed programming language this is not supported in java.

char Data Type:


size = 2 bytes (in c & c++ it is 1 byte)
Range= 0 to 65535

Question: 
Why char occupies 2 bytes of memory in case of java?

Old languages (c,c++) are ASCII code based and the number of different allowed ASCII characters are less than or equal to 256. To represent these 256 characters 8 bits are enough. Hence the size of char in old languages is 1 byte.

But , Java is UNICODE based and the number of different UNICODE characters are greater than 256 and less than equal to 65536. To represent these many characters 8 bits may not enough , compulsory we should go for 16 bits. Hence the size of char in java is 2 bytes.

Summary of java primitive data types:


Data Type
Size (in byte)
Range
Wrapper class
Default Value
byte
1
-128 to 127
Byte
0
short
2
-32768 to 32767
Short
0
int
4
-2,147,483,648 to 2,147,483,647
Integer
0
long
8
-2^63 to 2^63-1
Long
0
float
4
-3.4e38 to 3.4e38
Float
0
double
8
-1.7e308 to 1.7e308
Double
0.0
char
2
0 to 65535
Character
0.0
(represents space char)
boolean
NA
NA, but allowed values are true and false
Boolean
false

Note: null is the default value for object reference and we can't apply for primitives .
If we are trying to use for primitive, then we ll get compile time error.

Example:
char ch=null; // Incompatible type, found: null type, required: char


Reserve Words


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

Real Example:

“Dog” is a reserve word to represent one type of animal.
“Apple” is a reserve word to represent one type of fruit.
“sleep” is a reserve word to represent one type of action.
“eat” is a reserve word to represent one type of action.

In universe , there are millions of reserved words are there that we are using in our language, but in the language java we need to remember only 53 reserved words.

Note: Total 53 reserved words are there in java

Keywords:for data type: (8)
[ byte,short,int,long,float,double,boolean,char ]

Keywords for flow Control: (11)
[ if,else,switch,case,default,do,while,for,break,continue,return ]

Keywords for Modifiers: (11)
[public,private,protected,static,final,abstract,synchronized,native,strictfp(java 1.2),transient,volatile]

Keywords for Exception Handling: (6)
[ try,catch,finally,throw,throws,assert(java 1.4) ]

Class Related Keyword: (6)
[ class,interface,extends,implements,package,import ]

Object Related Keyword: (6)
[ new,instanceof,super,this ]

Void Return Type Keyword: (1)
[ void ]
In java,return type is mandatory. If a method wo'nt return anything, then we have to declare that method with void return type, But in C langugae return type is optional and the default return type is int.

UnUsed Keywords: (2)
[ goto,const ]

goto - -> usage of goto created several problems in old languages. Hence SUN people banned this keyword in java.
const --> use of final instead of const.

Note: goto and const are unused keywords and if we are trying to use we ll get compile time error.

Reserved Word Literals: (3)
[ true,false,null ]
true,false- values for boolean data type
null- default value for object reference

enum keyword(Introduced in java 1.5): (1)
[ enum ]
We can use enum to define a group of named constants.

Example:

enum month{
JAN,FEB,MAR...DEC;
}

Conclusion:
  1. All 53 reserved words in java contain only lower case alphabet symbols.
  2. In java, we have only new keyword, and there is no delete keyword because destruction of useless object is the responsibility of garbage collector.
  3. The following are new keywords in java.
    strictfp -->introduced in java 1.2
    assert -->introduced in java 1.4
    enum -->introduced in java 1.5
  4. Some confused reserved words are like:
    strictfp but not strictFp
    instanceof but not instanceOf
    const but not constant
    synchronized but not synchronize
    import but not imports
    extends but not extend
    implements but not implement
Question 1
Which of the following list contains java reserved words?

1.new,delete
2.goto,constant
3.break,continue,return,exit,
4.fianl,finally,finalize
5.throw,throws,thrown
6.notify,notifyAll
7.implements,extends,imports
8.sizeof,instanceof
9.instanceOf,strictFp
10.byte,short,Int
11.None of the above

Question 2
Which of the following are java reserved words?
1.public
2.static
3.void
4.main
5.String
6.args