Вы находитесь на странице: 1из 48

A name in java is called us identifier, which can be used for identification purpose.

It can be method name, variable name, class name or label name.


Identifier:-All Java components require names. Name used for classes, methods,
interfaces and variables are called Identifier.
Rules for defining java identifiers
1) All java predefined class name and interface name we can used as identifiers.
Even thou it is valid, but it is not good programming practice because it reduced
readability of code.
ex:- class Test
{
p s v m(String args)
{ int String = 888;
int Runnable = 999;
sopln(String);
sopln(Runnable); }
}
2) Reserved words are not used as identifier.
3) Identifiers are case sensitive.
4) No restriction in length of identifier but it is recommended to right small
identifier.
4) Valid identifier are $,_a-z,0-9,A-Z.
5) valid identifier
i) total_number (right)
ii) total# (wrong)
iii)123total (wrong)
iv) ca$h (right)
v) _$_$_$_$_ (right)
vi) all@hands (wrong)
vii) java2Share (right)
viii) Integer(right)
ix) Int(right)
x) int(wrong)
6) All identifiers must start with either a letter( a to z or A to Z ) or currency
character($) or an underscore.

Reserved Words:- Keywords have special meaning to the Java compiler. They help
in identifying a data type name or program construct name.
There are 53 reserved words in java.
1)Reserved words are of two types i)keywords(50) ii)Reserved literals(3)
2) keywords are also of two types
i) Used keywords(48) ex:- if else..... etc. ii) Unused keywords(2) ex:-goto,
const..
3) Reserved Literal (3):- true, false, null..
4) All reserved words in java contains only lower case alphabet symbol.
5) In java only we have new keyword in java and no delete keyword in java
because destruction of useless objext is the responsiblity of garbage collector.
6) Some new keywords in java. strictfp, assert, enum.
7)53 keywords are classified as:----
i) Data Type(8):- byte,int,char,short,float,double,long,boolean.
ii) Flow Control(11):-
if,else,switch,case,default,while,for,break,do,return,continue..
iii) Modifiers(11):-
public,private,protected,abstract,strictfp(1.2v),final,static,native,volatile,transient,
syncronized..
iv) Exception Handling(6):- try,catch,finally,throw,throws,assert(1.4v)....
v) Class (6):- class,interface,extends,implements,package,import..
vi) Objetc(4):- new,instanceof,super,this..
vii) default return type(1):-void.
viii) Unused(2):- const(used final instead of const), goto(create several problem
in old languages, hence some people band this keyword in java)
If we used this keyword we will get compile time error
ix)Reserved Literal(3):- ture,false(value for Boolean datatype), null(default value
for object reference)
x) enum keyword(1.5v):- we can used enum to define a group of named
constants.
ex:- enum Month
{
JAN,FEB.......DEC ;
}
CONCLUSION
1) All 53 reserved words in java contains only lowercase alphabets symbols.
2) In java we have only new keyword and there is no delete keyword because
destruction of useless object is the responsibility of garbage collector.
3) The following are new keywords in java
strictfp 1.2v, enum 1.5v, assert 1.4v
4) strictfp but not StrictFp
instanceof but not instanceOF
synchronized but not synchronize
extends but not extend
implements but not implement
Import but not imports
const but not constant

Q which of the following list contains java reserved words


New, delete
Goto, constant
Break, continue, return, exit
Throw, throws, thrown
Notify, notifyAll
Implements, extends, imports
Sizeof, Instanceof
instanceOf, strictfp
byte, short, Int
none of the above  ANS
--------------------------------------------------------------------------------------------------------------
--------------------------------------------------
DATA TYPE
1) In java every variable and every expression has some type.
Each and every data type is clearly defined.
Each assignment should be checked by compiler for the type
compatibility.
Because of the above reason we can conclude java language I strongly
typed programming language.
2) Java is not considered as pure OOPL because several OOPS feature is not
supported by java (like operator overloading, multiple inheritance etc.)
3) We are depending on primitive DT which are non objects.
Except boolean and char remaining datatype are considered as signed datatype
because we can represent both +ve and -ve numbers.
Data Types in Java

1) Based on the data type of a variable, the operating system allocates memory
and decides what can be stored in the reserved memory. Therefore, by assigning
different data types to variables, you can store integers, decimals, or characters in
these variables.
2) In java, there are two types of data types:
i) Primitive data types
ii) Non-primitive data types

Primitive Data Types


There are eight primitive datatypes supported by Java. Primitive
datatypes are predefined by the language and named by a
keyword. Let us now look into the eight primitive data types in
detail.

byte
 Byte data type is an 8-bit signed two's complement integer.
(1 byte)
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly
in place of integers, since a byte is four times smaller than
an integer.
 Example: byte a = 100, byte b = -50

short
 Short data type is a 16-bit signed two's complement integer
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte
data type. A short is 2 times smaller than an integer
 Default value is 0.
 Example: short s = 10000, short r = -20000

