Chapter 1) Language Fundamentals
Chapter 1) Language Fundamentals
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the
year 1995. James Gosling is known as the father of Java.
Java Platforms
Features of java
Object-Oriented
Java is an object-oriented programming language. Object-oriented programming is a
methodology in which application program can be develop using class and object. So it
simplifies software development and maintenance by providing some rules.
Platform Independent
Java is platform independent programming language. Which is a write once, run
anywhere language. Java source code can be executed on multiple platforms. for example,
Windows, Linux, Mac/OS, etc
Java source code is compiled by the compiler and converted into bytecode. This bytecode
is a platform-independent code because it can be run on multiple platforms by the Java
Virtual Machine.
1
Difference between Java and C++
C++ Java
C++ is mainly used for system programming. Java is mainly used for application programming.
It is widely used in console based application,
web application and mobile application.
C++ uses compiler only which converts source Java uses both compiler and interpreter. Java
code into machine code. source code is converted into bytecode at
compilation time. The interpreter executes this
bytecode at runtime.
C++ supports both call by value and call by Java supports call by value only. There is no call
reference. by reference in java.
Components Of Java
What is the JVM in Java ?
JVM stands for Java Virtual Machine is an abstract machine. It is called a virtual machine
because it doesn't physically exist. It is a specification that provides a runtime environment
in which Java bytecode can be executed. It can also run those programs which are written in
other languages and compiled to Java bytecode.
Java Virtual Machine are available for many hardware and software platforms. Java
Virtual Machine, Java Runtime Environment, and Java Development Kit are platform
dependent because the configuration of each Operating System is different from each other.
However, Java is platform independent.
The Java Virtual Machine performs Loads code, Verifies code Executes code Provides
runtime environment.
2
What is the JRE in Java ?
JRE stands for Java Runtime Environment. It is a set of software tools which are used for
developing Java applications. It is used to provide the runtime environment. It is the
implementation of Java Virtual Machine. It contains a set of libraries and other files that Java
Virtual Machine uses at runtime.
The Java Development Kit contains is a Java Virtual Machine (JVM), Java Runtime
Environment (JRE), java interpreter and java compiler etc.
3
Chapter 1) Language Fundamentals
Tokens Of Java
Identifiers
A name in java program is called identifier. which can be used for identification purposes. it
can be variable name, method name or class name.
4
Reserved words
Reserved words are predefined words to represent a meaning and functionality such type of
word are called reserved words.
1) byte
2) short
3) int
4) long
5) float
6) double
7) char
8) boolean
1) if
2) else
3) switch
4) case
5) default
6) while
7) for
8) do
9) break
10) continue
11) return
5
Keywords for modifiers (11)
1) public
2) private
3) protected
4) static
5) final
6) abstract
7) synchronized
8) native
9) strictfp (1.2 version)
10) transient
11) volatile
1) try
2) catch
3) finally
4) throw
5) throws
6) assert (1.4 version)
1) class
2) package
3) import
4) extends
5) implements
6) interface
1) new
2) instanceof
3) super
4) this
Void return type : If a method won't return anything compulsory that method should be declared
with the void return type.
1) void
6
Data Types
Data type are used to define type of variable and size of variable. There are two types of data types in
Java.
1) Primitive Data Types : Primitive type are predefined by the language and is named by a
reserved keyword.
2) Non-Primitive Data Types : Non-Primitive type are user-defined data types created by
programar or developer.
• Except Boolean and char remaining data types are considered as signed data types because
we can represent both "+ve" and"-ve" numbers.
1. Integral data
byte b = 10.50;
C.E :
Possible loss of precision
Found : double
Required : byte
7
byte b = true;
C.E :
Incompatible types
Found : boolean
Required : byte
byte b = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : byte
2. Short :
Size : 2 byte
Maxvalue : + 32767
Minvalue : - 32768
Range : - 32768 to 32767
Example :
✓ Short s = 10;
✓ Short s = 32767;
Short s = -32768;
C.E :
Possible loss of precision
Found : int
Required : Short
Short s = 10.50;
C.E :
Possible loss of precision
Found : double
Required : Short
Short s = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : Short
8
3. int :
Size : 4 byte
Maxvalue : + 2147483647
Minvalue : - 2147483648
Example :
✓ int i = 10;
✓ int i = 2147483647;
int i = 2147483648;
C.E :
Integer Number To Larege
Short s = 10.50;
C.E :
Possible loss of precision
Found : double
Required : int
Short s = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : int
4. Long :
Size : 8 byte
Maxvalue : + 263-1
Minvalue : - 263
Example :
✓ long l = 10;
✓ long l = 2147483647;
long l= 10.50;
C.E :
Possible loss of precision
Found : double
Required : long
Short s = “Rohan” ;
C.E :
Incompatible types
Found : java.lang.String
Required : long
Note : byte, short, int and long data types can be used to represent whole numbers
9
Floating Point Data types :
Float double
1) If we want to 5 to 6 decimal places of 1) If we want to 14 to 15 decimal places of
accuracy then we should go for float. accuracy then we should go for double.
2) Size : 4 bytes. 2) Size : 8 bytes.
3) Range : -3.4e38 to 3.4e38. 3) Range : -1.7e308 to1.7e308.
4) Float follows single precision. 4) Double follows double precision.
5)
Boolean data type :
Size : Not applicable (virtual machine dependent)
Range : Not applicable but allowed values are true or false.
Example :
✓ boolean b = true;
✓ boolean b = false;
boolean b = 0;
C.E :
Incompatible types
Found : int
Required : boolean
Size : 2 bytes
Range : 0 to 65535
10
Why is Java a strongly typed language ?
➢ Java is strongly typed language because, type checking is very strong.
➢ Java is not pure object oriented programming language because several OOP’s features (like
multiple inheritance, operator overloading) are not supported by java. moreover we are
depending on primitive data types which are non objects.
Literals
Any constant value which can be assigned to the variable is called literal.
Integer Literals
For the integral data types byte, short, int and long we can specify literal value in Decimal
literals, Octal literals and Hexa Decimal forms.
1) Decimal literals :
Allowed digits are 0 to 9.
Example : int x = 10;
2) Octal literals :
Allowed digits are 0 to 7.
Literal value should be prefixed with 0.
Example : int x = 010;
Int x =0759 ; → integer number too large
By default every integral literal is int type but we can specify explicitly as long type.
Example : long x = 10L;
11
Floating Point Literals
By default every Floating point literal is double type but we can specify explicitly as float
type.
We can specify floating point literal only in decimal form and we can not specify in octal and
hexadecimal forms.
Boolean literals
The only allowed values for the boolean type are true or false.
Char literals
A char literal is represented by a single character in single quotes ( ‘ ‘ ).
Example :
✓ char ch = ‘a’;
char ch = a ;
C. E :
cannot find symbol
symbol : Variable a
Location : Class ……….
Char ch = “a” ;
C. E :
Incompatible types
Found : java.lang.String
Required : char
Char ch = ‘ab’;
C. E : → Unclosed Character literal
• We can specify that integral literal in decimal, octal or hexadecimal form but allowed
values range is 0 to 65535.
String literals :
Any sequence of characters with in double quotes is treated as String literal.
Example :
✓ String s = “Sunil” ;
12
❖ Types of Variables
Division 1 : Based on the type of value represented by a variable. all variables are divided into 2
types.
1. Primitive variables
2. Reference variables
1) Primitive variables : can be used to represent primitive values such type of variables
are called Primitive variables.
Example : int x = 10 ;
2) Reference variables : can be used to refer objects values such type of variables are
called Reference variables.
Example :
Division 2 : Based on the position of declaration and behaviour. all variables are divided into 3
types.
1. Instance variables.
2. Static variables.
3. Local variables.
1) Instance variables :
• If the value of a variable is different from object to object such type of variables are
called instance variables.
• For every object a separate copy of instance variables will be created.
• Instance variables should be declared with in the class directly but outside of any
method, block or constructor.
• Instance variables will be created at the time of object creation and destroyed at the
time of object destruction. hence the scope of instance variables is exactly same as the
scope of objects.
• Instance variables will be stored on the heap as the part of object.
• We can not be access Instance variables directly from static area. But we can access by
using object reference.
• Instance variables can be access directly from Instance area.
13
Example :
class Test
{
int x = 10;
public static void main(String[] args) {
X System.out.println("X = "+x);
C.E :
on-static variable x cannot be referenced from a static context
Test t1 = new Test();
System.out.println("X = "+t1.x);
t1.M1();
}
public void M1( )
{
System.out.println("X = "+x);
}
}
• For the instance variables JVM will always provide default values. and we ate not
required to perform initialization explicity.
Example :
class Test
{
boolean b;
public static void main(String[] args)
{
Test t1 = new Test();
System.out.println("B = "+t1.b); // B = false
}
}
• Instance variables also known as object level variables.
14
2) Static variables :
• If the value of a variable is not different from object to object such type of variables is
not recommended to declare as instance variables. We have to declare such type of
variables at class level by using static modifier.
• In the case static variables for a singal copy will be created at class level and shared by
every object of that class.
• Static variables should be declared with in the class directly but outside of any method,
constructor or block.
• Static variables will be crated at the time of class loading and destroyed at the time of
class unloading hence the scope of the static variable is exactly same as the scope of the
.class file.
java TEST
1) Start JVM.
2) Create and start Main Thread
3) Locate(find) Test.class by main Thread.
4) Load Test.class by main Thread. // static variable creation
5) Execution of main() method.
6) Unload Test.class // static variable destruction
7) Terminate main Thread.
8) Shutdown JVM.
Example :
class Test
{
static int x = 10;
public static void main(String[] args)
{
System.out.println(x);
Test t1=new Test( );
System.out.println(t1.x);
System.out.println(Test.x);
}
}
• We can access static variables directly from both static area and instance area directly.
• Static variables also known as class level variables.
15
3) Local variables :
• We can declare variables inside a method or block or constructors such type of variables
are called local variables or temporary variables.
• local variables will be created while executing the block in which we declared it. Once
block execution complete automatical local variable will be destroy. Hence the scope of
the local variables is exactly same as scope of the block in which we declared it.
• Local variables will be stored inside stack memory.
Example :
class Test
{
public static void main(String[] args)
{
Int i = 0 ;
for(int j = 0 ; j < 3 ; j++)
{
i=i+j;
}
System.out.println( “ I = “+ i );
X System.out.println( “J = “ + j);
C.E :
Cannot find symbol
Symbol : variable j
Location : class Test
}
}
• For the local variables JVM not provide any default values compulsory we should
perform initialization explicitly before using that variable.
class Test
{
public static void main(String[] args)
{
int x ;
System.out.println( “ X = “+ x );
C.E :
Variable x mighat not have been initialized
}
}
16
Note :
• The only applicable modifier for local variables is final. If we are using any other modifier
than we will get compile time error.
• If we are not declaring any modifier then by default it is default. but this rule is
applicable for only static and instance variables but not local variable.
• Instance and static variables can be accessed by multiple Threads simultaneously and
hence these are not Thread safe. but in the case of local variable for every thread a
seperat copy will be created and hence local variables are Thread safe.
class Test {
int x = 10 ; → instance - primitive
static String s = "Rohan"; → static - reference
17
❖ (Variable No Of Argument Methods) (1.5)
We can declare a method with variable number Of arguments such type of methods are
called var-arg methods.
Syntax :
Method_Nname(data_type… variable_name)
Example :
Show(int…x)
• We can call this method by passing any number Of int values including zero number
also.
Example :
✓ Show( ) ;
✓ Show(10) ;
✓ Show(10,20) ;
✓ Show(10,20,30) ;
Example :
class Test
{
public static void main(String[] args)
{
Show(10) ;
Show(10,20) ;
Show(10,20,30) ;
}
public static void Show(int…x)
{
System.out.println( “Var- arg methods“);
}
}
Output :
Var- arg methods
Var- arg methods
Var- arg methods
18
• Internally var-arg parameter implemented by using one dimensional array. hence
within the var-arg method we can differentiate values by using index.
Example :
class Test
{
public static void main(String[] args) {
sum(10) ;
sum (10,20) ;
sum (10,20,30) ;
}
public static void sum (int…x) {
int tot = 0 ;
for(int x1 : x) {
tot +=x1;
}
System.out.println("The Sum = "+tot);
}
}
Output :
The Sum = 0
The Sum = 30
The Sum = 60
The Sum = 100
Case 1
✓ sum(int... x)
✓ sum(int …x)
✓ sum(int…x)
x sum(int x…)
x sum(int. ..x)
x sum(int .x.. )
19
Case 2
Example :
Case 3
If we mix normal parameter with var-arg parameter then var-arg parameter should be the
last parameter.
Example :
Case 4
Inside var-args method we can take only one var-arg parameter and we can not take more
than one var-arg parameter.
Example :
x sum(int…x, int…y);
Case 5
Inside a class we can not declare var-arg method and corresponding one dimensional array
method simultaneously other ways we will get compile time error.
Example :
class Test
{
public static void M1(int...x)
{
System.out.println("Var-Arg Method");
}
public static void M1(int[ ] x)
{
System.out.println("Array Method");
}
}
C.E :
Cannot declare both M1(int...) and M1(int[]) in Test
20
Example :
Output :
Var - Arg Method
Var - Arg Method
Genral Method
In general var-arg method will get least priority that is if no other method matched then only var-arg
method will get the chance this is exactly same as default case inside a switch.
Wherever one dimensional array present we can replace with var-arg parameter.
Example :
✓ M1(int[ ] x) → M1(int…x)
✓ main(String [ ] args) → main(String…args)
Case 2
Wherever var-arg parameter present we can not replace with one dimensional array..
Example :
X M1(int…x) → M1(int[ ] x)
21
Note :
1) M1(int…x)
we can call this method by passing a group of int values and x will become one dimensional
array.
M1(int…x) → int[ ] x
2) M1(int[ ] …x)
we can call this method by passing a group of one dimensional and x will become two
dimensional array.
M1(int[ ] …x) → int[ ][ ] x
class Test
{
public static void main(String[ ] args) {
int [ ] a = {10,20,30};
int [ ] b = {40,50,60};
M1(a,b);
}
Output
10
40
22
❖ Main Method
• Whether class contains main( ) method or not and whether main( ) method is declared
according to requirements or not these think won't be checked by compiler, at runtime
JVM is responsible to check this think.
• If JVM unable to find main( ) method then we will get runtime exception saying
NoSuchMethodError: main.
Example :
class Test
{
Output
Javac Test.java
Java Test
R.E : NoSuchMethodError: main.
• The above syntax is very strict and if we perform any changes then we will get runtime
exception saying
NoSuchMethodError: main.
• Even though above syntax is very strict but some changes are acceptable to main( )
method.
1) Instead of public static we can take static public that is the order of modifier is
not important.
2) We can declare string[ ] in any acceptable form.
✓ main(String[ ] args)
✓ main(String [ ]args)
✓ main(String args[ ])
23
4) We can replace string[] with var-arg parameter.
✓ main(String… xyz)
Example :
class HelloWorld
{
public static final synchronized strictfp void main(String...args)
{
System.out.println("Valid Main Method.!");
}
}
Output
Valid Main Method.!
24
Q 2) In which of the above cases we will get compile time error ?
We won't get compile time error any anywhere but except last two case in remaining we will
get runtime exception saying : NoSuchMethodError: main.
Case 1
• Overloading of the main() method is possible but JVM is always call String[ ] array
argument main() method only.
• The other overloaded method we have to call explicitly like normal method call.
• Example :
class Test
{
public static void main(String[ ] args)
{
System.out.println("String Array ");
}
public static void main(int [ ] args)
{
System.out.println("int Array ");
}
}
Output
String Array
Case 2
• Inheritance concept is applicable for main( ) method hence while executing child class if
the child class doesn't contain main( ) method then the parent class main( ) method will
be executed.
• Example :
class Perent
{
public static void main(String[ ] args)
{
System.out.println("Perent Main");
}
}
class Child extends Perent
{
}
javac Perent.java
javac Perent
javac Child
25
Case 3
class Perent
{
public static void main(String[ ] args)
{
System.out.println("Perent Main");
}
}
class Child extends Perent
{
public static void main(String[ ] args)
{
System.out.println("Child Main");
}
}
javac Perent.java
javac Perent
javac Child
• It seems overriding concept is applicable for main( ) method but it is not overriding it is
method hiding.
• Note : For main( ) method Inheritance and Overloading concept are applicable but
overriding concept is not applicable.
• Untill 1.6 version if the class doesn't contain main() method then we will get Runtime
Exception saying NosuchMethodError : main.
• But from 1.7 version onwards instead of NoSuchMethodError we will get more meaning
full description error information.
• Example :
class Test
{
}
1.7 version
1.6 version javac Test.java
javac Test.java java Test
java Test Error : main method not found in class Test, please
R.E : NosuchMethodError : main define the main method as public static void
main(String[ ] args)
26
Case 2
• From 1.7 version onwards main() method is compulsory to start program execution, hence
even though the class contains static block if won't be executed if the class doesn't main( )
method.
• Example :
class Test
{
static
{
System.out.println("Static Block.!");
}
}
1.7 version
1.6 version
javac Test.java
javac Test.java
java Test
java Test
Error : main method not found in class Test, please
Output : Static Block.!
define the main method as public static void
R.E : NosuchMethodError : main
main(String[ ] args)
Case 3
class Test
{
static
{
System.out.println("Static Block.!");
System.exit(0);
}
}
1.7 version
1.6 version javac Test.java
javac Test.java java Test
java Test Error : main method not found in class Test, please
Output : Static Block.! define the main method as public static void
main(String[ ] args)
Case 4
class Test
{
static
{
System.out.println("Static Block.!");
}
public static void main(String[ ] args)
{
System.out.println("Main Method.");
}
}
1.6 version 1.7 version
javac Test.java javac Test.java
java Test java Test
Output : Static Block.! Output : Static Block.!
Main Method. Main Method.
27
1.6 version
Identification of static members
Check for
Execute main() method R.E : NosuchMethodError : main
main()
1.7 version
Check for main() Not Available
Available
Error : main method
Identification of static members not found in class Test,
please define the main
method as public static
void main(String[ ] args)
Execute static block and static
variable assignment
28
❖ Command line arguments
• The arguments which are passing from command prompt are called command line arguments.
• With this command line argument JVM will create an array and by passing that array as
argument. JVM will call main( ) method.
• Example :
Java Test A B C
args[0]
args[1]
args[2]
args.length ---- 3
• The main objective of command line arguments is we can customize the behavior of the main(
) method.
Case 1
• Example :
class Test
{
public static void main(String[] args)
{
for( int i = 0 ; i < = args.length ; i++)
{
System.out.println(args[i]);
}
}
}
Output Output
javac Test . java javac Test . java Output
java Test A B C java Test A B javac Test . java
Output java Test
Output Output
A A
B B R.E :
C
R.E : R.E : ArrayIndexOutOfBoundsException
ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException
• If we replace < = with < then we won't get any runtime exception.
Case 2
• Example :
class Test
{
public static void main(String[] args)
{
String [] argh = {"A" , "B" , "C"};
args = argh;
fors( String x : args)
{
System.out.println(x);
}
}
}
29
Output Output
javac Test . java javac Test . java
java Test X Y Z java Test
Output Output
A A
B B
C C
Case 3
• Within the main() method command line arguments are available in String form.
• Example :
class Test
{
public static void main(String[] args)
{
System.out.println(args[0] + args[1]);
}
}
Output
java Test 10 20
Output
1020
Case 4
• Space itself separator between command line arguments if are command line argument itself
contains space than we have to enclose that command line argument with double quotes ( “ “
).
• Example :
class Test
{
public static void main(String[] args)
{
System.out.println(args[0]);
}
}
Output
Output
Note Book
30
❖ Java coding standards
• Whenever we are writing java code, It is highly recommended to follow coding standards.
• Whenever we are writing any component (Like : class, method or variable) it’s name should
reflect the purpose of that component (functionality).
• The main advantage of this approach is readability and maintainability of the code will be
improve.
• Example :
31
• Example :
run( )
add( )
sleep( ) VERB getName( )
println( ) setName( ) VERB - Nouns
print( ) toArray( )
MAX_VALUE
MAX_PRIORITY Nouns
NORM_PRIORITY
Note : Usually we can declare constants with public static final modifiers.
32
7) Java bean coding standards :
• A java bean is a simple java class with private properties and public getter and setter
methods.
• Example : Class name ends with bean is not
official convention frome sun
class StudentBean
{
private String name;
public void setName ( String name )
{
this.name = name ;
}
public String getName( )
{
return name;
}
}
1. It should be public
2. The return type should be void.
3. Method name should be prefixed with set.
4. Compulsory it should take some argument.
1. It should be public
2. The return type should not be void.
3. Method name should be prefixed with get.
4. It should not take any argument.
Note :
For the boolean properties the getter method can be prefixed with either get or is.
But recommended to use is.
Example :
33