Showing posts with label Fundamentals. Show all posts
Showing posts with label Fundamentals. Show all posts

Sunday, February 8, 2009

Java Identifiers

A name in a java Program is called an Identifier.Which can be used for representing classes,methods , variables and labels.
Rules:
1.Java Identifier is composed of a sequence of charaters,Which each charater may be a letter from a to b or A to B or digit from 0 to 9 or currency symbol ($) or connecting symbol (_).If we use other charater we will get commpail time error saying illegal charater.
2.No identifier starts with the digit.
3.There is no length limit for java identifier ,but SUN highly recommened upto 15 charaters .
4.Identifier in java are casesensitive.
5.we are not allowed to use reserved words as identifier.
6.All predefined java class names ,you are allowed to use as identifiers.
Examples:
Total (√)
total123 (√)
123total (×)
total$ (√)

_total (√)
total# (×)
total_numbers (√)
total-numbers (×)

Java KeyWords

Some identifiers are reserved in Java which has saparate functionality and meaning such type of reserved indentifiers are called reserved words.
53 reserved words are there in java
50 are keywords-----------48 used keywords,2 unused keywords(goto,const)
3 reserved literals----------true,false,null
Keywords for premitive datatypes:
*byte *short *int *long
*float *double *char *boolean
Keywords for fow control:
*if *else *switch *case *default *for
*do *while *break *continue *return
Keywords for Exception Handling:
*try *catch *finally *throw *throws *assert
Keywords for modifiers:
*public *private *protected *static *abstract *strictfp
*final *transient *native *volitle *synchronised
Class related key words:
*class *interface *package
*extends *implements *import
Object related key words:
*new *instanceOf *super *this
Other:
Void
Unused keywords:
*const *goto
Example:
class KeyEx1
{
int goto=10; ←---------------here we will get identifier expected error
}
Reserved literals:
*true *flase *null
New key words in j2SE 1.5:
*enum
All the key words contains only lower case alphabate symbols

Java Data Types

In java any variable has a type ,any express as a type and every type is strictly defind.Compiler will check all asignments for type compatability .Hence java is considered as strong typed language.
Java Language is not considered as pure oop language because some non-object (primitive data types)we have to maintain in our code sun people has interduced wrapper class to convert primitive to object form.

Data type --------------------- Wrapperclass
byte ------------------------- Byte
short ------------------------- Short
char ------------------------- Character
int ------------------------ Integer
float ------------------------ Float
double ----------------------- Double
boolean ---------------------- Boolean
long ----------------------- Long
Primitive types:
Numeric types:
Integral types for whole numbers
byte short int long
Floating point data types:
float double
char for character data type
boolean for logical values
except boolean and char the remaining data types are signed datatypes.i.e we can represent both positive and negative numbers by using numerical datatype.

java byte Datatype :
size---------8bits or 1 byte
range------ -128 to +127
native numbers are represented in 2’s complement form
this data type is best suitable of your handling data in terms of streams from a file or network
byte b=100; (valid)
byte b=200; (invalid)-----PLP found int required byte

short Datatype:
size------------16 bits or 2 bytes
range--------- -2 pow 15 to + 2 pow 15-1 i.e -32768 to 32767
this data type is very rarely used type in java.but best suitable for 16 bit process(these 16 bit processer are completely out dated and hence also the short data type is out dated now a days)

int data type:
size----------- 32 bits or 4bytes
range-------- -2 pow 31 to 2 pow 31-1 i.e -2147483648 to +2147483648
in c language the size of int is varied from platform to platform .the c program written for 32 bit proccesser can not run on 16 bit processor.hence chance of failing of c programe is very high .if we change plaiform. As a result c is not considered as a robust language.
But in the case of java the size of any data type is fixed for any platform . hence chance of failing of java program is very very lass .if we change platform. As a result java is considered as a robust language.

Long datatype:
Size----------64 bits or 8bytes
Range------- -2 pow 63 to 2 pow 63 -1
If int is not enough to hold big values like the amount of distence trvelled by light in 1000 days,we shoud go for long datatype only.
Float datatype:
Size--------------32bits or 4 bytes
Range---------- -3.4e38 to + 3.4e38
For 6 to 7 decimal places of accuracy , we should for float data type.so this is less accuracy.

Double datatype:
Size--------------64bits or 8 bytes
Range---------- -1.7e308 to + 1.7e308
For 14 to 15 decimal places of accuracy , we should for double data type.so this is more accurency.

Boolean datatype:
The size of boolean is not applicable.(it is purely depend on the underlying jvm).range not applicable.
But allowed values are true or flase. TRUE or FALSE are not allowed.

Char datatype:
Size--------------16 bits or 2 bytes.
Range----------- 0 to 65535.
This is to providing unicodes for all the worldwide charater sets.



java Literals


A constant value which can be assigned to a variable is known as Literal.If we are assigning any outside range value for any data type ,we will get a compile time error saying Possible Loss of Precision found int required byte.
For the integral data types (int ,byte,short,long) :we are allowed to specify a literal value of any any one of the following three forms.
---> Decimal literal (normal way)
--->Octa literal (prefixed with 0 )
--->Hexa decimal (prefixed with 0x )