int
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648 (-2^31)
 Maximum value is 2,147,483,647(inclusive) (2^31 -1)
 Integer is generally used as the default data type for integral
values unless there is a concern about memory.
 The default value is 0
 Example: int a = 100000, int b = -200000
long

 Long data type is a 64-bit signed two's complement integer


 Minimum value is -9,223,372,036,854,775,808(-2^63)

 Maximum value is 9,223,372,036,854,775,807


(inclusive)(2^63 -1)
 This type is used when a wider range than int is needed

 Default value is 0L

 Example: long a = 100000L, long b = -200000L

Float
 Float data type is a single-precision 32-bit IEEE 754 floating
point
 Float is mainly used to save memory in large arrays of
floating point numbers
 Default value is 0.0f
 Float data type is never used for precise values such as
currency
 Example: float f1 = 234.5f

double
 double data type is a double-precision 64-bit IEEE 754
floating point
 This data type is generally used as the default data type for
decimal values, generally the default choice
 Double data type should never be used for precise values
such as currency
 Default value is 0.0d
 Example: double d1 = 123.4

boolean

 boolean data type represents one bit of information


 There are only two possible values: true and false
 This data type is used for simple flags that track true/false
conditions
 Default value is false
 Example: boolean one = true
 Boolean b = True(cannot find symbol) and b = “True”;
(incompatible types)
 Int x = 0 If (x){ sopln(“hello”)}else{sopln(“hi”)} (compile
type error)

char

 char data type is a single 16-bit Unicode character


 Minimum value is '\u0000' (or 0)
 Maximum value is '\uffff' (or 65,535 inclusive)
 Char data type is used to store any character
 Example: char letterA = 'A'

Reference Datatypes
 Reference variables are created using defined constructors of
the classes. They are used to access objects. These variables
are declared to be of a specific type that cannot be changed.
For example, Employee, Puppy, etc.
 Class objects and various type of array variables come under
reference datatype.
 Default value of any reference variable is null.
 A reference variable can be used to refer any object of the
declared type or any compatible type.
 Example: Animal animal = new Animal("giraffe");

Possibilities
Byte b = 10; (right)
Byte b = 127; (right)
Byte b = 128; (ce: possible loss of precision
Found: int
Required: byte)
Byte b = 10.5; (ce: possible loss of precision
Found: double
Required: byte)

Byte b = true; (ce: incompatible types


Found: boolean
Required: byte)
Byte b = “durga”; (ce: possible loss of precision
Found: string
Required: byte)
Byte is the best choice if we want to handled data in terms of
streams either from the file or from the network (file
supported form or network supported form is byte).
fos.write(byte[] b);
Short
The most rarely used datatype in java.
Short is used to process data on 16 bit processor in 1995 but
this processor is outdates hence corresponding short data
type is also outdated datatype.
Short s = 32768; (ce: possible loss of precision
Found: double
Required: byte)
Short s = true; (ce: incompatible types
Found: boolean
Required: short)

Int
The most commonly used datatype in java us int.
Int x = 2147483648; (wrong) integer no. too large
Int x = 2147483648l; (wrong) ce: P L P
Int x = ture(wrong) ce: I T
Sometime int is not enough to hold the long value so we
should go for long type.
Long
The return type of length method is long f.length().
In java we can use any language character.(256)

LITERALS
Literal is any constant value which can be assigned to the variable is called literal.
Ex: - int a = 10;
Here 10 is literal.
Integral literals: -
Integral literal: - for integral datatypes (bytes, short, int, long) we can specify literal
value in the following ways: -
i) Decimal Literal: -int x = 1010;
Here base is 10
ii) Octal Literal: - (0-7) int x = 010;
Here Base is 8, prefix with 0
iii) Hexadecimal Literal(0-9,a-f) :- int x =0x10;
Here base is 16, prefix with 0x, lower & uppercase characters
NOTE: - i) This is one of very few areas where java is not case sensitive.

ii) This is only possible way to specify value for integral datatypes.

