of 43
Dos and Donts of Java Keyword
Java Important Concept
Author(s):Dayanithi JDate written: 06/03/2009DeclarationI hereby declare that this document is based on my personal experiences. To the best of my knowledge, this document does not contain any material that infringes the copyrights of any other individual or organization including the customers of Infosys.Target readers -Java LearnerKeywords Java, Basic, Static, Final, Exception, Interface, Inheritance, Class, Overloading, Overriding, Dynamic Binding
Pre-requisites Elementary Java KnowledgeIntroduction
This document helps you to understand the basic concept in java.
The coding snippet gives you the brief introduction about the topic. Appropriate Error messages are description in the right side of the each code snippet.
The Blue color indicates the keywords In Java. The Green color on the right side indicates the Valid program. The Red color on the right side indicates the Invalid or Error.
Index
1. Typecasting2. Array3. Class4. This Keyword5. Constructor6. Method Overloading7. Memory Allocation8. Null9. Array of Objects10. Statici. Static Variableii. Static Methodiii. Static Block11. String in Java12. Relationship13. Inheritance14. Method Overriding15. Dynamic Binding16. Runtime Polymorphism17. Abstract Class18. Finali. Final variableii. Final methodiii. Final Class19. Interface20. Package21. Autobox / unbox22. Exceptioni. Try & catch blockii. Finally blockiii. Throwiv. Throws23. Generic24. == Vs .equal()25. File HandlingTypecasting
float j,l=9;
j = (float)l;
-Validfloat j,l=9;
j = float(l);
-Invalid
Array
All arrays are created dynamically
new int[5] - It creates an array of 5 integers and returns a reference to the newly created array1) By default Array instance will be set to 0.
2) Local variable can not be used without initialized
3) While declaring Array types, The Value won't come in the left side.
int i[9];
-Invalid4) The number of elements in each row (dimension) need not be equal
int[][] irregular = { { 1 },
{ 2, 3, 4 },
{ 5 },
{ 6, 7 } };
-ValidSystem.out.println(irregular[2]);
-Valid(It print Address)int i[] = { 4, 5, 2, 7 };
-Valid
int []i = new int[10];
-Validint i[][] = { { 5, 4 }, { 3,5 } };
-Validint i[][] = { { 5, 4 }, { 3 } };
-Valid
int d[][] = new int[4][];
-Validint d[][] = new int[][7];
-InValid(column is must)int i[][4] = { { 5, 4 }, { 3,5 } };-Invalid(Left side
number should not come)
int i[] = new int[];
-InValid(Unknown size of
object)
int a[][] = new int[3][];
System.out.println(a[0]);
-Output: nullClass
1. All the data members, members are set to default access specifiers.
2. By Default, The data memebers of classes are assigned as shown belowi. numeric data types are set to 0ii. char data types are set to null character(\0)
iii. boolean data types are set to false
iv. reference variables are set to null
3. The variable, methods, class with default access specifierss can be used in all the classes of the same package
4. Classes and Interfaces can have either the public access or the default accessExample 1:
class Parent
{
int i;
}
public class Program
{
public static void main(String args[])
{
Parent p = new Parent();
System.out .println(p.i);//Variable i can be accessed here
}
}
Output:
0
This Keyword
class Parent
{
int i;
int geti()
{
System.out.println(i);
return i;
}
void seti(int i)
{
i = i;
System.out.println(i);//If this keyword not use here then,
}
//the value not set properly.
}
//So, this.i=i; is correct to change i
public class Program
{
public static void main(String[] args)
{
Parent p = new Parent();
p.seti(99);
System.out.println(p.geti());
}
}
Output: 99
0
0
Constructor
1. It is optional to define constructor2. If a user defined constructor is available, it is called just after the memory is allocated for the object3. Constructor will have same name as that of class name
4. Constructor will not have any return type (void, int etc...)5. In Inheritance, The Parent constructor is executed first6. Parent constructor is executed before child constructor execution7. The Super keyword is used to override the Parent constructor. Super Keyword should be used at first line8. Constructor can not be a static, abstract or finalExample 1:
/*to describe: The Super keyword is used to override the Parent constructor. Super Keyword should be used at first line*/
class Parent
{
Parent()
{
System.out.println("Parent's Default constructor");
}
Parent(int i)
{
System.out.println("Parameterized constructor");
}
}
class Child extends Parent
{
Child()
{
super(9);//Should be used at first line
System.out.println("Child's Default constructor");
}
}
public class Program extends Parent
{
public static void main(String[] args)
{
Child p = new Child();
}
}
Output:
Parameterized constructorChild's Default constructorMethod Overloading
Two or more methods in a Java class can have the same name, if their argument lists are different
Argument list could differ in
No of parameters
Data type of parameters
Sequence of parameters
Example 1:
public class Program {
int Add(int i, int j)
{
return i+j;
}
float Add(int i, int j, int k)
-Valid
{
return i + j + k;
}
public static void main(String[] args)
{
Program p = new Program();
System.out.println(p.Add(6, 7));
System.out.println(p.Add(5,6,7));
}
}
The Method overloading considers only the arguments.Example 2:
public class Program
{
int Add(int i, int j)
{
return i+j;
}
void Add(int i, int j, int k)
-Valid
{
System.out.println (i + j + k);
}
public static void main(String[] args)
{
Program p = new Program();
System.out.println(p.Add(6, 7));
p.Add(5,6,7);
}
}
when passing int ->if no int available -> then float will take
when passing char ->if no char available -> then float will take
when passing float ->if no float available-> then double will take
when passing String ->if no String available -> Errorwhen passing double ->if no double available-> Error
Hierachy of automatic conversion
char(1)->int(2)->float(3)->double(4)-> X(nothing)
String -> X(nothing)
Memory Allocation
Stack
-Local variable
Heap
-All dynamically allocated arraysDynamically allocated objectsData members of the class
If null is assigned to any reference, then the Garbage collector can dereference the object if memory allocation is needed more.If a reference variable is Declared Within a function, the reference is invalidated as soon as the function call endsExample 1:
public class Program {
private int i;
void editObj()
{
Program p = new Program(); //Object p destroyed when
p.i = 100;
//this function is over
}
void seti()
{
i = i + 5;
}
void displayi()
{
System.out.println(i);
}
public static void main(String[] args)
{
Program p = new Program();
p.i = 5;
p.editObj();
p.seti();
p.displayi();
}
}
Output:
10NullString str = null;
-Validint h = null;
-Invalid
Because, Primitive types are
not objects and they cannot
be assigned null
Array of Objects
PolicyHolder [] policyHolder = new PolicyHolder[3];
/*3 PolicyHolder references policyHolder[0], policyHolder[1] and policyHolder[2] are created and all 3 references are null*/
public class Child
{
int i;
public static void main(String args[]) throws Exception
{
try
{
Child d[] = new Child[5];
System.out.print(d[0].i);
//Exception Arise
}
catch (Exception e)
{
System.out.println(e);
}
}
}
Output:
Java.lang.NullPointerException
Example 2:To avoid NullPointerException, we need to create object for each reference by using new Keyword.
public class Child
{
int i;
public static void main(String args[]) throws Exception
{
try
{
Child d[] = new Child[5];
for (int i = 0; i < d.length; i++)
d[i] = new Child();
//Allocate memory
for (int i = 0; i < d.length; i++)
System.out.print(d[i].i+ " ");
}
catch (Exception e)
{
System.out.println(e);
}
}
}Output:
0 0 0 0 0Static
The static keyword can be used in 3 scenarios:
For class variables
For methods
For a block of code
Static Data Member in class1. Static data is initialized to zero
2. Static variable instantiated only once
3. Static data is a data that is common to the entire class
Static data is a data that is common to the entire class
public class Program
{
static int count;
Program()
{
count++;
}
public static void main(String args[]) throws Exception
{
Program p[] = new Program[10];
for(int i=0; i