int x=10 ------------> Decimal
int x=010 ------------>Octa
int x=0X10 -------------->Hexa
In the Hexa decimal notation for the extra digits we are allowed to specify either small or upper case a,b,c or A,B,C (this is one of the few places where java is not case sensitive).
Example:
class Sample {
public static void main(String add[]) {
int i = 10;
int j=010;
int k=0x10;
System.out.println( i+”….”+j+”…”+k);
} }
Output: 10,8,16
JVM gives only decimal form as output regardless of input as octa or hexa.
All the integral literals (decimal.octa,hexa) are by default int.
We can specify explicitly a long literal by suffixing l or L.
There is no direct way to specify the short,byte values.
Assigning chart (Possible assignments):
With out final compiler gives error .with final is possible because int has 4 bytes by declaring it final and that literal (10) is with in the size of byte.

int Literal Example:
class Literalone {
public static void main(String ass[]) {
int i='a';
byte b1='b';
char ch='b';
//byte b=ch; ---------->error (PLP found : char required: byte
System.out.println(i); -------------> output is 97
//System.out.println(b);
} }

floating Point Literal:
The floating point literals by default double.
Ex: float f=123.453; ----------> is invalid
Got error as PLP required :float found:double
A floating point literal can be specified as float type by suffixing with f or F
Example:
float f=128.453f or F (valid)
float f=123.456; (not valid)
double d=123.456; (valid)
double d=123.453f; (valid)
double d=123.345d or D; (valid)
A floating point literal can be explicitly double by suffixing with D or d;
float f=123.56d; (not valid)
A floating point literals must always specify in the decimal form only .there is no hexa decimal or octal form.
float f=123.0; (not valid)
float f=123; (valid)
float f= 0123; (valid)
float f=0x123; (valid)
We can assign an integral literal (decimal,octal,hexa) to the float data type directly (*no need to specify the f or F).
We can’t assign a floating point literal to the integral types.
int i=123.34 (not valid)

boolean Literal:
boolean valid literals are true or flase
boolean b=10; (not valid error PLP found:int reqired :boolean)
char literals:
A char literal can be specified as a single charter in single codes.
Ex: char ch=’@’; (valid)
char ch=a; (not valid)
char ch=’ad’; (not valid) error unclosed character literal.
An integral literal which represents the Unicode value of the character.
Ex: char ch=97; output: a
The valid integral literals must be from 0 to 65535.
for the Unicode values which are not sported by the system,we get ‘?’ as output.
char ch=0x(face) (valid)
char ch=ox61; output:1
The Unicode may be in octal /hexa decimal form.
char ch=97 ;
char ch= ‘a’;
char ch= 0x61;
char ch=’\uXXXX’; --------------------->Unicode representation
Ex: char ch=’\u0061’; output=a;
Unicode representation in nothing but \u followed by 4 digit hexadecimal number .(only small u,capital u is not allowed).
char ch=’\uface’; valid output: ?
char ch=’\ubeef’; valid
char ch=\ubeef; invalid ‘ ‘ missed.
char ch=’\ibeef’; invalid u missed.
Escape charater
Ex: char ch=’\b’; valid
char ch=’\t’; valid
char ch=’\n’; valid
char ch=’\f’; valid
char ch=’\k’; not valid
Escape sequences:
unicode value charater
\u0008 backspace
\u0009 horizental tab
\u000a new line
\u000d carriage return
\u000c form feed
\u0027 single quote
\u0022 double quote
\u005c back space

String literal:
Instead of \n and /r we are not allowed to the corresponding unicode charater \u000a and \u000d
Vailation leads to compail time error ever in the comments also.
String s=” laxman scjp”; (valid)
String s=”laxman \n scjp”; (valid)
String s=”laxman \t scjp”; (valid)
String s= “laxman \u0009 scjp”; (valid)
String s= “laxman \u000a scjp”; (not valid) gives error illegal escape character
String s=”laxman \u000d scjp”; (not valid) gives error illegal eacape chracter

Java Variables

Depends on the content hold by the variables are divided into two categories.
1.reference variable
2.primitive variable
reference variable can be used to hold object references.
Ex: String s=”Laxman”;
Here s is a String object
Primitive variable can be used to hold primitive values.
Example: int i=10;
int[][] a={{1,2},{3,4,5},{6,7,8,9},{}};
for(int i=0;i <= a ;i++)
System.out.println(a[i].length);

}
output: 2,3 ,4,0
Depends on the position at which it is declared all the variables divided into 3 categories.
1.instance variables/attributes/member variables
2.static variables
3.local variables
Example:
class Student {
String name;
int rollno;
public static void main(String arg[]) {
Student s=new Student();
}
}


Instance variables:
If the values of the variables are varied from instance to instance3, such type of variables are called instance variables.We can declare instance variables with in class ,but outside of any method or block.These are also known as attributes /properties/member variables.The instance variable will create when ever an object is created and destroyed ,whenever garbage collection destroys this object.Instance variable will get default variable no need to perform ,explicit initialization.