Exercise: -
Int x = 10;
Int x = 0786; (CE: integer number too large.)
Int x = 0777;
Int x = 0xFace;
Int x = 0xBeef;
Int x = 0xBeer; (CE :)
JVM always print values in integer form.
By default every integral literal is of int type but we can specify explicitly are the
long type by suffix with l,L.ex int x =10 ,long l = 10L; int x= 10l; (error) , long l=10;
There is no direct way to specify byte and short literal explicitly but indirectly
we can specify whenever we are assigning integral literal to the byte variable
and if the value within the range of byte then compiler treats it automatically
as byte literal, similarly short literal also.
FLOATING-POINT LITERALS
By default every fpl is of double type and hence we can’t assign directly to the
float variable, but we can specify floating point literal as float type by suffix with
F or f. ex: float f= 123.456f;
We can specify floating point literal as double type by suffix with
D or f. This convention is not required. Ex: double d= 123.456D;
Exercise: - double d = 123.456 (right) double d= 0123.456 (right) double
d=0x123.456 (malformed floating point literal)
We can specify floating point literal only in decimal form and we can’t specify in
octal and hexadecimal forms.
We can assign integral literal directly to floating point variables under that integral
literal can be specified either decimal, octal and hexadecimal form>
Ex: - double d = 0786(wrong),
double d = 0xface, (right)
double d = 0786.0, (wrong)
double d= 0XFace.0 (wrong),
double d = 10, (right)
double d= 0777; (right)
We can’t assign floating point literals to integral types.
Ex: - double d = 10; (right), int x = 10.0 (wrong).
We can specify floating point literal even in exponential form (scientific notation)
Ex: - double d = 1.2e3,
float f = 1.2e3F,
float f = 1.2e3 (Ce); PLP
BOOLEAN LITERALS: -
Only allowed value for boolean literal is true and false any other value we provide
immediately we will get compile time error.
Int x = 0;
if(x){
Sopln(“HIii”);
}
else
{
Sopln(“hi”)
}
→ CE: incompatible types
CHAR LITERLAS:-
Char ch = ‘ab’; (ce1 unclosed char literal, unclosed char literal, not a statement)
Char ch = a; (cannot find symbol, symbol variable a )
We can specify char literal as integral literal which represents Unicode value of the
character and that integral can be specified either in decimal, octal, hexadecimal
forms but allowed range is 0-65535.
Char ch = 97; (It prints a)
Char ch = 0xFace; (right)
Char ch = 0777; (right)
Char ch = 65535; (right)
Char ch =65536; (Ce: fount int required char)
Char ch = 0xbeer; ( wrong)
Char ch = \uface; (wrong)
Char ch = \ubeef; (right)
Char ch = ‘\m’; (wrong)
Char ch = ‘\iface’; (wrong)
We can represent char literal in Unicode representation which is nothing but
\uxxxx. Xxxx is four digit hexadecimal number.
Ex: char ch = ‘\u0061’; (It prints a)
Every escape character is a valid char literal.
Ex: char ch = ‘\t’; char ch = ‘\n’; char ch = ‘\m’; (illegal escape character)
Escape Character:-
Total 8 escape sequence available in java. They are:-
\n, \t, \b, \r, \f, \’, \’’, \\
String Literal
Any sequence of character within double quotes is treated as string literal.
Ex: String s = “sms”;
1.7v enhancement with respect to literals 1) Binary literals
For integral data type until 1.6v we can specify literal value in the following ways
i) Decimal form ii) Octal form iii) Hexadecimal form but from 1.7v onwards
we can specify literal value even in binary form also.
Allowed digits are 0 and 1. Literal value should be prefixed with 0b or 0B.
Int x = 0B1111; (It will print 15 on screen)
2) Usage of underscore symbol in numeric literals from 1.7v onwards we can use _
symbol between digits of numeric literals. The main advantage of this approach is
readability of the code will be improved. At the time of compilation this
underscore symbol will be removed automatically hence after compilation the
below lines will become double d = 123456.789
Ex: double d = 1_23_456.7_8_9;
i) We can use more than one _ symbol also between the digits.
Ex: double d = 1__23______ _ _4_5__6.7__89
ii) We can use _ symbol only between the digits if we are using anywhere
else we will get compile time error.
Ex: double d = _12_ _4_.56_7_;

8byte long value we can assign 4byte float variable because both are following
different memory representation internally.
Float f = 10l; (answer is 10.0)
ARRAYS IN JAVA:-
Agenda: - -- --
i) Introduction
ii) Array declaration
iii) Array creation
iv) Array Initialization
v) Array declaration creation and initialization in a single line
vi) Length vs. length()
vii) Anonymous arrays
viii) Array elements assignments
ix) Array variable assignments
INTRODUCTION: -
An array is an indexed collection of fixed number of homogenous data elements.
The main advantage of array is we can represent huge number of values by using
single variable so that readability of the code will be improved.
But main disadvantage of arrays is fixed in size that is once we creates an array
there is no chance of increasing or decreasing the size based on our
requirements hence to use arrays concept compulsory we should know the size
in advance , which may not possible always.
Arrays Declaration: -
One dimensional arrays declaration: -
Int[] x; recommended this one. [name is clearly separated from type]
Int [] x;
Int []x; int x[];
At the time of declaration we can’t specify the size otherwise we will get compile
time error.
Two dimensional arrays declaration: -
Int[][] x;
int [][]x;
int x[][];
int[] []x;
int[] x[];
int []x[];
The above all declaration are valid w.r.t two dimensional array.
Identify the dimensions: - - - -
Int[] a, b; a-> 1, b-> 1
Int[] a[],b; a->2 , b-> 1
Int[] a[],b[]; a->2 , b->2
Int[] []a,b; a->2 , b-> 2
Int[] []a,b[]; a->2 , b->3
Int[] []a , []b; compile error
If we want to specify dimension before the variable that facility is applicable only
for first variable in a declaration.
If we are trying to apply for remaining variable we will get compile time error.
Three dimensional arrays declaration: -
Int[][][] a; , int [][][]a; , int a[][][]; , int[] [][]a; , int[] a[][]; , int[] []a[]; , int[][] []a;
Int[][] a[]; , int [][]a[]; , int []a[][];
The above all declaration are valid w.r.t three dimensional array.

