0% found this document useful (0 votes)
13 views19 pages

Language Fundamental

Uploaded by

gouthamkumar2201
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

Language Fundamental

Uploaded by

gouthamkumar2201
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

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)

2)Identifiers cant starts with digits:


total123(Valid)
123total(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 .

5)We cant use reserved word as identifiers


int x=10;(Valid)
int if=20;(Invalid)

6)All predefined java class name and interface name ,we can use as identifiers
...................................................................................
................
class Test
{
public static void main(String[] args)

int String =888;


int Runnable=999;
}
...................................................................................
................
Even though it is valid but it is not a good programming practice because it
reduces readiblity and creates confusion.
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
--------------------------------
2)Reserved Word :In Java some words are reserved to represent some meaning and
functionality such type of words are called
reserved words.

Reserved words(53)
Keyword(50)
Reserved Literals(3)true,false,null
Used Keyword(48)if,else,int.......................................etc
UnUsed Keyword(2)goto.const

Keywords for Datatypes: byte,short,int ,long,float,double,boolean,char(8)


Keywords for
FlowControl:if,else,switch,case,default,while,do,for,break,continue,return(11)
Keywords for Modifiers:
public,private,protected,static,final,abstract,synchronized,native,strictfp,transie
nt,volatile(11)
Keywords for Exception Handling: try,catch,finally,throw,throws,assert(6)

Class related Keywords: class,interface,extends,implements,package,import(6)


Object related Keywords:new,instanceof,super,this(4)

Return Type keyword; void

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

enum Keyword(1.5v): We can use enum to define a group of named constants


...................................................................................
..............................................
Ex: enum month
{
JAN,FEB......................DEC;
}
...................................................................................
........................................................

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.

Types Of Primitive DataTypes: Numeric Data Types ,Non-Numeric Data Types

Numeric Data Types: Integral Data Types :byte,short,int,long


Floating point DataTypes:
float,double

Non-Numeric Data Types:char,boolean

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

MSB(Most Significance Bits)act as signed bit.


0 means positive number
1 means negative number
Positive number will be represented directly in the memory whereas negative
number will be represented in twos form compliment

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

NOTE : All the above datatypes (byte,short,int,long meant for representing


integral values if we want to represent floating point
values then we should go for floating point datatypes) .
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------
FLOATING POINT DATATYPES:

5)float : If we want 5 to 6 decimal places of accuracy then we should go for float.


float follows single precision
SIZE=4bytes
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------------
6)double : If we want 14 to 15 decimal places of accuracy then we shoulkd go for
double
double follows double precision
SIZE:8bytes
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------------
7)boolean : SIZE{N A(Virtual Machine Dependent)}
RANGE{N A(But allowed values are true/false)}
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------

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)

Integral Literals :For intergral datatypes (byte,short,int,long) we can specify


literal value in the following ways:
1)Decimal form(Base 10):Allowed digits are 0 to 9;
ex: int x = 10 ;

2)Octal form(Base 8) : Allowed digits are 0 to 7,Literals values should be prefixed


with 0.
Ex: int x = 010;

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.

> Which of the following declaratoin are valid ?


1)int x = 10; T
2)int x = 0786; F
3)int x= 0777; T
4)int x = 0xFace; T
5)int x = 0xBeer; F

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;

We cant assign floating point literals to intrgral types.


double d= 10;
int x=10.0;(C E: possible loss of precision )

We can specify floating point literals even in exponential form(Scientific


notation).
Ex: double d= 1.2e3;
float f=1.2e3;(C E: possible loss of precision )
float f=1.2e3f;
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------------------
BOOLEAN LITERALS :The only allowed values for boolean datatypes are true or false.
boolean b=true;
boolean b=0;(C E: incompatible types)
boolean b=True;(C E :cannot find symbol)
boolean b="true";(C E :incompatible type)

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
---------------------------
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

Every escape characters is a valid char literals


Ex : char ch='\n';
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
------------------------------
String Literals : Any sequence of characters within double quotes is treated as
String literal.
Ex: String s="Adam";