Static variables:
A single copy of the static variable will maintain and shared by all instances .the value of the static variable is the same for the instances.The static variable will create whenever the class loaded into the memory and destroy whenever the class is unloaded from the memory.These variables are also known as fields.
Example:
class Student {
String name;
int rollno;
static String collname;
Public static void main(String arg[]) {
Student s1=new Student();
System.out.println(s1.name); // null
System.out.println(collname); // null
}
}
With out s1 and static Compile time error
Static variables will get default values .No need to perform explicit initialization.
System.out.println(Student.collname);
System.out.println(s1.collname);
Static variables we can access by using either class name (highly recommended) or by using object reference.

Local variables:
The variables which are declared inside a method or block or constructor or as method argument are called local variables.Also known as temporary variables /stack variable/automatic variables.The local variables will create as the part of the method execution and will destroy when ever the method terminates.The local variables never get default values and must be initialized before using that local variable.Violation leads to CTE saying variable I might not have been initialized.

Example:
case1:
class Sample{

public static void main(String arg[]){
int i;
System.out.println(”hello”); // hello
} }
Case2: class Sample{
public static void main(String arg[]) {
int i;
System.out.println(i); // CTE variable I might not have been initialized.
} }
Case3: class Sample {
public static void main(String arg[]) {
int i=10;
System.out.println(i); // 10
} }
Case4: class Sample {
public static void main(String arg[]) {
int i;
if(arg.length>0) {
i=20;
}
System.out.println(i); // error
} }
It is not recommended to initialized local variable with in the logical blocks .(But legal)
Case 5:class Sample {
public static void main(String arg[]) {
int i;
if(arg.length>0) {
i=20;
}
else{
i=40;
}
System.out.println(i); // valid
} }
Case6: class Sample{
int[] a;
public static void main(String arg[]) {
Sample s=new Sample();
System.otu.println(s.a); // null
System.out.println(a) // error
System.out.println(s.a[0]); //RTE ---> null pointer exception
System.out.println(a.length); // RTE ---> null pointer exception
} }
case 7: If we declare as static int [] a;
System.out.println(a) // null
System.out.println(a[0]); //RTE ---> null pointer exception
System.out.println(a.length); // RTE ---> null pointer exception
Case8: static int [] a =new int[6];
public static void main(String arg[]) {
Sample s=new Sample();
System.out.println(a) // [I@add234]
System.out.println(a[0]); //0
System.out.println(a.length); //6
}
case9: class Sample {
public static void main(String arg[]) {
int [] a;
System.out.println(a); // error
System.otu.println(a[0]);
System.out.println(a.length);
} }
case10: class Sample {
public static void main(String arg[]) {
int [] a=new int[6];
System.out.println(a); // [I@add34]
System.out.println(a[0]); // 0
System.out.println(a.length); // 6
} }
Once an array object is created its elements will always get default values.
summarization:
Instance array:
int [] a;
System.out.println(objref.a) //null
System.out.println(objref.a[0]); // null pointer exception
System.out.println(objref.a.length); //null pointer Exception
int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); //6
Static array:
static int [] a;
System.out.println(objref.a); //null
System.out.println(objref.a[0]); // null pointer exception
System.out.println(objref.a.length); //null pointer Exception
static int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); //6
Local array:
int [] a;
System.out.println(objref.a) //CTE
System.out.println(objref.a[0]); // CTE
System.out.println(objref.a.length); //CTE
int [] a=new int[6];
System.out.println(objref.a) //[I@add234]
System.out.println(objref.a[0]); // 0 default value for int
System.out.println(objref.a.length); / /6

Coding Standards

Java coding standards:
Sun recommended the following for the naming conventions.

1.In case of classes:
The first letter should be capitalized and if the several words are linked together to form the name ,the first letter of the inner words should be upper case.
For the classes the names should be nouns .
Ex:Student,Customer ,Employee etc.

2.In case of Interfaces:
For the interfaces the names should be adjective and follows camel case.
Ex:
Runnable .Serializable,cloneable,Comparable,Movable etc