Arrays Creation 1-D: -


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 available and this classes are part of
java language and not available to the programmer level.
Ex: int[] a = new [3];

sopln(a.getClass().getName()); [I
ARRAY TYPE CORRESPONDING CLASS
Int[] [I
Int[][] [[I
Double[] [D
Short[] [S
Byte[] [B
Boolean[] [Z
long[] [J
char[] [C
float[] [F

Loopholes of array creation: - -


I) At the time of array creation compulsory we should specify the size
otherwise we will get compile time error.
a) Int[] a = new int[];
II) It is legal to have an array with size 0 in java.
a) Int[] a = new int[0];
III) If we are trying to specify array size with negative int value then we will
get runtime exception saying negativearraysizeexception. Compiler job is
to check whether a int value is available in size place or not. It does not
worry about negative value, it only wants integer value.
Ex: - int x = new int[-4];
IV) To specify array size the allowed datatypes are byte,short,char,int. if we
are trying to specify any other type then we will get compile time error.
Ex: - byte b = 20;
Int[] a = new int[b];
Short s = 30; int[] a = new int[s];
Int[] a = new int[‘a’]; // a value is replace by its correspond Unicode97.
V) The maximum allowed array size in java is 2147483647 which is a
maximum value of int datatype.
Int[] a = new int[2147483647]; // 4 x 2147483647 memory required.
Even in the first case we make a runtimeexception if subsequent heap memory not
available.

Array Creation 2-D: -


In java 2-d array not implemented by using matrix style, sun people followed array
of arrays approach for multidimensional array creation.
The main advantage of this approach is memory utilization will be improved.
Ex: -
I) int[][] x = new int[2][];
X[0] = new [2]; X[1] = new[3]

II) int[][][] x = new int[2][][];


x[0] = new int[3][];
x[0][0] = new int[1];
x[0][1] = new int[2];
x[0][2] = new int[3];
x[1] = new int[2][2];

Which of the following declaration are valid or not?


i) Int[] a = new int[]; // invalid
ii) Int[] a = new int[3]; // valid
iii) Int[][] a = new int[][]; // invalid
iv) Int[][] a = new int[3][]; // valid
v) Int[][] a = new int[][4]; //invalid
vi) Int[][] a = new int[3][4]; // valid
vii) Int[][][] a = new int[3][4][5]; // valid
viii) Int[][][] a = new int[3][4][]; // valid
ix) Int[][][] a = new int[3][][5]; // invalid
x) Int[][][] a = new int[][4][5]; // invalid
ARRAY INITIALIZATION: - -
Once we creates an array every element by default initialized with default values.
i) Int[] x = new int[3];
Sopln(x); // [I@3e25a5
Sopln(x[0]); // o
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: - classname@hashCode_in_hexadecimalform.
ii) Int[][] x = new int[2][3];
Sopln(x); // [[I@Je25a5
Sopln(x[0]); // [I@19821f
S Sopln(x[0][0]); // 0
iii) Int[][] x = new int[2][];
Sopln(x); // [[I@3e25a5
Sopln(x[0]); // RE: nullPointerException
If we are trying to perform any operation on null then we will get runtime
exception saying NullPointerException
iv) int[] x = new int[6];
x[0] = 10;
x[1] = 20;
x[2] = 30;
x[3] = 40;
x[4] = 50;
x[5] = 60;
Once we creates an array every element by default initialized with default values.
If we are not satisfied with default values then we can override this values with our
customized values. X[6] = 70; , x[-6] = 70; // ArrayIndexedOutOfBoundException.
X[2.5] = 90; // compile time error precision lost.
If we are trying to access array elements with out of range index (either positive
or negative int value) then we will get runtime exception
ArrayIndexedOutOfBoundsException.
ARRAY DECLARATION, CREATION and INITIALIZATION IN A SINGLE LINE
i) We can declare create and initialize array in single line (Shortcut
representation). For multidimensional array also.
a) Int[] x = {10,20,30};
b) char[] c = {‘a’,’e’,’i’,’o’,’u’};
c) String[] s = {“A”,”AA”,”AAA”};
ii) int x = { {10,20} , {30,40,50} };
iii) Int[][][] x = { { {10,20,30}, {40,50,60}} , { {70,80}, {90,100,110}}};
a) Sopln(x[0][1][2]); //60
b) Sopln(x[1][0][1]); //80
c) Sopln(x[2][0][0]); //RE: AIOOBE
d) Sopln(x[1][2][0]); //RE:AIOOBE
e) Sopln(x[1][1][1]); //100
f) Sopln(x[2][1][0]); //RE: AIOOBE

