0% found this document useful (0 votes)
4 views54 pages

Java Fundamentals

The document provides an overview of Java identifiers, including rules for defining them, reserved words, and data types. It details the characteristics of various data types, including their sizes, ranges, and how to declare and initialize arrays. Additionally, it explains the types of variables in Java, such as instance, static, and local variables, along with their storage and scope.

Uploaded by

Bandari Srinivas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
4 views54 pages

Java Fundamentals

The document provides an overview of Java identifiers, including rules for defining them, reserved words, and data types. It details the characteristics of various data types, including their sizes, ranges, and how to declare and initialize arrays. Additionally, it explains the types of variables in Java, such as instance, static, and local variables, along with their storage and scope.

Uploaded by

Bandari Srinivas
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 54

Identifiers

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{

Public static void main(String args[]){

Int i=10;

Test, main , String args and i are the identifiers in the above program, String is the
class name;

Rules for defining JAVA Identifiers

 The only allowed characters in JAVA identifiers are


1. A to Z
2. a to z
3. 0 to 9
4. $
5. _
 Identifiers should not start with digit
 Java Identifiers are case sensitive, java language is treated as case sensitive
programming language

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

public class identifiers {


public static void main(String args[]){
int String=000;
System.out.println(String);
}

}
Even it is valid but it is not a good programming practice because, it reduces
readability and creates confusion

Valid and invalid identifiers

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

 True false values for Boolean datatype


 Null default value for Object Reference

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

Floating point data type


 If we want 5 to 6 decimals places of accuracy then we should go for float
 If we want 14 to 15 decimals places of accuracy then we should go for
double
 Float – 4 Byte
 Double – 8 byte
Boolean Data Type
Size not applicable
Range not applicable but allowed values are true or false
Char Data Type
A Constant which can be assigned to the variable is called Literal
In old language like c , c++ are ASCII code base and the number of allowed
different ASCII code characters less than or equal 256.To represent these 256
characters 8 bits are enough hence the size of char in old languages like 1 bytes

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

Decimal literal (base 10)


Allowed digits 0 to 9
Example int x=10;

Octal Form (base 8)


Allowed digits are 0 to 7
Literal value should be prefixed with zero
Example int x=010

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

Which of the following declarations are valid?


By default every integral literal is of int type, but we can specify explicitly as long
by suffix with l/L
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 similarity short literal

Floating Point Literals


By default every floating point literal is of double type and hence we cannot assign
directly to the float variable but we can specify floating point literal as float type
by suffixed with f/F
We can specify explicitly floating point literal as double type by suffixed with
d/D,of course this convention is not required

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

We can’t assign floating point literals to integral types

We can specify floating point even in exponential form(scientific notation)


Boolean
The only allowed values for Boolean are true or false

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

We can specify char literal in Unicode representation which is nothing but ‘\


uxxxx’xxxx-4 digit hex decimal number
Example
Char ch=’\u0061’
Sop (ch)---a

Every escape character is valid char lieral


Char ch =’\n’
Which of the following are valid

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

 An array is an indexed collection of fixed number of homogenous data


elements.
 The main advantage of arrays is we can represent huge number of values by
using single variable, so that readability of the code will be improved but the
main disadvantages of arrays fixed in size i.e.. once we creates an
array ,there is no chance of increasing or decreasing the size

Array Declaration-one dimensional

 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

Array Declaration-Two dimensional


All the above declarations are valid

Which of the following are valid


Conclusion
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 next remaining
variable we will get compile time error

Array Declaration-Three dimensional

\
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

Int[] a= new int[3]

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

 It is legal to have an array with size zero in java

Int[] x=new int[0]

 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

Array Declaration , Creation and initialization

Int x[]={1,2,3}

Two Dimensional arrays


Length vs Length()
Length is a final variable applicable for arrays , Length variable represents
the size of the array.

Int[] x=new int[6]

Sop(x.length())---Compile time error


Sop(x.length)—6

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

There is no direct way to find the size of multidimensional array but


indirectly we can find as follows
X[0].length+x[1].length+x[2].length

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)

We can create anonymous array as follows


New int[]{10,20,30,40}
While creating anonymous arrays we cannot specify the size otherwise we
will get compile time error
We can create multi dimensional anonymous arrays also
New [][]{{10,20},{10,20,30}}

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

Array element assignment


Case 1
In the case of primitive of arrays , as arrays elements we can provide any
type which can be implicitly promoted to declared type
Example 2
In the case of float type arrays, the allowed are long, int, char, byte, short

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

Which of following promotions will be performed automatically


But in the case of Object type arrays child class type array can be promoted
to parent class type array
Example

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

Static variables also known as class level variables or fields


Some times to meet temporary requirements of the programmer we can declare
variables inside a method or block or constructor such type of variable are called
local or temporary variables or stack variables or automatic variables
Local variables will be stored inside stack memory
Local variable will be created while executing the block in which we declared it,
once the block executions completes automatically local variable will be destroyed
hence the scope of variable is the block in which we declared it

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

It is highly recommended to perform initialization for local variables at the time of


declaration at least with default values

The only applicable modifier for local variable is final, by mistake if we are trying
to apply any other modifier then we will 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

Every variable in java should be 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
Uninitialized Arrays
Instance array

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

Var Arg Methods


Until 1.4 we cannot declare a method with variable number of arguments if there
is a change in number of arguments compulsory we should go for new method, it
increases length of the code and reduces readability , To overcome this SUN
people introduced var args methods in 1.5, According to this we can declare
method which can take variable number of arguments such type of methods are
called var arg methods

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

We can call m1 by passing a group of numbers and x will be one


dimensional array similarly with others
Whether class contains main method or not and whether main method is
declared according to requirement or not these things wont be checked by
compiler, At run time JVM is responsible to check these things, if JVM
unable to find main method then we will get run time exception saying “no
such method error:main”

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

3. Instead of args we can take any valid java identifier


main (String[] xyz)

4. we can replace string array with var args


main (String... args)

We can declare with the following modifier

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

Inheritance concept applicable for method , hence while executing child if


child does’nt contain method then parent class method will be executed

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

Command line arguments


The arguments which are passing from command prompt are called
command line arguments
With these command line arguments JVM will create an array and by
passing that as argument JVM will call main method

Example

The main objective of command line arguments is , we can customized


behavior of the main method.
Case1
Within main method command line arguments are available in string form
Usually space itself is the separate between command line arguments if our
command line argument contains space then we have enclose that command
line arguments within double codes

Java Coding Standards


Whenever we write java code , it is highly recommended to follow code
standards,whenever we are writing any component , its name should the
purpose of that component(functionality)

The main advantage of this of approach is readability and maintainability of


the code will be improved
Coding standards for class
Usually class names are nouns, should start with upper case character and
if it contains multiple words , every inner word should start with upper case
character

Coding standards for interfaces


Same as class
Coding standards for methods
Usually method names either verbs or combinations of verb and noun.
Should start with lower case alphabet letter and if it contains multiple words
every 2 second should start with capital letter

Coding standards for variables


Same as method
Coding standards for constants
Usually constant names are nouns ,should contain only upper case
characters and if it contains multiple words then these words are separated
underscore symbol

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

You might also like