3.In case of Methods:
The first letter should be lower case and then normal camel case rules should be used.
The names should be verb –noun pairs
Ex: getBalance(); doCalculation(0;
setCustomerName();

4.In case of variables:
Like methods the camel case format should be used stating with a lower case letter.
Ex: buttonwidth;
accountBalance
mystring

5.Constants:
java constants are created by marking variables as and final.
They should be named using upper case letter with unscore (_) is the saperator.
Ex: MIN_HIGHT,MAX_HIGHT

Java Beans Naming Conventions:
Java Beans are java classes that have properties.For every property there should be getter and setter methods.
All the properties must be declared as the private (to get security)
For every non – Boolean property will we should have public getXXX() method.
i.e the getter method is no argument method only.
For the Boolean properties we can have setter method public setXXX()

Arrays Decleration Construction initialization

An array is a data structure that defines an indexed collection of fixed number of homogeneous data elements.Once the size of array is fixed there is no chance of increasing or decreasing its size.Array show wonderful performance when compared with the collections.
Declaration of array:
Become name is clearly saperated form the type,first one is the highly recommended way.
At the time of deceleration we are not allowed to specify the size ,violation leads to compail time error.

Array Example:int [] a; (valid)
int[6] a; (not valid)
For deceleration of 2/3 dimensional array
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. b[]; (valid)
int[] a,[]b; (not valid)

int a,b[]; (valid)
int [][]a[]; (valid)


Example:
int []a[]; ------>2 di
int []a[];-------->2di
int []a[],b[]; ------->a is 2 di,b is 2 di
int []a[],[]b[]; --------> //not valid

Construction of arrays:
At the time of construction we should specify the size ,other wise compail time error occures.
i.e int a =new int [6]; (not valid)
int [] a=new int []; (not valid)
int s[]=new int[0]; (valid)
It is legal to have an array with size zero.

Example: int [] a=new int [-6]; (not valid)
We are not allowed to specify the size of the array as nagative number,violation leads to runtime exception saying negative array size exception.
char/short /byte/int b=6;
int [] a=new int [b]; (valid)
long/double/float b=6;
int [] a=new int [b]; (not valid)

  • If we want to specify the size of the array by using some variable ,the allowed data type for that variable are byte,short,char,int(i.e any data type which can be implicitly promoted to the int type).
  • The maximum allowed size for java array is 2147483647.
  • Once an array is created ,all the elements will assign with default values (depends on data types)
Example:
int [] a=new int [6];
0 0 0 0 0 0
Then a -------------------->For int default 0,for string it is null
int [][] a= new int [3][2];
Then a-----------------------> In java the 2 dimensional array is not implemented as the matrix.it is simply an array of arrays.
int [][] a= new int [3][];
a[0] =new int[2];
a[1]=new int[3];
a[2]=new int[4];
so,no need to specify the second dimension in 2d,3d arrays.
Array Examples:
int [][] a=new int[3][2]; (valid)
int [][] a=new int[3][]; (valid)
int [][] a=new int[][2]; (not valid)
int [][] a=new int[][]; (not valid)
Base size should be specified mandatory.

int [][][] a new int [2][][]; (valid)
int [][][] a new int [2][3][]; (valid)
int [][][] a new int [][3][4]; (not valid)

Example:
int[] a=new int [6];
System.out.println(a[0]); -----------> output: 0
boolean[] b=new booleab[3];
System.out.println(b[0]); -------------> output: false
String s=new String [6];
System.out.println(s[0]); -------------->output: null

Example:
int [][] a=new int [2][3];
System.out.println(a[0]); -----------> output: Garbage value[I@add234]
System.out.println(a[0][0]); -----------> output: 0
int [][] a=new int [2];
System.out.println(a[0]); -----------> output: null
System.out.println(a[0][0]); -----------> output: Null Pointer Exception

Initializing an array:
int [] a=new int[3];
a[0]=20;
a[1]=30;
a[2]=40;
a[3]=50 ------> Leads to array index out of bound Exception
If you are accessing an array with invalid index or some -ve index we will get a RTE saying array out of bound exception.
a[4.0]; ---------> leads to compail time error
Deceleration ,construction and initialization in single line:
int [] a;
a=new int [3];
Example:
char[] ch={‘l’,’a’,’x’,’m’,’a’,’n’};
String [] s= {“laxman”,”scjp”};
int [] a;
a ={10,20,30}; ----------------> Leads to compail time error illegal start expression
so Declaration,contraction,initialization must in a single Line.

length Vs length():
length:This is a variable.applicable for only for array objects represents the number of elements or the size of the array.
Ex1:
int a=new int[6];
System.out.println(a.length); ------------------> output: 6
Can’t apply to String
Ex2:
String s=”Laxman”;
System.out.println(s.length);
Given CTE because length variable applicable only for array objects.
length(): It is a final method applicable for string objects.
It represents the number of characters present in the String Object.
Ex:
String s=”Laxman”;
System.out.println(s.length()); ---------> 4
System.out.println(s.length); ---------->error
Anonymous Arrays:
There are name less arrays.
Purpose of these anonymous arrays is just for instant use.
Example:
class Sample {
public static void main(String arg[]) {
System.out.println(sum(new int[]{10,20,30}));
} }
output: 60
While constructing anonymous arrays we are not allowed to specify the size .violation leads to compile time error.
If we want ,we can assign anonymous array for any reference variable.
i.e int [] a=new int[] {10,20,30,40}; ----------> valid

Array Element Assignments:
As array elements we can take any values which can be implicitly promoted to declared type.
int[] a =new int{3};
a[0]=10; -------> valid
a[0]=’a’; -------->valid because char can be implicitly promoted to int type.
a[0]=b; ---------->valid because byte can implicitly promoted to int type.
a[0]=10l; --------->CTE because long can’t be implicitly promoted to int
Here we can give only String objects.
Object[] o=new Object[b];
  • If an array is declared as object reference array we are allowed to assign the objects of either declared type or its child classes.
Array variable Assignments:
Case 1: int [] a={10,20,30};
char [] ch={‘a’,’b’,’c’};
int [] b=ch; -------------->CTE Incompatible types reqired:int[] found:char[]
A char element can be assigned in the place of int element .But we are not allowed to give a char array in the place of int array.
But int [] b=a; ---------> valid
Case 2: int [] a={10,20,30,40};
int [] b={50,60,70};
In this case a=b and b=a, both are valid because while assigning one array to another we have to consider only types irrespective of sizes.
Char ch={‘a’,’b’,’c’,’d’};
a=ch; --------->Incompatable not valid
case 3: int [][] a=new int[2][3];
a[0]=new int [6]; -------> valid
But a[0]=new int [2][3] -------> not valid
Int [][] a=new int[2][];
a[0]=new int[6]; -------> valid
a[0]=10; --------->CTE incompatable types reqired : int[] found : int
a[0]=new int [2][3]; -----------> CTE incompatable types reqired : int[] found : int[][]
case 4: int [] a=new int[6];
System.out.println(a.length); -------------> 6
Int [][] a=new int [3][4];
System.out.println(a.length); -------------> 3
System.out.println(a[0].length); -----------> 4

Java operators

Operators&Assignments:
• increment/decrement
• shift
• arithmetic
• equality(==,!=)
• relational
• bit-wise
• short-circuit
• instanceof
• cast
• conditional(?)
• new
• [ ]

Increment& decrement operators:
• Post Increment ------> y=x++;
• Pre Increment ------> y=++x;
• Post Decrement ------> y=x--;
• Pre Decrement ------> y=--x;

Example: int x=4;
int y=x++;
System.out.println(y); //4 .unexpecompile time errord type.
System.out.println(x); //5

Example: int y=++4;
System.out.println(y); //Compile time error

  • Increment or decrement operators, we can apply Only for variables not for constant expressions. Violation leads to Compile time error saying unexpecompile time errord type Required: variable but found=value.
Ex: int x=4;
int y=++(++x);
System.out.println(y); //COMPILE TIME ERROR
  • we can apply increment/decrement operators for variables only one time. Ie . nesting of increment/decrement operators are not allowed.
Ex: int x=y;
final int x=y;
x++;--- [x=x+1] x++;
System.out.println(x); //5
System.out.println(x); //COMPILE TIME ERROR
  • Increment/decrement operators, we can’t apply for the final variables. Violation leads to compile time error saying can’t assign a values to final.
Ex: double d=10.5;
d++; System.out.println (d); //1.5
  • Increment/decrement operators, we can apply for floating point data types.
Ex: byte b=10;
b=b+1;
System.out.println (b); //compile time error
Possible loss of precession
found: int , required :byte

Ex: byte b=10;
b=b++;
System.out.println (b); //11
i.e automatic typecasting takes place internaly

Ex: byte a=10;
byte b=20;
byte c=a+b;
System.out.println (c); //compile time error
  • if we can perform any arithmetic operation between any 2 variables a and b the result is always max (int, type a, type b )
byte + short=int
char + char=int
int + char=int
int + long=long
doubles + byte=double

Arithmetic OPERATORS:-( + , - , * , / , % )
byte a=10
byte b=20
byte c=a+b; //compile time error plp req:byte
  • If we can perform arithmetic operators b/w any two operands a and b , the result type is, max(int, type a, type b)
Ex: int a=10+’a’ => 10+97=107
double b=10+12.5 => 10.0+12.5=>22.5;
  • For representing infinity, there are no constant ; define in the integer class. Hence 0/0 results is sum time exception saying arithmetic exception
System.out.println(10/0); //Runtime Exception by zero .
System.out.println(10.0/0); //infinity
System.out.println(10.0f/0); //infinity
  • But in the float and double classes for representing infinity constants are defined.
System.out.println (Float. POSITIVE_INFINITY); // infinity
System.out.println( Float NEGATIVE_ INFINITY); //-infinity

final float postive_ infinity ,

final float negative _ infinity are the constants contain in float class.
0/0 is undefined in the Integer class for representing undefined results there is no constant available . Hence 0/0 results arithmetic exception.
0/0 →arithematic exception but in float and double classes for representing
undefined values there is a commands available . public static final float NaN.
NaN→not a number and public static final double NaN

Ex:
System.out.println(0.0 / 0) NaN
System.out.println(Math.sqrt(4)); 2.0
System.out.println(Math. Sqrt(-4)); NaN.
System.out.println(10/0)→ Arithmatic exception
System.out.println(10.0 / 0)→ infinity
System.out.println(-10.0 /0→ - infinitz
System.out.println(0/0) → Arithematic Exception.
System.out.println(0.0/0 → NaN
System.out.println(-10/0) arithmatic exception
System.out.println(-10.0/0)→ -infinity,
System.out.println(-0.0/0)→ NaN.
Float. POSITIVE_INFINITY = = Float. POSITIVE_INFINITY; // true
Float . POSITIVE_INFINITY = =Double. POSITIVE_INFINITY. // true
Float . NaN = =Float. NaN.
Float. NaN >double. NaN }false
Float. NaN !=Float. NaN →true.
  • if one are comparing NaN with any other , including NaN itself, the result is always false, except for not equal(!=)operator.
Arithmetic exception:

1. runtime exception (unchecked)
2. only in the cone of integer arithmetic.
3. / and % only there two operators result in Arithmetic exception.
String concatenation operation:-
‘+’ is the only operator in java which in overloaded. We can one for arithmetic addition and for string concatenation.
String a=”java”.
int b=30;
int c=20;
int d=10;
System.out.println (a+b+c+d);→java302010;
System.out.println(b+a+c+d);→ 30java2010
System.out.println(b+c+d+a); →60java
System.out.println(b+c+a+d);→50java10.

* If at least one operand is of string type then + acts as string concatenation operator other wise + acts as arithematic operator.

SHIFT OPERATORS(1.4 ONLY):-
Left shift (<<)
Right shift ( >>)
Unsigned /zero filling right shift operator ( >>>)
In order to get high resolution of pictures
For compression of data also used these shift operators frequently use in j2me edition.
Left Shift Operator:
a << b shift the bits of a ,b times to the left hand side.
Ex: 8 << 33 then 8 << 33 % 32 = 8 << 1 // result=16
Ex: 8 << - 31 then 8 << -31+32 = 8 << 1 // result= 16



Right Shift Operator:
a>>b shift the bits of a ,b times to the right hand side by filling the left hand side bits with sign bit.
8 >> 1 --> 0000 …….100 = 4.
Filled with sign bit zero.
a >> b =a/2 power b for 8 >> 1 =8/2 power 1 =8/2=4.
If b < 31 then b=b+32
If b >31 then b= b% 32.
- 8 >> 1 ---> -8/2 power 1 = -8/2= -4.

Unsigned Right Shift Operator:
a>>> b , shift the bits of a, b times to the right hand side. By filling left most bits with zero always.If a is +ve ,then there is no difference between right shift and unsigned right shift operator.Except shift distance zero ,the result of unsigned right shift operator is always positive.
I few are applying shift operator between a and b the result type is always max(int type of a)



Case1: byte b=8 >>1; // valid
Case2: int a=8;
byte b=a >> 1; // invalid
Case3: final int a=8;
byte b=a>>1; // valid
Case 4:long c=1;
byte b=8>>c; //invalid (as per max(int,type of a)
In a << ,>> ,>>> b ,If a and b ,both are compile time constants then the compiler won’t go for formula for the result type.If at least one in the variable ,either a or b then the compiler checks the type of the result which is max(int,type of a) , the type b never participated in the result .


Access modifiers

class Modifiers:
Once we are writing a class the access modifier describes the properties of that class .(creation of child class is allowed or not ,creation of object is allowed or not ,we can access this class from outside the package or not and so on).
Access specifiers or Access modifiers are same in case of java.java compiler shows the error related to public,static,.......so on , it use the word modifier not Specifier.
The allowed modifiers for the Top level classes are :
1.public 2.default 3. final 4.abstract 5. strictfp
If we are using other then these modifiers ,compile time error saying modifier some not allowed here.
For the inner classes the following are allowed modifiers:
1.public 2. private 3.protected 4.default 5.final 6.abstract 7.static 8.strictfp



public class:
A public class can be accessed from any where with in the package /outside the package.
package pack1;
public class B
{
System.out.println(“hai”);
}
package pack2
{
import pack1.B;
class A
{
public static void main(String arg[])
{
B b=new B(); // we can access
}

class:
If a class declared as the default ,we are allowed to access that class only with in the current package.If you are trying to access from outside package compilation fails.
package pack1;
class B
{
System.out.println(“hai”);
}
package pack2
{
import pack1.B;
class A
{
public static void main(String arg[])
{
B b=new B(); //we can't access
}
Here class B is is default ,but not public in pack1.So this class can’t be accessed from outside package.
final class:
If a class declared as the final then we are not allowed to create the child class.
Advantage:
We can implement security .
Limitation:As we are not allowed to create the child class,we are missing the key benefits of object oriented programming ,re usability and flexibility.Its not a good programming practice to use final classes in the real time unless security is required.
final method:
If a method declared as the final ,it indicates that this implementation is final implementation.
i.e we are not allowed to override this implementation the child class.
Observations:

  • If a class declared as the abstract ,we should create the child class to provide implementation for abstract methods.
  • If a class declared as the final ,you are not allowed to create the child class.Hence final and abstract combination is illegal for classes.
Example:
class Sample
{
void m1(); //error: missing method body or declaration missing.
public static void main(String arg[])
{
System.out.println(“hai”);
}
}

  • Abstract methods should be overridden in the child class to provide implementation.But final methods are not allowed to override .Hence abstract and final combination is illegal for methods also.
  • A final class never allowed to contain abstract methods .but a final methods is allowed to keep inside abstract class.i,e final method in abstract class is valid But abstract method in final class is not valid.
  • Abstract is the keyword which can be applied for classes and methods only.i.e we can’t use abstract keyword for a variable.
  • final is the keyword which can be applied for classes ,methods and variables.
Strictfp: Strict floating point
  • This keyword we can apply for classes and methods .i.e we can’t apply strictfp for the variables.
  • If a method declared as the strictfp all the floating point calculations inside that method has to follow “IEEE 754” standards so that we will get platform independent result.
  • If a class declared as the strictfp ,all concrete methods in that class has to follow IEE 754 standard for floating point calculations .
  • Abstract and strictfp combination is not-valid for methods .But it is valid combination for the classes.
Not-valid combinations:
abstract and final .
abstract and strictfp
abstract and synchronized
abstract and static
abstract and native
abstract and private.

Method level Modifiers and Variable level Modifiers:
public members:
If a member is declared as public ,we are allowed to access that member from any where with in the package or outside the package.
package pack1;
class A
{
public void m1()
{
System.out.println(“hai”):
}
}
package pack2;
import pack1.A;
class B
{
public static void main(String arg[])
{
A a=new A(); //error
a.m1();
}
}
  • The corresponding class must be visible.Before checking member visibility ,first we have to check class visibility.
  • If class A is declared as public ,then the class B compiles fine and prints “Hai”.
default member:
If a member declared as the default ,that member is visible with in the current package only.
package pack1;
public class A
{
void m1()
{
System.out.println(“hai”):
}
}
package pack2;
import pack1.A;
class B
{
public static void main(String arg[])
{
A a=new A();
a.m1(); //error
}
}
error:m1() is not public in pack1.A.
  • Hence default modifier is also known as package level modifier.
private members:
  • If a member declared as the private we can access with in that class only.i.e from outside the class,you are not allowed to access.
  • It is highly recommended to declare data members as private to achieve security.
protected member:The most misunderstood modifier in java .If a member declared as the protected with in the current package,every where we are allowed to access,but outside the package ,we can access only in the child classes.

protected= + child classes;

Example:
package pack1;
public class A
{
protected void m1()
{
System.out.println(“hai”);
}
}
case 1:
class B
{
public static void main(String arg[])
{
A a=new A();
a.m1(); // hai
}
}
Case 2:
class B extends A
{
public static void main(String arg[])
{
B b=new B();
b.m1(); // hai
}
}
case 3:
A a1=new B();
a1.m1(); //hai
case 4:
B a=new A();
a.m1(); // error
Example:
package pack2;
import pack1.A;
class B extends A
{
public static void main(String arg[])
{
A a=new A();
a.m1();
}
case 2:
B b=new B();
b.m1(); // valid
case 3:
a a1=new B();
a1.m1(); // in-valid
conclusions:
  • The protected members can be accessed with in the current package any where either by using parent class reference or by using child class reference.
  • But from outside package we can access protected member only by using child class reference .
  • If we are using parent class reference to access protected member from outside package we will get a compile time error.
Example:
case 1:
class Sample
{
public static void main(String arg[])
{
Object o=new Object();
o.finalize(); // error
System.out.println(“hai”);
}
}
error :finalize has protected access.
Case 2:
public static void main(String arg[])throws Throwable
{
Sample s=new Sample();
o.finalize(); // valid
System.out.println(“hai”);
}
case 3:
Object o=new Sample();
o.finalize(); //in valid

final variables:
final is the keyword which can be applied for methods classes and variables.
  • Instance and static variables will get default values always .There is no need to perform explicit initialization.
  • But the local variables never get any default values .Before accessing a local variable ,we should perform initialization other wise compile time error.
final instance variables :
For the final instance variables ,we should perform initialization other wise compile time error.
The final instance variable must be initialization before constructor compiles.i.e at the time of declaration or inside instance initialization block or inside constructor.
Example:
final int i;
public static void main(String arg[])
{
Sample s=new Sample()
System.out.println(s.i); // invalid
}

final-static variables:-
Final static variables must be initialized before class loaded into memory. otherwise compile time error. i.e we can perform initialization for the final static variables at one of the following places.
1. at the time of declaration
2. inside the static initialization block
final static int I;
static
{
int i=30;
}

final-local variables:-
Local variables even though we can declared as the final must be initialized before using.
class Sample
{
Public static void main(String args[])
{
final int I;
System.out.println(“hai”);
} // hai
  • For the local variables the only allowed modifier is final.
Example:
class test
{
public static void main(String arg[])
{
final int a; //instead of final we cant write int modifier
System.out.println(“hi”);
}
}

The variables which are declared as the method arguments are simply acts as local variables of that method .hence the only applicable modifier for the logical variables is final. If any formal parameter declared as the final we are not allowed change its value with in the method.
Example:
class test
{
public static void main(String arg[])
{
m1(100,200);
}
}
public static void m1(final int i, final int j)
{
i=200; //error
i=300; //error
}
}

Static Modifier:
  • The keyword static can be use for classes,methods, variables
  • We can not apply static keyword for the top level classes,but we can apply inner classes.
  • For every object a separate copy of instance variables will be created but in the case of static variables a single copy will be created at the class level and shared by all the objects of that class.
Example:
class test
{
int i=10;
static int j=20;
public static void main(string arg[])
{
Test t1=new Test();
t1.i=100;
t1.j=200;
System.out.println(t1.i+’…”+t1.j); //100,200
Test t2=new Test();
System.out.println(t2.i+’…”+t2.j); // 10,200
t2.j=2000;
System.out.println(t1.i+’…”+t1.j); //100,2000
}
}
Most of the cases the keyword static associated with final modifier for defining class level constants.
Non static variables can not be returning form static modifier/ content:
class test
{
int i=10;
public static void main(String arg[])
{
System.out.println(i);
}
}
error: Non static variable I cant be returning static content
example:
1) int i=10;
2) static int i=10;
3)public void m1()
{
System.out.println(i);
}
4) public static void m1()
{
System.out.println(i);
}
Which of the following are not allowed simultaneously in the same class
1) & 3) instance variable can't be accessed from instance area,either instance block, constructors or instance access block

1) & 2) compile time error.. non static variables are instance variables can not be referenced from static constant