10 20 30 40 50 60 70 80 90 100 110

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 line then we will get compile
time error.
Int[] x;
CE: illegal start of expression, not a java statement.
LENGTH VS LENGTH()
Length is a final variable applicable for arrays. Length variable represents the size
of the array.
EX: int[] x = new int[6];
Sopln(x.length()); //can’t find symbol location: class int,symbol method length()
Sopln(x.length); //6
Length method is a final method applicable for string objects. Length method
returns number of characters present in the string.
NOTE: - length variable applicable for arrays but not for string objects, whereas
length method applicable for string objects but not for arrays.
String[] s = {“A”,”AA”,”AAA”};
i) Sopln(s.length); // 3
ii) Sopln(s.length()); // CE: cannot find symbol length()
iii) Sopln(s[0].length); // CE: cannot find symbol variable length
iv) Sopln(s[0].length()); // 1
In multidimensional array length variable represents only base size but not total
size. Int[][] x = new[6][3];
i) Sopln(s.length); // 6
ii) Sopln(s[0].length); // 3
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….
ANNONYMOUS ARRAY
Sometimes we can declare an array without name such type of nameless arrays
are called anonymous array.
The main purpose of anonymous array is just for instance use. (One time usage).
Example: - class Test
{ public static void main (String[] args)
{
Sum (new int[]{10,20,30,40});
}
Public static void sum(int[] x)
{
Int total = 0;
For(int x1 : x) {
Total = total +x1;
}
Sopln(“The sum is ” + total); }
}

No need to declare a size of anonymous array.


We can create multidimensional anonymous array also.
New int[][] {{10,20},{30,40,50}};
Based on our requirement we can give the name for anonymous array then it is no
longer anonymous. Int[] x =new int[]{10,20,30};
ARRAY ELEMENTS ASSIGNMENTS
CASE: --- 1
EX: 1
In the case of primitive type arrays as array element we can provide any type
which can be implicitly promoted to declare typed.
Int[] x = new int[5];
X[0] = 10;
X[1] = ‘a’;
Byte b = 20;
X[2] = b;
Short s = 30;
X[3] = s;
X [4] = 10l; //error possible loss of precision
EX: 2
In case of float array the possible datatype are byte, int, char, byte, short, long.
CASE: --- 2
EX: 1 Object[] a = new object[10];
A[0] = new Object();
A[1] = new String(“durga”);
A[2] = new Integer(10);
EX: 2 Number[] a = new Number[10];
A[0] = new Integer();
A[1] = new Double(10.5);
A[2] = new Integer(“sms”); →CE: incompatible types

In the case of object type arrays as array elements we can provide either declared
type object or its child class object.
CASE: --- 3
For interface type arrays as array elements its implementation class objects are
allowed.
EX: - 1
Runnable[] r = new Runnable[10];
R[0] = new Thread();
R[1] = new String(“durga”); //error incompatible types
CASE: --- 4
Abstract class type array allowed child class object.
EX 1: - Number n = new Number[10];
N[0] = new Integer(10);
N[1] = new Double[10.5];
N[2] = new String[“durga”];

ARRAY VARIABLES ASSIGNMENTS


CASE: --- 1
Element level promotion are not applicable at array level.
Ex:- char element can be promoted to int type whereas char array cannot be
promoted to int array.
Char[] ch = {‘a’,’b’,’c’,’d’};
Int[] x = {10,20,30,04};
Int[] b = x; //right
Int[] c = ch; //wrong

Q:- Which of the following promotion are valid?


Charint //right
Char[] int[] //wrong
Intdouble //right
Int[] double[] //wrong
Float  int //wrong
Float[]  int[] //wrong
String  Object //right
String[]  Object[] //right
But in the case of object type arrays child class type array can be promoted to
parent class type array.
String s = {“A”,”B”,”C”};
Object[] a = s; // valid
CASE: --- 2
Whenever we are assigning one array to another array internal elements wont be
copied just reference variable will be reassigned.
Int[] a = {1,2,3,46,6,8};
Int[] b = {10,20};
a= b; //valid
b = a; // valid
CASE: --- 3
Whenever we are assigning one array to another array the dimensioned must be
matched.
Ex:- 1-D int array we should provide 1-D array only. If we are trying to provide any
other dimensions then we will get compile time error.
Int[][] a = new [3][];
A[0] = new Int[4][3]; //CE
A[0] = 10; //CE
A[0] = new Int[2];
Whenever we are assigning one array to another array both dimension and type
must be matched but the sizes are not required to match.

