Java Language Fundamental by Druga Sir
Java Language Fundamental by Druga Sir
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
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
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
Default value is 0L
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
char
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)
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.
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
10 20 30 40 50 60 70 80 90 100 110
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”];
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
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
3) Local level
a) int[] x;
Sopln(obj.x); ===>
Sopln(obj.x[0]) ===> CE: variable x might not have been initialized.
We can call this method by passing a group of 1-D int arrays and x will become 2-D
int array
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
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.
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
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.