2) & 3) , 2) & 4)… static variables can be accessed from any where either from instance area or static area


3)Usually static methods are utility methods and we should provide complete implementation but for abstract methods we are not allowed to provide implementation . Hence abstrace and static combination is illegal for the methods.

4) we can overload static methods.but we can not override

Synchronized Keyword:
  • Synchronized is the keyword which can be apply for method and blocks. i.e we can not apply synchronized keyword for classes and variables.
  • If a method declared as synchronized at a time only one thread is allowed to execute that method on the given object.
Advantages:
1) We can provide thread safety
2) We can avoid data inconsistency problems
Disadvantages:
1)synchronized keyword increases waiting time of threads and hence performance of the system goes down.hence unless and until there is no specific requirement do not use synchronized keyword in the coding.
Note:Synchronized is the keyword which is always talks about implementation but abstract never talks about implementation.Hence synchronized and abstract combination is illegal for the methods.

Native Modifier:
Native is the keyword which can be apply only for methods. i.e we can not apply native keyword for classes and variables.
1) A native method means. The method which is implemented in non-java like c,c++;
2) Native methods are also known as foreign methods.
Advantages of Native method:
1) As the performance of java is low for improving the performance we can depends on c or c++. This stage methods can be helped by native keywords
2) We can communicate legacy systems by using native keyword
Demo:
class NativeEx
{
static
{
System.loadLibraries(“path of native methods library”);
}
native void m1();
}
class Client
{
public static void main(String arg[])
{
Native n=new NativeEx();
n.m1();
}
}

  • For the native methods already implementation is available but abstract method means implementation is not available .hence abstract and native combination is illegal for the methods
  • Native methods already implementation is available we are not providing any implementation. hence nativemethod declaration should be ends with semicolon
  • Native and strictfp combination is illegal for methods because old languages may not fallow IEEE 754 standerd for floating point.
  • We can override a native method
  • We can overload a native method