COMMAND LINE STRING ARRAY


EX: ---1
Class test
{
P s v m (String[] args)
{
For(i=0; I<=args.length; i++ )
{
s.o.pln(args[i]);
}
}
}
Java test A B C
A
B
C
RE: AIBOOE
Java test A B
A
B
RE: AIOOBE
Java Test
RE: AIBOOE

EX: ---2
Class test
{
P s v m (String[] args)
{
String argh= {“x”,”y”,”z”};
Args = argh;
For (String s: args)
{ s.o.pln(s); }
} }
In all cases we are getting x y z only.

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

Q1: Total how many object created


A:  11
Q2: total how many objects are responsible for garbage collection?
A: 7

TYPES OF VARIABLES
DIVISION 1
Based on type of value represented by a variable all variables are divided into 2
types.
a) primitive variables: int, short…..
Can be used to represent primitive values.
b) Reference variables:
Can be used to refer objects. Student s = new Student[];

DIVISION 2
Based on position of declaration and behaviour all variables are divided into 3
types.
a) instance variable b) static variable c) local variables.
→ 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 separate copy of instance variable will be created.
Should be declared within the class directly but outside of any method,
constructor or block.
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
object.
Will be stored in the heap memory as a part of object.
We can’t access iv directly from static area but we can access by using object
reference.
We can access iv directly from instance area.
For iv JVM will always provide default values and we are not required to perform
initialization explicitly.
Iv also known as object level variables or attributes.

→ Static Variable
if the value of a variable not varied from object to object then it is not
recommended to declare variable as instance variable. We have to declare such
type of variables at class level by using static modifier.
In the case of iv for every object a separate copy will be created but in case the of
sv a single copy will be created at class level and shared by every object of the
class.
SV should be declared within the class directly but outside of any method or block
or constructor.
SV will be created at the time class loading and destroyed at the time of class
unloading. Hence scope of sv is exactly same as scope of .class file.
HOW PROGRAM RUN
Java Test
1) Start JVM
2) create and start main thread
3) Locate Test.class file
4) Load Test.class
5) Execute main() method
6) unload Test.class
7) Terminate main thread
8) Shutdown JVM
SV will be stored in method area.
We can access sv either by object reference or by class name but recommended to
use class name. Within the same class it is not required to use class name and we
can access directly.
We can access sv directly from both instance and static area.
For sv JVM will provide default values and we are not required to perform
initialization explicitly.
SV also knowns as class level variables or fields.

→ 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 variables or automatic variables.
LV will be stored inside stack memory.
LV 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 declared it.
If access outside block CE: cannot find symbol
If not perform intialization CE: variable xx might not have been initialized
For LV JVM wont provide default values compulsory we should perform
initialization explicitly before using that variable.
The only applicable modifier for local variable is final by mistake if we are trying to
apply any other modifier then we will get CE. Illegal start of expression.
NOTE: If we are not declaring with any modifier then by default it is default but
this rule applicable only for iv and sv not for lv.

SUMMARY
1) For iv and sv JVM will provide default values and we are not required to perform
initialization explicitly but for lv jvm wont provide default values compulsory we
should perform initialization before using it.
2) IV and SV can be accessed by multiple threads simultaneously and hence this
are not thread safe but in the case of LV for every thread a separate copy will be
created and hence lv are thread-safe.
3) Possible combination of variables
instance primitive, instance reference.
static primitive, static reference.
local primitive, local reference.
Every variable in java should either instance or static or local.
Every variable in java should be either primitive or reference.
Hence various possible combinations of variables in java are above.
Example
class Test{
int[] x;
p s v main (S[] args){
Test t = new Test();
Sopln(t.x); ===> null
Sopln(t.x[0]) ===> RE: NPE
}
}

1) Instance level
a) int[] x;
Sopln(obj.x); ===> null
Sopln(obj.x[0]) ===> RE: NPE
b) int[] x = new int[3];
Sopln(obj.x); ===> [Ie343dsd
Sopln(obj.x[0]) ===> 0

2) Static level
a) staic int[] x;
Sopln(obj.x); ===> null
Sopln(obj.x[0]) ===> RE: NPE

b) static int[] x = new int[3];


Sopln(obj.x); ===> [Ie343dsd
Sopln(obj.x[0]) ===> 0

3) Local level
a) int[] x;
Sopln(obj.x); ===>
Sopln(obj.x[0]) ===> CE: variable x might not have been initialized.

b) int[] x = new int[3];


