Java Fundamentals
Java Fundamentals
A name in java program is called identifier, which can be used for identification
purpose, it can be method name or variable name, class name or label name.
Example
Class Test{
Int i=10;
Test, main , String args and i are the identifiers in the above program, String is the
class name;
Class Test{
Int number=10;
Int Number=20;
Int NUMBER=30
There is no length limit for java identifiers but it is not recommended to take
too lengthy identifiers
We cannot use reserved words as identifiers
All predefined java class names and interface names we can use as
identifiers
Example
}
Even it is valid but it is not a good programming practice because, it reduces
readability and creates confusion
Reserved words
In Java, some words are reserved to represent some meaning or functionality, such
type of words are called reserved words.
Keywords for DataTypes
Byte, short, char , int , long, float double , Boolean
Keywords for Follow Control
If, Else, switch-case default, while, do, for break, continue ,return
Keywords for Modifiers
Public, private, protected, static, final, abstract, synchronized, native,
strictfp, transient, volatile
Keywords for Exception handling
Try, Catch , Finally, Throw, Throws, assert
Class related Keywords
Class, interface, extends, implements , package, import
Object related Keywords
New , instanceof, super , this
Void return Type Keyword
Void,
Unused Keywords
Goto : Usage of Goto created several problems in old languages and hence
SUN people banned this keyword in JAVA
Const: Use final instead of Const
Note : the above keywords are unused keywords and if we are trying to use we will
get compile time error.
Reserved Literals
ENUM(1.5 Version)
We can use ENUM to define a group of named constants
Example
ENUM month{
Jan,Feb,....Dec
}
Conclusions
All 53 reserved words in JAVA contains only lower case alphabet symbols
In Java, we have only new keyword and there is delete keyword because
destructions of useless objects is done by Garbage Collector
The following are new keywords in java
Strictfp—1.2
Assert—1.4
ENUM—1.5
Data Types
Except Boolean and char the remaining datatypes are considered as signed
DataTypes because we can represent both positive and negative numbers
Byte
Size- 1 byte (8 bits)
max values +127
Min values -128
Range -128 to 127
The most significant bit acts as sign bit, 0 means positive , 1 means negative
Positive numbers will represented directly in the memory whereas negative will be
represented in 2 compliment forms
Byte is the best choice if we want to handle in terms of streams either from the file
or from the network(file supported form or network form is byte)
Short
Size 2 bytes(16 bits)
Range -32768 to 32767
Int
Size 4 bytes (32 bits)
Range -2147483648 - 2147483647
Long
The numbers of characters present in a big file, may exceed int range hence the
return of length method is long but not int
Long l=f.length
But Java is Unicode based and number of different Unicode characters are greater
than 256 and less than or equal 65536, to represent these many characters 8 bits
are not enough hence 16 bits is required , the size of char in java is 2 bytes
Range – 0 to 65535
Literals
Int x=10;
Int - DataType
X is the name of variable /indentifer
10 is constant value or literal
Integral Literals
For integral Data (Byte, Short, int and long) we can specify literal value in the
following ways
Hexadecimal Form
Allowed digits are 0 to 9, a to f (any case)
Literal value should be prefixed with 0x/0X
Example int x=0x010
We can specify floating point literals only in decimals and we cannot specify in
octal and hexa decimal forms
We can assign integral directly to floating point variables and that integral can be
specified either in decimal or octal or hex decimals
Char
We can specify as single character within single quotes.
Char ch=’a’
We can specify char literal as integral literal which represents Unicode value of
the character and that integral literal can be specified either in decimal or octal or
hex decimal forms but allowed range is 0 to 65535
String Literal
Any sequence of characters within double is treated is as string literal
String s=”durga”
1.7 version Enhance methods with respect to literal
Binary literals
For integral data type until 1.6 version we can specify values in the
following values-Decimal , octal, hex but 1.7 onwards we can specify
literal value even in binary form also
Allowed digits 0 and 1
Literal values should be prefixed with 0b/0B
Int x=0b1111
Sop (x)—15
Usage of Underscore in Numeric literals
From 1.7 onwards we can use underscore between digits of numeric literal
Example double d = 123456.789 can written as
Double d 1_23_456.7_8_9
The main advantage of this approach is readability of the code will be improved
At the time of compilation these underscore symbols will be removed
automatically. Hence after compilation the above lines will become
double d = 123456.789
We can use more than one underscore symbol between the digits
We can use underscore symbol only between the digits if we are using anywhere
else we will get compile time error
8 byte long value we can assign to 4 byte float variable because both are following
different memory representations internally
Float f= 10 l
Sop(f)-10.0
Arrays
Int[] x,
Int []x
Int x[]
All the above 3 are valid but first one is recommended as name is clearly separated
from type.
At the time of declaration we cannot specify the size otherwise we will get compile
time error
Int[6]x is invalid
\
All the above declarations are valid
Array Creation
Every array in java is an object only, hence we can create arrays by using new
operator
Output
For every array corresponding class are available and these classes are part of
java language and not available to the programmer level
At the time of array creation compulsory we should specify the size
otherwise we will get compile time error
If we are trying to specify array size with some negative int value, then we
will run time exception saying negative array size exception
To specify array size the allowed data types are byte ,short ,char and int. If
we are trying to specify any other type then we will get compile time error
Note The maximum allowed array size in java is 2147483647 which is the
maximum value of int data type. Even in the first we may get runtime
exception if sufficient heap memory is not available
Int x[]={1,2,3}
Length method is a final method applicable for string object , length method
returns numbers of the characters present in the string
String s=”durga”
Sop(x.length)—compile time error
Sop(x.length())—5
Note length variable is applicable for arrays but not for string objects where
as length method is applicable for string objects but not for arrays
In multi-dimensional arrays length variable represents base size but not
total size
Anonymous Array
Sometime we can declare an array without name, such time of arrays are
called Anonymous arrays.The main purpose of anonymous arrays is just for
instant use(one time usuage)
Based on our requirement we can given the name to the anonymous then it is
no longer anonymous
Int[]x =new(10,20,30)
In the above pic example to call sum , we require an array but after
completing sum method , we are not using that array any more hence for
one time requirement anonymous array is the best choice
Case 2
In the case of Object type arrays as array elements we can provide either
declared type of objects or its child class objects
Case 3
For interface type arrays, as array elements its implementation class objects
are allowed
Runnable is interface and its implementation class is Thread
Case 1
Element level promotions are not applicable at array level
For example
Char element can be promoted to int type where as char array cannot be
promoted to int array
Case 2:
Whenever we are assigning one array to another internal element won’t be
copied just reference variable will be assigned
Case 3:
Whenever we are assigning one array to another array , the dimensions
must be matched , for example in the place one dimension int array we
should proved one dimensional array only,if we trying to provide any other
dimension then we will get compile time array.
Whenever we are assigning one array to another array, both dimensions and
types must be match but sizes are required to match
Example 1
Example 2
Example 3
Types of Variables
Based on type of value represented by a variable all variables are divided
into 2 types
Primitive Variable can be to represent primitive values
Ex: int x=10
Reference Variable can be used to refer objects
Ex student s=new student()
Based on position and behavior all variables are divided into 3 types
Instance Variable
Static Variable
Local Variable
Instance Variable
If the value of a variable is varied from object to object such type of
variables are instance variables
For every object a separate copy instance variable will be created
Instance variable should be declared within the class but outside of method
or block or constructor
Instance variable will be created at the time of object and destroyed at the
time of object destruction hence the scope of instance variable is same as the
scope of object
Instance variables will be stored in the heap memory as part of the Object
We cannot access instance variable directly from static area but we can
access by using object reference but we can access instance variable
directly from instance area
For instance, JVM will always provide default values and we are not
required to perform initialization explicitly
Instance variables also known object level variable or attributes
Static Variables
If the value of a variable is not varied from object to object then it is not
recommended to declare as instance variables, we have to declare such type
of variables at class by using static modifier
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 declared within the class directly but outside of
any method, 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 variable is exactly 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 Variable destruction
7. Terminate main Thread
8. Shut down JVM
Static variables will be stored in method area
We can access static variables either by object reference or by class name but
recommended to use classname. within the same it is not required to 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 and we not required to perform
initialization explicitly
For local JVM will not provide default values compulsory we should perform
initialization explicitly before using that variable i.e if we are not using then it is
not required to perform initialization
Note It is not recommended to perform initialization for local variables inside
logical blocks because there is not guarantee for the execution of these blocks
always at run time
The only applicable modifier for local variable is final, by mistake if we are trying
to apply any other modifier then we will compile time error.
If we are not declaring with any modifier than by default it is default but this rule
is applicable only for static and instance variables but not for local variables
Conclusion
For instance and static variables JVM will provide default values and we are not
required to perform initialization explicitly but for JVM won’t provide default
values compulsory we should perform initialization explicitly before using that
variable
Instance and static can be accessed by multiple threads simultaneously and hence
these are not thread safe but in the case of local variables for every thread a
separate copy will be created and hence local variables are thread safe
Static array
Local level
Once we create an array every array element by default initialized with default
values irrespective of whether it is instance or static or local array
12
We can declare a var arg method as follows m1(int... x). We can call this method
by passing any number of int values including zero number
Output
Internally var args parameter will be converted into one dimensional array , hence
within the var args method we can differentiate the values by using index
Case1
Valid Var Args method declarations
Case2
We can mix var args parameters with normal parameter
Case 3
If we mix normal parameter with var args parameter should be last parameter
Case 4
Inside var args method we can take only var args parameter and we cannot more
than one var arg parameter
Case 5
Inside a class we cannot declare var arg method and corresponding one
dimensional array,we will get compile time error
Case 6
In general var arg method will get least priority i.e if no other method matched
then only var arg method will get chance it is exactly same as default case inside
switch
Equivalence between var arg parameter and one dimensional array
Case 1
Where ever one dimensional array present we can replace with var arg
parameter
Case 2
Where ever var arg parameter present we cannot replace with one
dimensional array
Note
At run time JVM always searches for main method with the following
prototype
The above syntax is very strict and if we perform any change then we will
get run time exception saying no such method : error main
Even though above syntax is very the following changes are acceptable
1. Instead of public static we can take static public i.e the order of modifiers
is not important
2. We declare String array in any acceptable form
Case 1
Overloading of the main method is possible but JVM will always String
array argument main method only , the other overloaded we have to call
explicitly like normal method call
Case 2
Case 3
It seems overriding concept applicable for main method but it is not
overriding and it is method hiding
Note: Inheritance and overloading concepts are applicable but overriding is
not applicable, instead of overriding method hiding is applicable
Case 1
Without writing main method is it possible to print some statements to the
console, yes by using static block. This rule is rule is applicable until 1.6 but
from 1.7 onwards it is impossible to print some statements to the console
without writing main method
Example
Note : usually we will declare constants with public, static and final
modifiers
JDBC
1. Load and register driver,from jdbc 4.0 it activity is done
automatically
For.class(“oracle.jdbc.oracleDriver”)—not required after jdbc 4.0
2. Connection
Connection –establish the connection
Connection con=Drivermanager
(“jdbc:oracle:thin:@localhost:1521xe”,”scott”,”tieiger”
3. Statement st=con.createstatement
4. Result rs=st.executequery(“select * from DB”)
5. Process
While(rs.next()){
Sop(rs.getString(item)+rs.getint(quantity)
6. con.close
Maven:
M2_home:path upto maven folder
Path:upto bin
Setup mvn using command propt
Mvn –version
MVN archetype:generate
Groupid:pacage name
Artifactid:project name
Mvn eclipse:eclipse this will create .classpath and .project which will help to
import the project into eclipse