Transient Keyword:
Transient is the keyword which can be applicable only for variables i.e., we are not allowed to use transient keyword for methods and classes.
Serialization:
The process of saving an object to a file is called serialization Strictly serialization means “The process of converting java supported format object to network supported format object (or) file supported format object is called serialization.
1)If a variable declared as a transient, at the time of serialization JVM ignores the values of that the transient variable. Instead of original values JVM saves default value.
2) Hence transient means not to serialize.
Example:- While saving account information permanently to a file we are not allowed to save passwords for security reasons such type of variables we have to declare by transient keyword
3)We can serialize only serializable objects violation leads to runtime exception saying not serializable exception
4)An object is said to be serializable if an only if the corresponding class implements serializable interface

Transient Example:
import java.io.*;
class Transient Demo implements Serializable
{
int i=10;
int j-20;
public static void main(string args[])throws exception
{
Transient demo t1=new transient demo();
System.out.println(t1.i+”----“+t1.j);
file output stream fos=new file output stream(“abc.txt”);
object output stream oos=new object output stream(fos);
oos.writeobject(t1);
//t1.i=1000
//t1.j=2000
FileInputStream fis=new FileInputStream(“abc.txt”);
ObjectInputStream fis=new ObjectInputStream(fis);
Transient Demo t2=( Transient Demo)ois.writeObject(t1);
System.out.println(“t2.i+”…”+t2.j);

1).If we are not declaring implements serializable we will get a runtime exception not serializable exception
2)if we are not keeping throws exception compile time error saying unreported exception must be called or declared to be thrown

Note:- static variables never part of object state hence we are not participating in the serialization process during a static variables as the transient is useless and there is no impact.

Volatile Keyword:
Volatile is the keyword which can be applicable only for variables i.e we can not use for classes and methods . If the value of the variable is changing frequently such tpe of variables we have to declare with the keyword volatile.
1) For the volatile variables JVM will create a separate private copy for every thread.After completing entire transaction but that thread the final value will be updated in the master copy. So that the value of the volatile variable is always stable
2) At variable level we can achieve synchronization by using volatile keyword
3) For every thread maintaining a separate copy is always difficult .hence performance of the system goes down
4) Volatile means the value keep on changing but final means the value is not allowed to change. Hence volatile and final combination is always illegal. We are not declaring a final variable as volatile.