Java 1.7 version Enhancement with respect to literals :


1)Binary Literals : For integral datatypes until .6 version we can specify literal
values in the following ways
Decimal form
Octal forms
Hexadecimal form
But from 1.7 version onwards we can specify literal values even in Binary form
also.Allowed digits are 0 & 1.Literal value should
be prefixed with 0b or 0B.
Ex : int x = 0B1111;=====15
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
------------------------------
Usage of underscore symbol in numeric literals : From 1.7 version onwards we can
use unerscore symbol between digits of
numeric literals .
Ex : double d=123456.789;
double d=1_23_456.7_8_9;
double d=123_456.7_8_9;
The main advantages of this approach is readibility of the code will be improved.
At the time of compilation these underscore symbol
will be removed automatically hence after compilation the above lines will become :
double d=123456.789;
We can use more than 1 underscore symbol under the digits.We can use underscore
symbol only between the digits,if we are using
anywhere else we will get compile time error.
double d=1_23_4_5___6.7__8__9;(valid)
double d=_1_23_4_5___6_.7__8__9_;(Invalid)

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
--------------------------------
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.

Two dimentional array declaration:


int[ ][ ] x;

If we want to specify dimension before the variable that facility is applicable


only for first variable in the declaration.If we are trying to
apply for remaining variables we will get complie time error.
int[ ] [ ]a,[ ]b;(invalid)

Three dimentional array declaration:


int[ ][ ][ ] x;

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];

3)Array Initialisation: Once we create an array every array element by default


intialised with default value.
Ex :
int [ ] x=new int [3];
System.out.println(x);[i@wrrt34trf

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

Ex3: int[ ][ ] x=new int[2][ ];


System.out.println(x);
Sytem.out.println(x[0]);null
Sytem.out.println(x[0][0]);// NullPointerException.
If we are trying to perform any operation on null then we will get ......R E saying
NullPointerException.

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)

6)Array Declaration Creation and Initialisation in a single line: We can


declare ,create and initilised an array in a single line(Shortcut
representation)
Ex: int [ ] ={10,20,30};

We can extend this shortcut for multidimensional array also.


Ex:
int [ ][ ] x={ {10,20} , {30,40,50} };
If we want to use this shortcut compulsory we should perform all activities in a
single line,if we are trying to divide into multiple lines
then we will compile time error.
Ex: int[] x;
x={10,20,30};//CE IllegalStartOfExpression
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
----------------------------
6)length vs length() :
:>length is a final variable applicable for arrays,length variable represents the
size of arrays. //arr.length.
:>length() method is a final method applicable for String objects.Length() return
number of characters presents in the String.

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

We can create multidimensional anonymus array also......new [ ][ ]{{10,20},


{30,40,50}}.

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.

8)Array elements assignment:

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.

Ex: Object[ ] a=new Object[10];


a[0]=new Object();
a[1]=new String("durga");
a[2]=new Integer(10);

Ex 2: Number[ ] n=new Number[10];


n[0]=new Integer(10);
a[1]=new Double(10.0);

CASE 3: For Interface type arrays as arrays elements its implementation class
objects are allowed.

Ex: Runnable[ ] r=new Runnable[10];


r[0]=new Thread();//valid
r[1]=new String("durga");//invalid .....CE incompatible types

-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------
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

Ex: int[ ]a= {10,20,30,40,50};


int[ ] b={60,70};

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.

Ex: int[ ][ ] a=new int [3][ ];


a[0]=new int [4][3];//CE incopatible types

NOTE:Whenever we are assigning one array to another array both dimension and types
must be match but sizes are not
required to match .
===================================================================================
==============================

int[ ][ ] a=new int[4][3];=>5


a[0]=new int[4];=>1
a[1]=new int[2];=>1
a=new int[3][2];=>4

Q.Total how many objects created? 11


Q.Total how many objects eligible for GC? 7
===================================================================================
==============================
-----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------
-------------------------------
TYPES OF VARIABLE :

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