Sopln(obj.x); ===> [Ie343dsd
Sopln(obj.x[0]) ===> 0
Once we create an every array elements by default initialized with default values
irrespective of IA, LA, SA.

VAR ARG METHODS.


(Variable number of argument method)
Until 1.4v we cant declare with variable no of arguments if there is a change in no.
of argument compulsory we should go for new method, it increases length of the
code, and reduces readability.
TO overcome this problem sun people introduced var-arg methods in 1.5v a/c to
this we can declare a method which can take variable no. of arguments. Such type
of methods are called var-arg methods.
Within the var arg method we can differentiate values by using index.
Which are the following are valid var-arg method declaration:
CASE 2:
WE can mix var-arg parameter with normal parameter.
m1(int x, int… y)
m1(String s, double… y)
Case: 3
If we mix normal parameter with var-arg parameter then var-arg parameter should
be last parameter.
m1(String... s. double d) {invalid}
Case: 4
Inside var-arg method we can take only 1 var-arg parameter and we can’t take
more than one var-arg parameter.
m1(int… x, double… d) [invalid]
case: 5
Inside a class we can’t declare var-arg method and correspondin 1-d array method
simultaneously otherwise we will get CTE; eg
case : 6
class Test{
p s v m1(int… x) { Sopln(“var-arg method”);}
p s v m1(int x){Sopln(“General purpose method”);}
p s v main(S[] args) {
m1(); //var-arg
m1(10,20) //var-arg
m1(10); // general
}
}
if there is a competition between old and new concept then old is always going to
win.

EQUIVALENCE b/w var-arg parameter and 1-D array parameter


m1(int[] x) m1(int… x)

m1(new int[]{10}); (right) (right)

m1(new int[]{10,20}); (right) (right)

m1(new int[]{10,20,30});(right) (right)

m1(int[] x) ==> m1(int… x)


main(String[] args) ===> main(String… args)
Wherever var-arg parameter present we can’t replace with 1-D array.
m1(int… x) ==> m1(int[] x) [invalid]

We can call this method by passing a group of 1-D int arrays and x will become 2-D
int array

COMMAND LINE ARGUMENT


The argument which are passing from CMP are called CLA.
With this command line argument JVM will create an array and by
passing that array as argument JVM will call main method.
Java Test A B C
The main objective of command line argument (CLA) is we can
customized behaviour of the main method.
Eg:
class Test{
public static void main(String[] args){
int n = Integer.parseInt(args[0]);
System.out.println(“The square of ”+n+” is ”+(n*n));
}
}
Eg:-2
class Test{
public static void main(String[] args){
String[] argh = {“a”,”b”,”c”};
args = argh;
for(String S: args){
Sopln(s); }
}
}
Within main method CLA are available in String form.
EG;-3
class Test{
public static void main(String[] args){
System.out.println(args[0]+args[1]); == String concatenation
}
}
Usually space itself is the separater between CLA if our CLA itself
contains space then we have to enclosed that CLA within “”

Main Method
Whether class contain main method or not and whether main
method is declared a/c to requirement or not this things wont be
checked by compiler at runtime JVM is responsible to check this
things, if JVM unable to find main method then we will get
RuntimeException saying: NoSuchMethodError : main
class Test {}
Javac Test.java (right)
Java Test
RE: NoSuchMethodError : main

Syntax OF MAIN METHOD


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 won’t return anything to JVM.
→ main: This is the name which is configure inside JVM.
→ String[] args: Command Line Arguments
The above syntax is very strict and if we perform any change then
we will get RE: NoSuchMethodError: main

Changes in Syntax of Main method


Even though above syntax is very strict the following changes are
acceptable
1) static public
instead of public static we can take above. That is the order of
modifier is not important
2) We can declare String array in any acceptable form.
main(String[] args)
main(String []args)
main(String args[])
3) Instead of args we can take any valid java identifier.
main(String sms[])
4) We can replace String[] with var-arg parameter
main(String… args)

We can declare main method with the following modifiers


→ final, synchronized, strictfp
static final synchronized strictfp public void main(String… sms)
Which of the following valid declaration of main method.
→ public static void main(String args) [wrong]
→ public static void Main(String[] args) [wrong]
→ public void main(String[] args) [wrong]
→ public static int main(String[] args) [wrong]
→ final synchronized strictfp public void main(String[] args) [w]
→ final synchronized strictfp public static void main(String[] args)
[right]
→ public static void main(String... args) [right]
==> We won’t get compile time error anywhere but except last 2
cases in remaining we will get RE: NoSuchMethodError: main

CASE:- 1
→ Overloading of main method
overloading of the main method is possible but JVM will always
call String[] argument main method only. The other overloaded
method we have to call explicitly like normal method call.
Class Test{
p s v main(S[] args) {
Sopln(“String[]);
}
p s v main(int[] args){
Sopln(“int[]”);
}
}

CASE:-2
Inheritance concept is applicable for main method hence while
executing child class if child doesn't contain main method then
parent class main method will be executed.
class P {
p s v main(String[] args){
Sopln(“parent main”);
}
}
class c extend P{

}
Javac P.java
1) P.class
2) c.class
java p
O/P: Parent main
java c
O/P: Parent main

