Language Fundamental
Language Fundamental
1)Identifier
2)Reserved Words
3)Data Types
4)Literals
5)Arrays
6)Types of Variables
7)Var-args Methods
8)main Methods
9)Command Line Arguments
10)Java Coding Standards
===================================================================================
=========================
1)Identifiers: A name in java program is called identifier which can be used for
identification purpose,it can be method name or
variable name or class name or label name.
1)Rules for defining java indentifiers : The only allowed characters in java
identifiers are A to Z, a to z, 0 to 9 and $ _
If we are using any other characters we will compile time errror
Ex: total_number(Valid)
total# (Invalid)
3)Java identifiers are case sensensative of course java language itself is treated
as case sensentive programming language
.............................................................................
class
{
int number=10;
int Number=10;
int NUMBER=10;
}
...............................................................................
4)There is no length limits for java identifiers ,but it is not recomended to take
too lengthy identifiers .
6)All predefined java class name and interface name ,we can use as identifiers
...................................................................................
................
class Test
{
public static void main(String[] args)
Reserved words(53)
Keyword(50)
Reserved Literals(3)true,false,null
Used Keyword(48)if,else,int.......................................etc
UnUsed Keyword(2)goto.const
In java return type is mandatory ,if a method wont return anything we have to
declare that method with void return type,
Unused Keywords:goto :> Usage of goto created several problem in old languages,and
hence sun people banned this keyword in java
const :> use final instead of const
NOTE:goto and const are unused keywords and if we are trying to use we wil get
compile time error
Reserved Literals: true ,false :> value for boolean data types
null :> for object reference
Conclusions:
1)All 53 reserved words in java contains only lower case alphabet symbols.
2)In java we have only new keyword and there is no delete keyword in java because
destruction of useless objects is the
responsibility of Garbage Collection.
3)The following are new keywords in java: strictfp(1.2v),assert(1.4v),enum(1.5v).
===================================================================================
=======================
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------
3)Data Types: In java every variable and every expression has some type.Each and
every data types is clearly defined,every
assignment should be checked by complier for type compatability.Because of above we
can conculde java language is strongly
typed programming language.
NOTE: Java is not considred as pure object oriented programming language because
several OOPS features are not satisfied by java
Like(Operator overloading,multiple Inhertiance.....etc).Moreover we are depending
on primitive data types which are non-objects.
Except boolean and char remaining datatypes are considred as signed datatypes
because we can represent both positive and
negative numbers.
1)byte: Size=1byte(8bits)
MAX_VALUE: +127
MIN_VALUE: -128
RANGE :-128 to +127
|------|------|-----|------|-------|--------|-------|-------|
msb| 2^6|2^5|2^4| 2^3 |2^2 |2^1 |2^0 |
|------|------|-----|------|-------|--------|-------|-------|
0=+ve|64+32+16+8+4+3+1=
1=-ve
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 or network supported form is byte).
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
------------------------------
2)short :This is the most rarely used data types in Java
Size=2byte(16bits)
MAX_VALUE: +32767
MIN_VALUE: -32768
RANGE :-2^15 to 2^15-1
Short datatype is best suitable for 16bit processor like 8085 but these processor
are completely outdated and hence
corresponding short datatype are also outdated datatype.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------------------
3)int : The most commonly used datatypes in java is int.
Size=4byte(32bits)
MAX_VALUE: +2147483647
MIN_VALUE: -2147483648
RANGE :-2^31 to 2^31-1
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
--------------------------------
4)long : Sometimes int may not enough to hold big values then we should go for long
type.
ex : The amount of distance travelled by light in thousands days,to hold this value
int may not enough we should go for long datatypes
long l=126000*60*60*24*1000 miles.
ex2: The number of character present in a big file may exceed int range hence the
return type of length method is long but not int
long l=f.length();
Size=8byte(64bits)
RANGE :-2^63 to 2^63-1
8)char : Old languages (like C ,C++ are ASCII code based and the numer of different
allowed ASCII code characters are less than or
equal to 256 to represent these 256 characters 8bits are enough
hence the size of char in old languages is 1 Byte).
But java is UNICODE based and the number of different UNICODE
are greater than 256 and <=65536.To represent
these many charactes 8bits maynot enough compuslory we should go
for 16bits,hence the size of char in java is 2bytes.
SIZE: 2Bytes
RANGE: 0 to 65535
NOTE: Null is the default for object reference and we cant apply for primitives.If
we are trying to use for primitive then we will get
compile time error saying( incompatiable type)
===================================================================================
=============================
3)LITERALS : A constant value which can be assigned to the variable is called
literal.
Ex : int x = 10 ;(10 is a constant value or literal)
3)Hexadecimal form(Base 16): Allowed digits are 0 to 9,a to f .For digits(a to f)we
can use both lower case and uppercase
characters.This is one of very few areas where java is not case sensative.The
literals value should be prefixed with(0x or 0X).
Ex: int x=0x10;
These are only possible ways to specify literal value for integral datatypes.
By default every integral literals is of int type but we can specify explicitily as
long type by suffixed with (L,l).
Ex: int x = 10;
long l = 10L;
int x = 10L;(C E: possible loss of precision )
long l = 10;
There is no direct way to specify byte and short literals explicitily but
indirectly we can specify.Whenever we are assigning integral
literals to the byte variable and if the value within the range of byte then
compiler treates it automatically as byte literals similarly
short literals also.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
------------------------------
FLOATING-POINT LITERALS : By default every floating point literals is of double
type and hence we cant assign directly to the
float variable.But we can specify floating point literals as float type by suffixed
with (f,F).
Ex: float f = 123.456;(C E: possible loss of precision )
float f = 123.456F;
double d = 123.456;
We can specify explicitily floating point as double type by suffixed with (d,D).Of
course this convention is not required.
Ex: double d = 123.456D;
float f = 123.456d;(C E: possible loss of precision )
We can specify floating point literals only in decimal and we cant specify in Octal
and Hexadecimal forms.
Ex: double d = 123.456;
double d = 0123.456;(C E: malformed floating point literals)
double d = 0X123.456;
We can assign integral literals directly to floating point variable and that
integral literals can be specified either in ,decimal,octal
or Hexadecimal .
Ex: double d=0786;(C E integral number too large)
double d=0XFace;
double d=0786.0;
double d=0XFace ;
double d=10;
double d=0777;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------------
8)char : We can specify char literals as single charachters within single quotes
char ch = 'a' ;
Ex : char ch='a';
char ch=a;(C E cannot find symbol)
char ch='ab';(C E incompiatible type & not a statement)
We can specify char literal as integral literal which repersents 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.
char ch=0XFace; T
char ch=0777; T
char ch=65535; T
char ch=65536;(C E : possible loss of precision )
we can represent char literal in unicode representation which is nothing but ('\
uxxx')4digit hexadecimal number.
Ex: char ch='\u0061';====a
...................................................................................
...................................................................................
..............................................
Escape Character:
\n = New line
\t = Horizontal
\r = Carriage return
\b = back Space
\f = form feed
\' = single quote
\" = double quote
\\ = back slash symbol
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
--------------------------------
byte -> short and char -> int -> long -> float -> double
NOTE : 8 byte long value we can assign 4byte float variable because both are
following different memory representation internally.
Ex : float f=10L;
===================================================================================
=============================
ARRAYS :
1)Introduction
2)Array Declaration
3)Array Creation
4)Array Initialisation
5)Array Declaration,Array Creation,Array Initialisation in single line
6)length vs length()
7)Anonymous Arrays
8)Array element assignments
9)Array variable assignments
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------
1)Introduction : An array is an indexed collection of fixed number of homogenous
data elements.The main advantages of array is
we can represents huge number of values by using single variable so that
readibility of the code will be improved.
But the main disadvantages of arrays is fixed in size That is once we create an
array there is no chance of increasing or decreasing
the size based on our requirements .Hence to use array concept compulsory we should
know the size in advance ,which may not
possible always.
2)Array Declaration:
One dimentional array declaration:
int[ ] x; Recomemded because name is clrearly seperated from type .
At the time of declaration we cant specify the size otherwise we will get compile
time error.
3)Array creation :Every array in java is an object only hence we can create arrays
by using new operator .
int[ ] a = new int[3] ;
For every array type corresponding classes are avaliable an these classes are part
of java language and not available to the
programmer level. (obj.getClass().getname())
Ex: int [ ] ==[ I
LOOP HOLES :
1)At the time of array creation compulsory we should specify the size otherwise we
will get compile time error.
EX: int[ ] x=new int [6];
2)It is legal to have an array with size 0 in java .
EX : int[ ] x=new int [0];
3)If we are trying to specify arrays size with some negative int value the we will
get runtime excetion saying:
NegativeArraySizeException
4)To specify arrays size the allowed datatypes are (byte,short,char,int) if we are
trying to specify other type then,we will get compile
time error.
int[ ] x = new int [10];
int[ ] x = new int ['a'];
byte b = 10;
int[] x = new int[b];
5)NOTE: The maximum allowed arrays size in java is 2147483647 which is the maximum
value of int data types.
int[ ] x=new int [2147483647];
int[ ] x=new int [2147483648];( RE: integer too large )
Even in the first case we may get runtime exception If suffucient heap memory not
available.
2)2-d Arrays Creation :In java 2D array not implemented by using matrix style ,sun
people followed array of arrays approach for
multi-multidimensional arrays creation .The main advantages of this approach is
memory utilisation will be improved.
Ex-1:
int[ ][ ] x=new int[2][ ];
x[0] =new int [2];
x[1] =new int [3];
Ex 2:
int[ ][ ][ ] x=new int[2][ ][ ];
x[0]=new int[3][ ];
x [0][0]=new int [1];
x[0][1]=new int[2];
int[0][2]=new int [3];
int [0][3]=new int [2];
Whenever we are trying to print any reference variable internally toString() method
will be called which is implemented by default
to return the string in the following form ...............class_name@hashcode_in
_hexadecimal_form.
int [ ][ ] x=new int [ ][ ];
Sytem.out.println(x);// [[I@r48t34
Sytem.out.println(x[0]);// [I@r48tf34t24r5
Once we create an array every array element by default initilised with default
values ,if we are not satisfied with default values
then we can override these values with our customized values.
Ex:
int[ ] x=new int [2];
x[0]=10;
x[1]=20;
x[2]=30;
x[3]=40;//ArrayIndexOutOfBoundsException;
x[-3]=40;//ArrayIndexOutOfBoundsException;
NOTE: If we are trying access with out of range index(either positive or negative
int value then we will get RE saying
ArrayIndexOutOfBoundsException)
String s="Adam";//s.length();====4
NOTE : Length variable is applicable for arrays but not for String objects
Whereas length() is applicable for String objects but not for arrays.
In multidimensional arrays length variable represent only base size but not total
size.
There is no direct way to find total length of multidimensional array but
indirectly we can find as follows:
x[0].length+x[1].length+x[2].length+....................................;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------
7)Anonymus arrays: Sometims we can declare an array without name such type of
nameless arrays are called anonymus arrays.
The main purposes of anonymus arrays is just for instant use(one time usage).
We can create anonymus arrays as follows...........new int[ ] {10,20,30,40};
While creating anonymus we cant specify the size otherwise we will get compile time
error.
new int[3]{10,20,30}//invalid
new int[ ]{10,20,30}//valid
Based on our requirements we can give the name for anonymus array then it is no
longer anonymus .
int[ ] x=new int [ ]{10,20,30};
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------
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 xx : x)
{
total=total+xx;
}
}
}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------
In the above example just to call some method we required an array but after
completing some method call we are not using that array
anymore,hence for this onetime requirements anonymus array is the best choice.
CASE 1: In the case of primitive as array elements we can provide anytype which can
be implicitily promoted to declared type
int [ ] x=new int [5];
x[0]=10;
x[1]='a';
byte,short..............
Ex2: In the case of float type arrays the allowed datatypes are
(byte,short,char,int,long,float)
CASE 2:In the case of object type arrays as array elements we can provide either
declared type objects or its child class objects.
CASE 3: For Interface type arrays as arrays elements its implementation class
objects are allowed.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------
8)Array variable assignment:
CASE 1: Element level promotion are not applicable at array level for Ex: char
element can be promoted to int type whereas char[ ]
can not be promoted to int[ ].
Ex: int[ ] x={10,20,30,40};
char[ ] ch={'a','b','c'};
int[ ] b=x;
int[ ] c=ch;//C E incompatible types.
-----------------------------
String[ ]==>Object[ ];........................................
In the case of Object type arrays child class type arrays can be promoted to parent
class type array.
Ex: String[ ] s={"A","B", "c"};
Object[ ] a=s;
CASE 2: Whenever we are assigning one array to another array internal elements wont
be copied just refrence
variable will be reassigned
a=b;//valid
b=a;//valid
CASE 3: Whenever we are assigning one array the dimension must be matched for ex.in
the place of one dimensional int array
we should provide one dimensional array only if we are trying to provide any other
dimension then we will get compile time error.
NOTE:Whenever we are assigning one array to another array both dimension and types
must be match but sizes are not
required to match .
===================================================================================
==============================
Division one: Based on type of value represented by a variable all variable are
divided into 2 types
1)Primitive variables: Can be used to represent primitive values ex. int x = 10;
2)Reference variable: Can be used to refer objects ex. Student s=new Student();
Division two: Based on position of declaration and behaviour all variables are
divided into 3 types
Instance variable,Static variables,Local variables.
1)Instance variables :
:>If the value of a variable is varied from object to object such type of variable
are called instance variables
:>For every object a seperate copy of instance variable will be created
:>Instance variable should be declared within the class directly but outside of any
method or block or constructor
:>Instance variable will be created at the time of object creation and destroyed at
the time of object destruction,hence the scope of
instance variable is exactly same as the scope of objects.
:>Instances variable will be stored in the Heap memory as a part of objects
:>We cant access instance variables directly from static area but we can access by
using object refrence
:>But we can access instance variables directly from instance area
:>For instance variable JVM will always provide default values and we are not
required initialisation explicitily.
:>Instance variable is also known as object level variables or attributes.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------------------
2)Static variables:
:>If the value of a variable is not varied from object to object the its not
recomended to declare variable as instance variable we
have to declare such type of variable at class level by using static modifiers
:>In the case of instance variables for every object a separate copy will be
created but in the case of static variables a single copy
will be created at class level and shared by every object of the class.
:>Static variables should be decalred within the class directly but outside any
method or block or constructor.
:>Static variables will be created at the time of class loading and destroyed at
the time of class unloading ,hence scope of static
variables is excatly same scope of .class file
JAVA Test:
1)Start JVM
2)Create & Start main Thread
3)Locate Test.class file
4)Load Test.class //static variable creation
5)Execute main() method
6)Unload Test.class //static variables destroyed
7)Terminate main Thread
8)ShutDown JVM
:>We can access static variables directly from both instance and static areas
:>For static variables JVM will provide default values and we are not required to
perform initialisation explicitily
:>Static variables also known as class level variables or fields
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------
2)Local variables :
:>Sometimes to meet temporary requirements of the programmer we can declare
variables inside a method or block or constructor
such type of variables are called local variables or temporary variables,or stack
varibles,or automatic variables.
:>Local variables will be stored inside stack memory
:>Local variables will be created while executing the block in which we declared it
once block execution completes automatically
local variables will be destroyed ,hence the scope of local variables is the block
in which we dedclared it.
:> For local variable JVM wont assign default values compulsory we should perform
initialisation explicitily before using that variable
i.e If we are not using then it is not required to perform initialisation
:> It is not recomemned to perform initialisation for local variables inside
logical blocks because there is no gurentee for excution
of these blocks always at runtime.
:>It is highly recomended to perform initialisation for local variables at the time
of declaration atleast with default values
:>The only applicable modifier for local variable is Final by mistake if we are
trying to apply any other modifier then we will
get compile time error
NOTE: If we are declaring with any modifiers then by default it is default but this
rule is applicable for instance and static variabe
but not for local variable
Conclusions:
1)For instaance and static variable JVm will provide default values and we are not
required to perform initiliastion explicitily
But for local variable JVM wont provide default values compulsory we should perform
initilisation explicitily before using that variable
We can call this method by passing any number of int value including 0 number.
m1();
m1(10);
m1(10,20,30);
Internally var-args parameter will be converted into 1D array hence within the var-
args method we can differenciate value
by using index .
CASE: If we mix normal parameter with var-args parameter the var-args parameters
should be last parameters
Ex: m1(double... d,String s) //invalid
m1(String s,double... d) //valid
CASE: Inside var-args method we can take only one var-args parameter and we cant
take more than one var-args parameter
Ex: m1(int... x,double... d) //invalid
CASE: Inside a class we cant declare var-args method and corresponding 1D array
simultainously otherwise we will get
compile time error saying ......CE cannot declare both m1(int[ ] x) and
m1(int... x) in class Test.
CASE : In general var-args methods will get least priority i.e if no other method
matched then only var-args will get chance
This is exactly same as default case inside the switch
m1(int[ ]... x) we can call this method by passing a group of 1D int arrays and x
wi;; become 2D int array
===================================================================================
==============================
===================================================================================
==============================
===================================================================================
==============================
main() method:Whether class contains main() method or not and whether main method
is declared according to requirements or
not these things wont be checked by compiler at run time JVM is responsible to
check these things
if JVM unable to find main() method then we will get runtime exception saying :
NoSuchMethodError : Main
At runtime JVM always searches for the main method with the following prototype
The above syntax is very strict and if we perform any change then we will get
runtime Exception saying
RE : NoSuchMethodError:main
Even though the above syntax is very strict the following changes are acceptable
:>Instead of public static we can take static public i.e the order of mofdifiers
is not important
:>we can declare String[ ] in any acceptable form.
main(String[ ] args)
main(String [ ]args)
main(String args[ ])
CASE 1: Overloading of the main method is possible but JVM will always call
(String[ ] args)only the other overloaded method we
have to call explicitily like normal method call .
CASE 2: Inheritance concept applicable for main() method hence while executing
child class if child doesnt contain main method
then parent class main method will be executed
CASE 3: It seems overriding applicable for main() method but it is not overriding
and it is ......method hiding.........
NOTE : For main method inheritance and overloading concepts are applicable but
overriding concept is not applicable .Instead of
overriding method hiding is applicable.
===================================================================================
==============================
Main() method Enhancement.........:
:> From 1.7v onwards main method is mandatory to start program execution,hence even
though class contain static block it wont be
executed if the class doesnt contain main method
:>Without writing main() method we cannot print anything on the console even in
static block(it was possible before 1.6v)
===================================================================================
=============================
CommandLine Arguments: The arguments which are passing from command prompt are
called CommandLine Arguments.
With these command line arguments JVM will create an String array and by passing
that array as arguments JVM will call main().
CASE 1: Within main() method commandline arguments are available in String form,if
we want to perform any other operation use
.parseInt(args [0])
CASE 2:Usually space itself is the seperator between commandline arguments if our
commandlin arguments contains a space then
we have to enclose that commandline arguments within double quotes.
===================================================================================
==============================
JAVA CODING STANDARDS: Whenever we are writing java code it highly recomnded to
follow coding standards whenever we are
writing any component its name should reflect the purpose of that
component(funcyionality).
The main advantage of this approach is readibility and maintainability of code will
be improved.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------------
Coding Standards for Methods: Usually methods names are either verbs or verb-noun
combination
:>Should starts with lower case alphabet symbol and if it cintain multiple words
then every inner words should starts with upper case
characters (camelCaseConvention)Ex: print(),sleep(),getname(),SetSalary()
NOTE: Usually we can declare constants with : public static and final
modifiers
Coding Standards for JavaBean : A JavaBean is a simple java class with private
properties and public getter and setter methods.
public class StudentBean //classname ends with beans is not official from SUN
---------------------------------------------------------------------------
Syntax for setter() method : It shouild be public method
:>The return type should be void
:>Method name should prefixed with set
:>It should take some arguments i.e it should not be no arguments method
NOTE :For boolean properties getter method name can be prefixed with either "get"
or "is" but recomended to use "is"
===================================================================================
=============================
===============================================END=================================
============================