:>Static variables will be stored in method area


:>We can access static variables either by object refrence or by class name but
recomended to use class name
within the class it is not required to use class name and we can access directly

:>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

2)Instance and static variables can be accesed by multiple threads simultainsouly


and hence these are not thread safe
But in the case of local variable for every thread a separate copy will be created
and hence local variable are thread safe

3)Every variable in java should be either instance ,static or local.


Every variable in java should be either primitive or reference hence various
possible combination of variables in java are

instance primitive ||reference


static primitive ||reference
local primitive ||reference
>>>>Uninitialised Array: Once we create an array every array element by default
initilised with default values irrespective whether
it is instance,static,local array.
===================================================================================
===================================================================================
============================================================
Var-args methods(Variable number of arguments method ):Until 1.4 version we cant
declare a method with variable number of
arguments if there is a change in number of arguments compulsory we should go for
new method,it increases length of code
and reduces readibility,to overcome this problem sun people introduced var-args
method in 1.5 version according to this
we can declare a method which can take variable number of arguments such type of
methods are called var-args methods.
We can declare a var-args method as follows

=> void m1(int... s)

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 : We can mix var-args parameter with normal parameters


Ex: m1(String s,int... y )

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

CASE: Equivalence between var-args parameter and one dimensional array:

case1: Wherever 1D array present we can replace with var-args parameter


ex: m1(int[ ] x)=>m1(int... x)
main(String[ ] args)=> main(String... args)

case2: Wherever var-args parameter present we cant replace with 1D array


ex: m1(int... x)=>m1(int[ ] x)
NOTE:
m1(int... x) we can call this method by passing a group of int values and x will
become 1D arrays

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

public static void main(String[ ] args)

public: to call by JVM from anywhere


static: without existing Object also JVM has to call this method
void: main() method wont return anything to JVM
main:This is the name which is configured inside JVM
(String[ ] args): command line arguments

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[ ])

:>Instead of args we can take any valid java identifiers


main(String[ ] adam)

:>We can replace String[ ] with var-args parameter


main(String... args)

:>We can declare main() method with the following modifiers...


>final
>synchronized
>strictfp

static final synchronized strictfp public void main(String... adam)


//valid ..........................................................................
..............

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().

Ex: Java Test A B C //abc us the arguments

The main objectives of commandline arguments is we can customize behaviour of the


main method.

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 classes : Usually class names are Nouns


:>Shoud starts with uppercase characters and if it cintains multiple words every
inner words should starts with upper case characters
Ex: String,StringBuffer,Account,Dog
Coding Standards for Interfaces : Usually interfaces name are Adjectives
:>Should starts with uppercase characters and if it contain multuple words every
inner words start with uppercase.
Ex: Runnable,Serializable

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()

Coding Standards for Variable : Usually variables names are nouns


:>Should starts with lowercase alphabet symbol and if it contains multiple words
then every inner words should starts with
uppercase characters(camelCaseConvention) Ex: name,age,mobileNumber

Coding Standards for Constant :Usually constant names are nouns


:>Should contain inly uppercase characters and if it cintains multiple words then
these words are seperated with _ symbol
Ex: MAX_VALUE,MAX_PRIPORITY,MIN_PRIPORTY

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

public void setName(String name)


{
this.name=name;
}

Syntax for getter method: It should be public method


:>The return type should not be void
:>Method name should prefixed with get
:>It should not take any arguments

public String getname()


{
return name;
}

NOTE :For boolean properties getter method name can be prefixed with either "get"
or "is" but recomended to use "is"

Coding Standards for Listeners:

CASE 1:To register a listeners:


:>Method name should be prefixed with add //Ex: public void
addMyActionListener(MyActionListeners)
CASE 2: To unregister a Listeners:
:>Method name should be prefixed with remove //public void
removeMyactionListener(MyActionListener l)

===================================================================================
=============================
===============================================END=================================
============================

You might also like