CASE:-3
It seems overriding concept applicable for main method but it is
not overriding and it is method hiding.
class P {
p s v main(String[] args){
Sopln(“parent main”);
}
}
class c extend P{
p s v main(String[] args){
Sopln(“child main”);
}
Note:- For main method inheritance and overloading concept are
applicable but overriding concept is not applicable. Instead of
overriding it is method hiding.

1.7v Enhancement with respect to main


method
CASE:-1
Until 1.6v if the class doesn’t contain method then we will get
RE: saying NoSuchMethodError: main, but from 1.7v onwards
instead of NoSuchMethodError we will get more elaborated error
information.
Example
class Test{}
1.6v
javac Test.java
java Test
RE: NoSuchMethodError: main
1.7v
javac Test.java
java Test
Error: Main method is not found in class Test, please declared
main method as:
public static void main(String[] args)

CASE:- 2
From 1.7v onwards main method is mandatory to start program
execution even though class contains static block it won’t be
executed if the class doesn’t contain main method.
class Test{
static
{ Sopln(“static block”); }
}
1.6v
javac Test.java
java Test
O/P:- Static block
RE: NoSuchMethodError: main
1.7v
javac Test.java
java Test
Error: Main method is not found in class Test, please declared
main method as:
public static void main(String[] args)
CASE:- 2
class Test{
static
{ Sopln(“static block”);
System.exit(0);
}
}
1.6v
javac Test.java
java Test
O/P:- Static block
1.7v
javac Test.java
java Test
Error: Main method is not found in class Test, please declared
main method as:

CASE:- 3
class Test{
static
{ Sopln(“static block”);
}
p s v main(S[] args) {
Sopln(“Main method”); }
}
same in 1.6v and 1.7v
O/P:- static block
main method

Control flow in 1.6v and 1.7v


1.6v
1) identification of static members.
2) execute static block & static variable assignments.
3) check for main()
a) if available
4) Execute main
b) if not available
NoSuchMethodError: main

1.7v
1) Check for main()
a) if not available
Error: Main method is not found in class Test, please declared
main method as:
b) if found main method
2) identification of static members
3) Execution of static variable assignment & static block
4) execute main method
WITHOUT MAIN METHOD IT IS POSSIBLE TO PRINT SOME
STM?
By using static block but this rule is applicable until 1.6v but from
1.7v onward it is impossible to print some STM to the console
without writing main method.

JAVA CODING STANDARDS


Whenever we are writing java code it is highly recommended to
follow coding standards.
Whenever we are writing any component its name should reflect
its purpose of the component (Functionality)
The main advantage of this approach is readability and
maintainability of the code will be improved.
-→Class
Usually class names are nouns should starts with Uppercase
character and if it contains multiple words every inner word
should starts with Uppercase character
eg: String, StringBuffer
→ Coding standard for inteface
Usually interface names are adjectives.
Should starts with Uppercase character and if it contain multiple
words every inner words should starts with uppercase character.
Eg: Runnable, Comparable etc.
→ Coding standard for methods
Usually methods name are either verbs or verb-noun combination
should starts with Lowercase alphabet symbol and if it contain
multiple words then every inner word should starts with
Uppercase character. (camel case convention)
eg:- sleep(), print(), run() etc
→ Coding standard for variables
Usually variable names are nouns should starts with Lowercase
alphabet symbol and if it contain multiple words then every inner
word should starts with Uppercase character. (camel case
convention).
Eg:- name, number.
→ Coding standard for constants
Usually constants names are nouns should contain only Uppercase
character and if it contain multiple words then every inner word
then this word are separated with _ symbol. (camel case
convention).
Usually we can declare constant with public, static and final
modifier.
Eg:- MIN_VALUE, PI etc.
→ Java Bean coding standard
A java bean is a simple java class with private properties and
public getter & setter methods.
StudentBean → ends with bean is not official convention from
sun.
→ Syntax for setter methods
1) return type should be void
2) method name should be prefixed with set.
3) it should takes some argument that is it should not be no
argument method.
Public void setName(String name)

→ Syntax for getter method


1) it should be public method
2) return type should not be void.
3) method name should prefixed with get.
4) It should not take any argument.
For Boolean properties getter method name can be prefixed with
either get or is, but recommended to use is.
→ Coding standard for listener.
CASE:-1
To register a listener
method name should be prefixed with add
public void addMyActionListener(MyActionListener l) [right]
public void regiterMyActionListener(MyActionListener l) [wrong]
public void addMyActionListener(ActionListener l) [wrong]
CASE:-2
Method name should be prefixed with remove.
public void removeMyActionListener(MyActionListener l) [right]
public void unRegisterMyActionListener(MyActionListener l)
[wrong]
public void removeMyActionListener(ActionListener l) [wrong]
public void deleteMyActionListener(MyActionListener l) [wrong]