Java Notes Xen
Java Notes Xen
It is a High Level, Object Oriented, Strictly Typed, Platform Independent, General Purpose
Programming Language Developed by Mr James Gosling and his team at Sun
Microsystems (now Taken over by Oracle) in 1995-96. It’s also a Platform and Technology.
Low level programming language are those language whose program are directly
interact with hardware. They can be easily understand by machine but cannot be
easily understand by human.
Program: A computer program may be defined as the set of instructions in static state
OR we can say that it is a chain of steps OR a set of activities which combine together to
perform a specific task but they are in static state.
Process: It’s the Active state of a program OR we can say that program in execution is
called a process.
Thread: It’s a Sub-Process. Process Inside process or light weight process
Translator: A translator is a program that converts a computer program from
one language to another (in general from High Level Language program to Machine
Language Program). It takes a program written in source code and converts it into
machine code.
1
There are three type of Translator:
1. Compiler
2. Assembler
3. Interpreter
2
Sdlc models: There are quite a few software development life-cycle models out there
that you can follow and use. Each model follows a series of unique steps, with the
ultimate aim of ensuring the success of the software development.
3
Platform:
It is the environment on which our program is executed. It could be a software, hardware
of a combination of both.
1. Software :- OS ,Server
2. Hardware :- CPU ,Microcontroller
3. Software + Hardware (Embedded Systems)
**A Programming language is called platform independent if its program compiled on
one platform can be executed on other platforms without changing their object code.in
short it’s abbreviated as CORA: Compile Once Run Anywhere
4
Problems with C language
C is a procedural programming language and C++ is Object Oriented Programming
Language.
1. No data hiding
2. It doesn’t support the concept of real world
3. No modularity
4. Complexity
5. Tight coupling
6. Platform Dependent
Platform:-
It is the place on which our program is going to be executed it could be a hardware or software or
combination of both.
Type of Platform:-
1. Software- O.S
2. Hardware- Micro controller or micro processor
3. Software + Hardware
5
What is Platform Independency: -
Any programming language is called platform independent if Its program is compiling on
one platform and same program can be executed on another platform without changing
Its object code. In other word we can say that CORA (compile once run anywhere)
6
JVM, JRE and JDK
JVM : JVM (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.
Loads code
Verifies code
Executes code
Provides runtime environment
JRE: JRE is an acronym for Java Runtime Environment It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JDK: JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.
7
What is API (Application program interface): -
Set of inbuilt libraries or predefined functionality in any language whose form may varies
from language to language.
In C and C++ API is present in the form of Header files, in .Net it’s in the form of namespace
and DLL files whereas in Java it’s in the form of classes, interface and packages.
What is Framework: It is the set of API.
Bytecode: - Highly optimized, unique and universal code which is created by java
compiler with the help of JRE which is runs by Java Virtual Machine (JVM).
8
• Enterprise Applications
• Scientific Applications
• Gaming Applications
• Big Data technologies
• Business Applications
• Distributed Applications
• Cloud-based Applications
Features of java:
1. Simple
2. Secure
3. Platform Independent
4. Architectural Neutral
5. Portable
6. Robust
7. Multithreaded
8. Interpreted
9. Distributed- RMI, EJB & Webservices
10. Dynamic
11. High Performance
12. Object Oriented
9
• It doesn’t has support of Explicit use of pointers which prevents someone to gain
the direct access to a memory location .Hence making the program secure.
• It has the facility of bytecode verification using the concept of magic number. The
magic number is the part of bytecode.
• An executable file is generated only when we run the program and it’s automatically
deleted by the JVM after the program execution.
• Java also has Java Authentication and Authorization Service (JAAS)
for authentication of users, to reliably and securely determine who is currently
executing Java code.
• Java also provides the application level security called encryption and decryption.
• Sandbox security checks the security concern on the network.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and
4 bytes of memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.
11
Object Oriented: - Java is an object-oriented programming language. Everything in
Java is an object. Object-oriented means we organize our software as a combination of
different types of objects that incorporates both data and behaviour.
Object-oriented programming (OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.
Basic concepts of OOPs are:
• Object
• Class
• Inheritance
• Encapsulation
• Polymorphism
• Abstraction
JAVA FUNDAMENTALS
12
1. Keywords: - A keyword is a predefined reserved word whose meaning is fixed
in the programming language.
Type of keywords in java: -
13
There are approximately 52+ keywords used in java.
*Java is a Case Sensitive language.
In java all keywords must be written in small letters of Lower Case.
String college_name;
float price1;
int _rn;
int $mob;
pubic static final int MAX_AGE;
#Example
15
package employeeofsurya; //name of package
public class EmployeeDetails
{
//code snippet
}
#Example
class Employee
{
//constant
static final int MIN_AGE = 18;
//code snippet
}
Variable: - A variable is a name given to a memory location. It is the basic unit of storage
in a program which refer the value of specific address.
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
• In Java, all the variables must be declared before use.
• From OOPs point of view in java variables are also known as Data Members (D.M).
16
Types of Variables or Data Members in java
1. Non static variable / Instance variable / Non static data member
• Instance variables are non-static variables and are declared in a class outside any
method, constructor or block.
• As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
• Unlike local variables, we may use access modifiers for instance variables. If we do
not specify any access modifier then the default access modifier will be used.
• Initialisation of Instance Variable is not mandatory. Its default value is 0
• Instance Variable can be accessed only by creating objects.
#Example
class Test
{
int z=p+q;
System.out.println(z);
18
1. Primitive data types: The primitive data types include boolean, char, byte, short,
int, long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
1 byte = 8 bit
For signed data type, the range can be calculated as -2n-1 to 2n-1-1. Where n is
number of bits.
b) Unsigned data type.(+Ve)
#Note: - In java there is no any concept of unsigned data type.
19
Why the size of char in java is 2 bytes whereas in C and C++ it’s only 1 byte?
It is because java uses Unicode system not ASCII code system.
Unicode System
Unicode is a universal international standard character encoding that is capable of
representing most of the world's written languages.
▪ ASCII (American Standard Code for Information Interchange) for the United States.
▪ ISO 8859-1 for Western European Language.
▪ KOI-8 for Russian.
▪ GB18030 and BIG-5 for Chinese, and so on.
Problem
This caused two problems:
▪ A particular code value corresponds to different letters in the various language
▪ The encodings for languages with large character sets have variable length.
▪ Some common characters are encoded as single bytes, other require two or more byte.
Solution
▪ To solve these problems, a new language standard was developed i.e., Unicode
System
▪ In Unicode, character holds 2 byte, so java also uses 2 byte for characters.
Literals in java: - Constant values that are typed in the program as a part of the
source code are called literals. There are 5 types of literals in java
20
OR
#Example
21
class JavaLiterals
{
float f = 89.0; // Type mismatch: cannot convert from double to float
float ff = 89.0f; //OK
Methods in java
In Java Methods are also known as Member functions.
A method is a block of code which only runs when it is called.
▪ Methods are used to perform certain actions, and they are also known as functions.
▪ We use methods for the reusability of code. Once a method is defined it can be used
again and again.
▪ A method is a self-contained block.
▪ A method doesn’t perform any task until it’s called.
▪ You can pass data, known as parameters, into a method.
▪ From OOPs point of view a member function represents the behaviour of an object.
▪ If we make a method public and static, then it acts as a global method thus can be
accessed from anywhere.
Rules Regarding Methods in Java:-
▪ Before using / calling a method, we have to define it.
▪ We don’t have to declare a method in java
int add(); //Not Valid
▪ It’s valid only with the abstract keyword
abstract int add(); //Valid
22
#Syntax to create a method: -
Modifiers + Return type + Method Name (Arguments If any)
{
Body of the method….
return value; (if return type is mentioned above)
}
#Example
Types of Methods
23
#Example
▪ class Test
▪ {
▪ static void hello() // non parameterized without return
▪ {
▪ System.out.println("hello");
▪ }
▪ static int hello1() // non parameterized with return
▪ {
▪ System.out.println("hello");
▪ return 19;
▪ }
▪ static void hi(int x) // parameterized without return
▪ {
▪ System.out.println("hello");
▪ }
▪ static String hi1(int x) //parameterized with return
▪ {
▪ System.out.println("hello");
▪ return "hello";
▪ }
▪ public static void main(String ss[])
▪ {
▪ System.out.println("main");
▪ hello(); }
▪ }
#Example
▪ public class Test
▪ {
▪ void show(byte b)
▪ {
▪ System.out.println("Byte="+b);
▪ }
▪ void show(short b)
▪ {
▪ System.out.println("short="+b);
▪ }
▪ void show(int b)
▪ {
▪ System.out.println("int="+b);
▪ }
▪ void show(long b)
▪ {
▪ System.out.println("long="+b);
25
▪ }
▪ void show(float b)
▪ {
▪ System.out.println("float="+b);
▪ }
▪ void show(double b)
▪ {
▪ System.out.println("double="+b);
▪ }
▪ public static void main(String [] args)
▪ {
▪ Test t=new Test();
▪ //t.show(23l);
▪ //t.show(23);
▪ t.show(23.67f);
▪ }
▪ }
#Syntax: -
Target-dataType variableName = (Target-dataType) variableToConvert;
//Java program to illustrate explicit type conversion
class Test
{
public static void main(String[] args)
{
double d = 100.04;
byte b=20;
int c=b;// type promotion
int male=5;
int female=2;
float ratio=(float)male/female;
System.out.println(ratio);
}
Output :- 2.5
Comments: -
They are also a symbols they are used for ignoring the line as well as for explaining
the steps. It increases the readability of code.
1. Single line----- //
2. Multiline -----/ *--------*/
3. Documentation----/**-------*/
The nesting of single line comment is possible. But not possible is multiline.
#Example
27
public class Test
{
// This is an Example of single line comment
/* This is an
Example of Multiline
Comment */
Operators: -
In java programming operators are the symbols which are used to perform the operation
over operand.
int x=10;
int y=20;
in x+y ‘+’ is the operator and ‘x’ and ‘y’ are operands.
Types of Operators: -
1. Unary Operators: The Java unary operators require only one operand.
#Example: Increment Operator (++), Decrement Operator (--), Not Operator (!)
2. Binary Operators: The Java binary operators require two operands.
#Example:
• Arithmetic (+,-,*,/,%)
• Logical (&&, || , !)
• Assignment(=)
• Relational (>,<,>=,<=,!=)
• Bitwise (&,| )
• Shift (>>,<<)
28
Java has only one ternary operator which is also known as Conditional Operator
29
What is object oriented programming?
It is the programming methodology which we can relate to the real world in order to
simplify the software development and maintenance.
This methodology has many concepts like:
• Polymorphism
• Inheritance
• Encapsulation
• Abstraction
• Class
• Object etc...
Collectively these concepts are called OOPs. (Object Oriented Programming Concepts).
30
• From real world point of view
• Form coding point of view
• From memory point of view
• From class point of view
▪ Object is any things which exist is the real word which we can see, touch feel &
imagine.
▪ Every real-world entity is called object.
▪ Every real-world entity which physical logical tangible or intangible existence
knows as object.
Every object has the following three characteristics: -
1. State or Data Member
2. Behaviour or Functionality
3. Identity
#Example
If we have a Mobile phone then its characteristics be like
State: - Colour, Price, Dimensions, Camera, RAM, ROM etc.
Behaviour: - Calling, Mailing, Messaging, Internet Surfing.
Identity: - IMEI Number.
Now we know that every object has, state, behaviour, and identity but in real world
we can see that there are many objects in the real world which have same state
and behaviour and this is a problem so to overcome this problem we categorize the
objects. Thus we find the solution in the form of class of categorization.
Class or Classification: -
▪ A class is the logical categorization of similar type of object.
▪ A class is combination of data member and member function.
▪ A class is the blue print from an object
▪ A class is the user define data structure.
▪ A class is user define data type.
▪ A class is the way to implementing the encapsulation
Class: - A class is the template (blue print) for an object and object is the instance for
the class.
#Syntax to create a class in java
31
class Identifier
{
[ Data Member]
[Member Function]
Special Member Function
Constructor
[Initializer (init block & static block)]
}
**Methods are stored in method area but calling of method is done in stack area.
33
#Ans. Function represent independent functionality of an application whereas a member
function represents the behaviour of an object.
Function can be called independently whereas member function must be called on
member (object)
void morningWalk()
{}
morningWalk(); // Function
Ram.morningWalk(); // M.F
35
#Example
class Trainee
{
String name,mobile,course,address;
int age,id;
void showInfo()
{
System.out.println(name);
System.out.println(mobile);
System.out.println(course);
System.out.println(address);
System.out.println(age);
System.out.println(id);
}
/*
public String toString()
{
return getClass().getName()+'*'+Integer.toHexString(hashCode());
}
*/
void setData()
{
name="ravi";
mobile="79789798";
course="java";
address="grnoida";
age=23;
id=12313;
}
36
mobile=m;
course=c;
address=adr;
age=a;
id=i;
}
Trainee()
{
name="ravi";
mobile="79789798";
course="java";
address="grnoida";
age=23;
id=12313;
}
void read()
{
System.out.println("trainees r reading....");
}
void chat()
{
System.out.println("trainee r chating.......");
}
*/
//new Trainee().name="manoj";
//Trainee t2;
//System.out.println(new Trainee().name="sunny");
//System.out.println(new Trainee().mobile="9211420");
//new Trainee().chat();
//Trainee t=new Trainee();
//System.out.println(t);
//t.chat();
//t.read();
//t.id=111;
//t.name="sunny";
//t.address="shivpur";
//t.age=100;
//t.course="merjava";
//t.mobile="9211420";
//t.showInfo();
//
//
//Trainee t1=new Trainee();
//System.out.println(t1);
//t1.id=112;
//t1.name="ravi";
//t1.address="bhihar";
//t1.age=110;
//t1.course="Lutjava";
//t1.mobile="9211420786";
//t1.showInfo();
38
//
//Trainee t3;
//t3=new Trainee();
//System.out.println(t3);
//t3=t;
//System.out.println(t3);
//System.out.println(t);
//t2=t1;
//t3.name="kabi";
//t.showInfo();
}
}
Copy Constructor: -
The copy constructor is a constructor which creates an object by initializing it with an
object of the same class, which has been created previously. The copy constructor is used
to − Initialize one object from another of the same type. Copy an object to pass it as an
argument to a function.
//Program to demonstrate how copy constructor works
public class Student
{
String name;
int age;
Student(String n,int a)
{
name=n;
age=a;
void show()
{
System.out.println(name);
System.out.println(age);
// s1.name=s.name;
// s1.age=s.age;
//System.out.println(s1.name);
s1.show();
if(condition){
// statements (if Block)
}
//other statements
b) If statement: If the condition is true then, it will execute the If block. Otherwise, it
will execute the Else block.
if(condition){
// statements (if Block)
}
else{
// statements (Else block)
}
//other statements
c) If Else-If statement: if the condition is true, then it will execute the If block.
Otherwise, it will execute the Else-If block. Again, if the condition is not met, then it will
move to the else block.
40
d) Switch Statement: - Switch statement allows program to select one action among
multiple actions during the program execution.
#Example
class WriteExample{
public static void main(String []args){
int a=2; int b=3; int c=4;
if(a>b){
System.out.print(“Institute1”);
}
else if(a>c){
System.out.print(“Institute2”);
}
else{
System.out.print(“AndroJava”);
}
}
}
OUTPUT: - AndroJava
Switch(variable/value/expression){
Case :
// statements
Case :
// statements
default:
// statements
}
#Syntax
for(initialization; condition; increment/decrement){
//statements (For Body)
}
41
#Example: -
class WriteExample{
public static void main(String []args){
int a=1;
for(int i=0; i<2; i++){
System.out.println(“Value of a is:”+ a); // string concatenation
a++; // increases value by 1
}
}
}
b) while Loop
• While loop executes till the condition becomes false.
#Syntax: -
while(condition){
// statements
}
#Example: -
class AndroJava {public static void main(String args[]) {
int i = 2;
while( i <=2 ) {
System.out.println(“AndroJava” );
i++;
}
}
}
Output: - AndroJava
c) do while Loop
• When you are using for or while, then it will execute the loop body only if the
condition if true.
• In do-while loop, it will execute the loop first, then it checks the condition. So, it will
execute the loop at least once.
• It is called exit controlled loop while for & while loop are called entry controlled
loop.
42
#Syntax: -
do{
// statements
}while(condition);
#Example: -
class AndroJava {public static void main(String args[]){
int a = 2;
do{
System.out.println(AndroJava);
i++;
}while( a< =2 );
}
}
3. Unconditional Control Statements/Jump Statements
a) Break Statement: -break is a keyword. It is used within any control statements.
It is used to terminate the execution of the current loop or switch statements.
#Example: -
class AndroJava{ // break without label
public static void main(String args[]){
for(int i=1;i<=4;i++){
if(i==3) break;
System.out.println(“AndroJava”);}
} }
Output: -AndroJava
AndroJava
43
Initializers: -
An initializer is a line of code (or a block of code) placed outside any method,
constructor, or other block of code. Initializers are executed whenever an instance of
a class is created. Initializers are used to initialize data even before the constructor.
class A
{
int x;
{
x=10;
}
44
}
**The logic of init block is automatically pasted by the compiler at the top of every
constructor.
#Example: -
package oops;
public class A
{
int x;
static int counter;
{
counter++;
System.out.println("init block1");
A()
{
x=10;
System.out.println("A cons...="+x);
}
A(int x)
{
System.out.println(x);
}
{
System.out.println("init block2");
}
45
public static void main(String[] args)
{
System.out.println("main block..");
new A();
new A(24);
new A(44,67);
{
System.out.println("mai init ka jaisa hu...");
}
A.countObject();
{
//x=20;
//System.out.println("init block....="+x);
System.out.println("init block3");
}
#Example: -
package oops;
public class Employee
{
String name;
int age;
Address adr;
Salary sa;
int x;
{
adr= new Address();
}
{
sa=new Salary();
}
Employee(String m,int a)
{
46
name=m;
age=a;
}
void show()
{
System.out.println("Name="+name);
System.out.println("Age="+age);
System.out.println("Address="+adr.city +"State,"+adr.state+" Country,"+adr.countr
y);
System.out.println(sa.ta +" "+sa.da+" "+sa.hra);
}
47
String companyname = "HCL";
String collegename = "Kalinga University";
String s_name;
int s_id,s_age,s_sal;
s_id=sid;
s_name=sname;
s_age=sage;
s_sal=ssal;
void show(){
p1.show();
p2.show();
p3.show();
48
}
package androjava;
49
String s_name;
int s_id,s_age,s_sal;
s_id=sid;
s_name=sname;
s_age=sage;
s_sal=ssal;
void show(){
p1.show();
p2.show();
p3.show();
}
}
50
Static Data Member and Non static Data member: -
1. Static data member represents the property of class whereas non-static data
member is representing property of object.
2. In case of static data member memory is allocated in class area at class loading time
only once and this memory is shared by multiple objects. It means single copy is
created in memory in case of static data member.
3. In case of non-static data member memory is allocated in each objects separately
(In heap area).It means separate copy is created in each objects in case of non static
data member.
4. If a data is common for all objects then make it static otherwise non static.
5. As we know that static represents the property of class that’s why the standard
approach to call the static data member is with class name. and non static with
object reference
public class B {
static int x;
B()
{
x++;
System.out.println(x);
}
}
OUTPUT: -
1
2
3
51
How Many ways are used to call Non static data member:-
1. Object.Nonstatic Data member; (e.g. new A().x)
2. Object Reference. Non static Data member (e.g--- a.x)------- (Standard approach)
3. Directly Non static Data member (but only in same class non static member function
and constructor ) (e.g .x)
**Above two approaches are valid in same class as well as different class.
**Above three approaches are valid in same class as well as different class.
Rule: - A non-static data member or non-static member function cannot directly access
in static context (static method or static block) but vice-versa is allowed.
Static Member Function and Non static member function:-
1. Static Member Function represents the behaviour or functionality of class and Non
static member functions representing behaviour of object.
2. Method is either static or non-static it gets memory in method area (method table).
3. As we know that static represent the behaviour of class that’s why the standard
approach to call the static member function with class name and non-static with
object reference
How Many way are used to call Non static member function:-
1. Object. Non static member function; (e.g. new A().show())
2. Object Reference. Non static member function(e.g--- a.show())------- Standard
approach
3. Directly member function(but only same class non static member function and
constructor ) (e.g .x)
Above two approaches are valid in same class as well as different class.
How Many way are used to call static member function:-
52
1. Object .static member function; (e.g. new C().disp())
2. Object Reference. static member function(e.g--- a.disp())
3. ClassName. static member function. Standard aproach
4. static member function(same class anywhere) (e.g .disp())
Above three (1 to 3) approaches are valid in same class as well as different class.
Static Block: -
1. Are those blocks which executes only once at class loading time.
2. This block is object independent.
3. It execute before main() method.
4. We can write any logic in static block which we can write in main().
5. In case of more than one static block their order of execution in FCFS.
Note: - we can’t pass the command line argument in static block this could be only
possible with main method.
//Static Block
static
{
//coding…..
Class loading: -
It is the process of storing the class specific information into memory (i.e. data member,
member function, constructor etc.) this process is done by class loaders. (They are the
software program).
Type of Class Loaders: -
1. bootstrap class loader(rt.jar)
2. extension class loader (jre/lib/ext)
3. Application class loader (environment variable)
Things done at class loading time:
• Memory is allocated to the Static Data member.
• Default values are initialized to the Static Data Member.
53
• Static Block are executed in given order
Types of Class Loading:
1. Static class loading
2. Dynamic class loading.
In case of static class loading compiler have already knowledge about loaded class but in
case of dynamic class loading compiler does not have the knowledge about loaded class.
Condition of static class loading: -
1. When we run any class.
2. When we are creating the object of a class into another class.
3. When we are inheriting one class into another class.
4. When we call any static members of a class.
Condition of static class loading: -
In java there is a class whose name is Class and this class Class have a static method
called forName() which is responsible for dynamic class loading?
Command Line Arguments: -It is the process of passing the values from command line
at run time.
In java there is a class whose name is Class. Every class is the instance of class
Class.When any class statically or dynamically loaded into memory then JVM creates
object of class Class for the loaded class. Then class Class object is the duplicate copy
(reflected image) of specific loaded class. It is the part of reflection API.
How many ways are there to get the object of class Class:
1. When we call the getClass() method of object class on the target class object.
Class A
{
Public static void main(String ss[])
{
A a=new A();
Class c=a.getClass():;
}
}
54
2. When we load a class dynamically using the static method forName() of class Class
then it return the object of class Class.
Class c=Class.forName(args[0]);
3. Directly.
Class ca=String.class; //directly
Wrapper Classes: -
• Wrapper classes are those classes which provide the facility to convert the primitive
data type into object and object to primitive.
• In java there are so many wrapper classes are available for every primitive data
types (java.lang)
Explanation of main()
In java main() method is the method which maintains the entry point of a java program
main() is neither predefined nor user defined but it’s a contract between the user and the
programming language.
***We can also use some other modifiers for main like strictfp, final synchronized ,etc. but
is must have public ,static, void and a string array argument
We can change the name of the string array argument. args[] to anything[].
It is used to hold the command line arguments in the form of string values.
56
Java main method doesn’t return anything, that’s why its return type is void.
And it was made so by the java developers because JVM doesn’t require any return value
from the main() to perform any kind of operations so to keep java simple they made main()
as void .
Overloading of main()
We can overload main() with different types of parameters.
But JVM will execute main() which have String array as an argument and the overloaded
function behaves as a normal function.
classTest
{
publicstaticvoidmain(String[] args)
{
System.out.println("Main Method String Array");
}
Data Shadowing: - When in a program the name of instance variable and the name
of local variable are same this concept is called data shadowing.
In other words data shadowing is the process of having same name of instance and local
variable in a program.
package mydata;
int x=10;
void dip(int x)
{
//int x=20;
System.out.println(x);
System.out.println(x);
57
}
**Whenever Data Shadowing is done the preference always goes to the local data
members
package mydata;
int x=10;
58
Whenever we are calling any non-static method and constructor in the
program so by default is method and constructor have an extra
argument (i.e. Object of same class) passed by java compiler its self.
Signature of this public final this;
#Example: -
//use of this in identification of instance variable in case of data shadowing
Class A
{
Void show(this)
{
}
A(this)
{
}
PSVM()
{
A a=new A(a); // Object of same class
a.show(a); // Object of same class
package mydata;
int x=10;
void dip(int x)
{
//int x=20;
System.out.println(x);
System.out.println(this.x);
System.out.println("This ID="+this);
59
}
package mydata;
int x=10;
Void dip()
{
//int x=20; // If local variable not available.
System.out.println(x);
System.out.println(x);
}
60
//Case 1:-If local variable not available…
package mydata;
int x=10;
void dip()
{
//int x=20; // If local variable not available.
System.out.println(this.x); // this keyword id added J.C
System.out.println(this.x);
}
package mydata;
int x=10;
void dip()
{
int x=20;
System.out.println(x); // this keyword not added J.C
System.out.println(x);
}
61
public static void main(String[] args)
{
Demo de=newDemo();
de.dip();
Use 2.
This keyword is used as a method argument in order to refer the current class object.
// This keyword is used as a method argument in order to refer the current object.
package mydata;
class B
{
static void disp(A a)
{
a.msg();
System.out.println("disp");
}
}
class A
{
void show()
{
B.disp(this);
System.out.println("show");
}
void msg()
{
System.out.println("msg");
}
}
Use 3.
This keyword can also be used in case of method chaining.
Method chaining is the process of calling multiple methods on same object at same time.
Note:-In java every constructor have implicit return type i.e class type and it return the
reference id of same class in the form of this.
class A
{
//Default Constructor
class A
{
A A()
{
return this;
}
}
package mydata;
ThisTest3 disp()
{
System.out.println("disp");
return this;
void show()
{
System.out.println("show");
}
63
ThisTest3()
{
System.out.println("cons....");
new ThisTest3().disp().show();
}
Use 4.
This keyword can also be used in case of constructor chaining.
Constructor chaining is the process of calling multiple constructor in a chain on single
object at same time.
Syntax to call constructor: - this(args if any);
this(args if any); statement must be the very first statement in constructor body in
case of constructor chaining.
// Java program to illustrate Constructor Chaining
// within same class Using this() keyword
class Temp
{
// default constructor 1
// default constructor will call another constructor
// using this keyword from same class
Temp()
{
// calls constructor 2
this(5);
System.out.println("The Default constructor");
}
// parameterized constructor 2
Temp(int x)
{
// calls constructor 3
this(5, 15);
System.out.println(x);
64
}
// parameterized constructor 3
Temp(int x, int y)
{
System.out.println(x * y);
}
Use 5.
this keyword can also be used to call the same class methods static and non-static both.
this.show();
show();
Use 6.
this keyword can also be used for forward referencing .
A forward reference is a reference to a variable that has not yet been initialized. These
are bad simply because, if allowed, they'd give us unexpected results. Take a look at this
bit of code:
package mydata;
int z=x*this.y;
int y=20;
ThisTest4()
{
System.out.println(z);
65
}
void show()
{
System.out.println("show");
}
void disp()
{
this.show();
System.out.println("disp");
}
new ThisTest4().disp();
}
}
Encapsulation
• It is the process of wrapping the data member and member function into a single
unit called class.
• The purpose of encapsulation is to achieve data hiding.
• And class is the way to achieve the encapsulation.
• But the normal class is not providing the 100 % implementation of encapsulation.
• Java Bean class providing the best implementation of encapsulation.
Java Bean class or (POJO) Plain Old java Object:
A java bean is the general purpose reusable piece of code that must have the following
characteristics.
Any normal class said to be java bean class if it has the following characteristics: -
1. This class must be public.
2. This class must be inside package.
3. The data member of the class must be private.
4. This class must not be extends any specific class and implements any specific interface
but must implement serializable interface.
5. This class must have public setter and getter method.
6. This class must have public default constructor.
66
Note: - Java bean must implement serializable interface whereas POJO may or may not.
#Example: -
package com.youtube.login;
public class Login implements java.io.Serializable
{
private String name,pass;
Inheritance
It is a process of acquiring the properties and behaviour of Parent class (Base class/Super
class) into a new class called Child class (Sub-class/Derived class) with own properties and
behaviour.
In java we use extends keyword to inherit a class.
Advantages of Inheritance:-
1. The purpose of inheritance is reusability.
2. To achieve run time polymorphism.
3. Method overriding.
4. Data Hiding.
67
#Example: -
package inheritance;
package inheritance;
68
public class Child extends Base //This is child /Sub/Derived class
{
System.out.println(new Child().x);
Child b=new Child();
System.out.println(b.x);
new Child().nsMethod();
b.nsMethod();
System.out.println(new Child().y);
System.out.println(b.y);
System.out.println(y);
new Child().sMethod();
b.nsMethod();
sMethod();
Child.sMethod();
Types of Inheritance: -
1. Single-Level
2. Multi-Level
3. Multiple
4. Hybrid
5. Hierarchical OR Network Based Inheritance
69
*** In java there is no any class created without inheritance
• If there’s class name as A then it will extends Object class. This Object class is
extended by each and every class in java. Or we can say that object class is the
Parent/Super class of all the user defined and pre-defined classes.
• Object class has 9 methods known as magic method.
• Thus we can say that Single level inheritance is by default present in java.
Why java doesn’t supports Multiple Inheritance in case of class: - because it leads to data ambiguity.
int x=10;
}
int x=20;
void show()
{
System.out.println(x);
70
System.out.println(super.x);
}
**Note: - Data shadowing has done is one class whereas data hiding happens in two
classes.
Super Keyword: -
• It is the keyword which can be used in so many ways.
• It is used to identify the parent class data in case of data hiding.
• It is used to call the parent class method in case of method overriding.
• It is used to call the parent class constructor in case of constructor chaining.
Note: - Super can’t be used in static context like this.
Up-casting and Down-Casting: -
• In java the object of child class can be hold into the reference variable of parent
class this concept is called up casting.
• But we can’t hold the object of parent into child.
71
About Type:-
1. In java every primitive variable have it’s type.int x=10;
2. In java every object have their type. e.g new A();
3. In java every reference variable has their type. A a;
In java any child class reference is child type and parent type too. It means child class
object (reference) are tread as the parent class instance.
Question: - In case of Inheritance when we are creating the object of Child class parent
class object are created or not? If not then how parent class data member gets memory.
If yes then how?
Answer: - No, Object of parent class is not created. All the data of parent get memory
into the child class object as shown the diagram below.
no parent class object is not created. All the parent data gets memory into child class
object. We can see in the below diagram:
***Rule: - We can call the parent class members with child reference but we can’t call the child class personal
data with parent reference.(V.V.Imp)***
Instanceof: - The java instanceof operator is used to test whether the object is an
instance of the specified type (class or subclass or interface). The instanceof in java is
also known as type comparison operator because it compares the instance with type. It
returns either true or false. If we apply the instanceof operator with any variable that
has null value, it returns false.
72
//Example and Syntax to use instanceof operator .
class Sample1{
public static void main(String args[]){
Sample1 s=new Sample1();
System.out.println(s instanceof Sample1); //true
}
}
package resubality;
class Boss
{
int x=200;
}
int x=10;
}
int x=20;
// System.out.println(b1.x);
// System.out.println(b2.x);
// System.out.println(b3.x);
// System.out.println(super.x);
// System.out.println(x);
//
System.out.println(((Base)this).x);
System.out.println(((BaseKaBase)this).x);
System.out.println(((Boss)this).x);
System.out.println(x);
}
public static void main(String[] args)
{
Child c =new Child();
//Base v=c;
73
c.show(c,c,c);
System.out.println(c instanceof Child);
System.out.println(c instanceof BaseKaBase);
System.out.println(c instanceof Boss);
System.out.println(c instanceof Base);
}
}
Method Overriding
@overriding
When in a program the parent class method name and child class method name are same
this concept is called method overriding .In other words we can say that when child class
rewrites the parent class method with same name and same signature so we can say that
child class overrides the parent class method.
//Example
class Parent {
Void show()
{
}
}
Rules:
1. There must be a relation of parent and child between classes for method overriding.
2. The name of the method and its signature must be same.
3. In Case of method overriding the preference always goes to child class overridden
method.
4. Static, final and private methods can’t be overridden.
74
5. If the method of parent class is static and child is non static then it’s not valid also it’s
opposite is not valid. But if both methods are static then it’s valid. (This concept is
called method hiding)
6. In Java there are 4 type of access rule
a. Public
b. protected
c. default
d. Private
Note: This sequence is stronger sequence. But case of method overriding either same
or weaker to stronger.
#Example
package inheritance;
class Base {
** From jdk 1.5 method overriding can also be done by changing the return type of the
method, but the conditions below must be followed.
Case 1: Both class methods must have return type of reference type
Primitive return type is not allowed.
*The classes which is used as a return type they must have relation of parent and child.
75
Case 2: Parent Class method should return parent class reference and child class method
should return child class reference
The Above Case is known as COVARIANT RETURN.
COVARIANT RETURN: Before java 1.5 it’s not possible to override a method by changing
its return type but from java 1.5 we can override a method by changing return type. (But
this must satisfy case 1 and 2).
IF the return type of parent and child class varies then this is known as covariant return.
package Inharitence;
class A
{
A()
{
System.out.println("Defualt constructer A");
}
}
class B extends A
{
B()
{
System.out.println("Defualt constructer B");
}
}
76
class C extends B
{
C()
{
System.out.println("Defualt constructer C");
}
}
Ineherite()
{
System.out.println("Defualt constructer Ineherite");
}
Note: we cannot use this () and super() together in a constructor. Because call to this
must be first statement in a constructor body and call to super must be first statement a
constructor body. By default it is using super().
package Inharitence;
class A
{
A()
{
super();
System.out.println("Defualt constructer A");
}
}
class B extends A
{
B()
{
super();
System.out.println("Defualt constructer B");
77
}
}
class C extends B
{
C(int x)
{
this();
System.out.println(x);
C()
{
super();
System.out.println("Defualt constructer C");
}
}
Ineherite()
{
super(40);
System.out.println("Defualt constructer Ineherite");
}
Constructor Chaining:
It is process of calling multiple constructors in a chain on single object.
package inharitence;
class A
{
A(int a)
{
System.out.println(a);
}
78
A()
{
super();
System.out.println("Defualt constructer A");
}
}
class B extends A
{
B(int x, int y)
{
super(65);
System.out.println(x);
System.out.println(y);
}
B(int x)
{
this(25,65);
System.out.println(x);
}
class C extends B
{
C(int x)
{
this();
System.out.println(x);
C()
{
super(25);
System.out.println("Defualt constructer C");
}
}
Ineherite()
{
super(40);
System.out.println("Defualt constructer Ineherite");
}
79
public static void main(String[] args) {
Ineherite s = new Ineherite();
}
}
What is binding?
When a member call getting their member definition is called binding.
OR
Connecting a member call with their member definition is called binding.
*Member means data and member functions.
There are two types of binding
1. Compile time binding (earlier binding)
2. Runtime binding (late time/dynamic binding)
Compile Time Binding: When a member call getting their member definition at compile
time this is called compile time binding. In case of compile time binding compiler does its
binding on the basis of reference variable.
Dynamic Binding: When a member call getting their member definition at runtime this is
called dynamic binding. Runtime binding is done by JVM on the basis of object type.
***Except non-static methods /virtual methods/instance methods all other entities
are bound statically.
80
**Note: At the time of compilation assembly instructions are putted by the compiler in
the byte-code in both types of binding.
Instructions include:
1. Invoke static: static binding to be done.
2. Invoke virtual: dynamic binding to be done.
3. Invoke special: this is also static binding but a special type of case.
class Parent{
{
System.out.println("Init of parent");
}
int x=100;
static int s=200;
Parent (){
System.out.println("Dc of parent const...");
}
void display() {
System.out.println("Display method of Parent");
}
{
System.out.println("init of child");
}
Children(){
81
Parent c= new Children();
System.out.println(c.x);
System.out.println(c.s);
c.show();
c.display();
class Parent{
{
System.out.println("Init of parent");
}
int x=100;
static int s=200;
Parent (){
System.out.println("Dc of parent const...");
}
void display() {
System.out.println("Display method of Parent");
}
{
System.out.println("init of child");
}
Children(){
try {
Class c =Class.forName(args[0]);
System.out.println(obj.x);
System.out.println(obj.s);
obj.show();
obj.display();
} catch (Exception e) {
e.printStackTrace();
}
83
POLYMORPHISM
84
a. Compile time polymorphism: - Compile time polymorphism or static method
dispatch is a process in which a call to an overloading method is resolved at compile
time rather than at run time. In this process, we done overloading of methods
which is called through the reference variable of a class here no need to superclass.
Method overloading: - If a class have multiple methods by same name but different
parameters, it is known as Method Overloading.
}
}
OUTPUT:
30
40
}
}
** It can also be done by changing both number of parameters and data type of
parameters as shown in the above code.
Constructor overloading: - Constructor overloading is a technique in Java in which a
class can have any number of constructors that differ in parameter list. The compiler
differentiates these constructors by taking into account the number of parameters in the
list and their type.
//Example of constructor overloading
class Demo{
int value1;
int value2;
/*Demo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st Constructor");
}*/
Demo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
Demo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
Demo d1 = new Demo();
Demo d2 = new Demo(30);
Demo d3 = new Demo(30,40);
d1.display();
d2.display();
d3.display();
}
}
86
b. Run time polymorphism: - Runtime polymorphism or Dynamic Method Dispatch
is a process in which a call to an overridden method is resolved at runtime rather
than compile-time.
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object
being referred to by the reference variable.
#Example:
class Bank{
float getRateOfInterest(){return 0;}
}
class SBI extends Bank{
float getRateOfInterest(){return 8.4f;}
}
class ICICI extends Bank{
float getRateOfInterest(){return 7.3f;}
}
class AXIS extends Bank{
float getRateOfInterest(){return 9.7f;}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
}
}
OUTPUT:-
SBI Rate of Interest: 8.4
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
#Example:
class Shape{
void draw(){System.out.println("drawing...");}
}
class Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle...");}
87
}
class Circle extends Shape{
void draw(){System.out.println("drawing circle...");}
}
class Triangle extends Shape{
void draw(){System.out.println("drawing triangle...");}
}
class TestPolymorphism2{
public static void main(String args[]){
Shape s;
s=new Rectangle();
s.draw();
s=new Circle();
s.draw();
s=new Triangle();
s.draw();
}
}
void channelChange() {}
void colorChange() {}
void volChange() {}
class OperateTv{
Class c=Class.forName(args[0]);
MaterRemote m=(MaterRemote)c.newInstance();
m.channelChange();
m.colorChange();
m.volChange();
88
}
class tv1 extends MaterRemote{
void channelChange() {
89
Final keyword can be used with:
1. class
2. Method
3. Data member
4. Local variable
Final variables
If a variable is declared with the final keyword, its value cannot be changed once
initialized. Note that the variable does not necessarily have to be initialized at the time of
declaration. If it’s declared but not yet initialized, it’s called a blank final variable.
Blank final variables should be initialized in constructor or init block.
Final methods
A method, declared with the final keyword, cannot be overridden or hidden by
subclasses.
// declaring a final method
class Base{
90
}
Final classes
A class declared as a final class, cannot be subclasses it means final class can’t be
inherited.
// declaring a final class
final class FinalClass {
//...
}
class Subclass extends FinalClass{ //attempting to subclass a final class throws an error
//...
}
Final parameters
If you ever see the final keyword with a parameter variable, it means that the value of
this variable cannot be changed anywhere in the function.
class finalParameter {
public static void example( final int parameter ) {
}
}
Abstraction in Java
In java abstract is a keyword which can only be used with:
a. Methods
b. Classes
91
Abstract Method:
If you want a class to contain a particular method but you want the actual implementation
of that method to be determined by child classes, you can declare the method in the
parent class as an abstract.
1. The abstract keyword is used to declare the method as abstract.
2. You have to place the abstract keyword before the method name in the method
declaration. E.g., public void get();
3. An abstract method contains a method signature, but no method body.
4. Instead of curly braces, an abstract method will have a semicolon (;) at the end.
Abstract Class:
A class which contains the abstract keyword in its declaration is known as an abstract
class. E.g., abstract class Employee{ }
1. Abstract classes may or may not contain abstract methods, i.e., methods without a
body. . E.g., public void get();
2. But, if a class has at least one abstract method, then the class must be declared
abstract.
3. If a class is declared abstract, it cannot be instantiated means we can’t create object
of that class.
4. To use an abstract class, you have to inherit it from another class, and also you need
to define/override all the abstract method of that class in your class.
package abstracion;
@Override
public double computePay() {
sal=49000.99;
System.out.println("Salary of developer is "+sal);
return sal;
}
}
class Tester extends Employee{
@Override
public double computePay() {
sal=49000.99;
System.out.println("Salary of Tester "+sal);
return sal;
}
Employee dev;
dev= new Developer();
dev.computePay();
dev = new Tester();
dev.computePay();
}
}
93
Abstraction:-
It is the process of showing the essential functionality of an object and hiding the unessential complexity.
Generic method are those method which have only declaration and it’s implantation are provided by different-2 users
as per need.
Advance:-
Implementing of abstraction:-
1. Class
2. Method
Abstract class:-
When we put the abstract keyword with class then class is called abstract class. we can’t create the object of abstract
class.
Rule:-If any normal class extends the abstract class the normal class need to override all the abstract method of abstract
class otherwise child class have to be abstract.
abstract method:-
Any method become abstract if we use the abstracts keyword with method.
94
Interface.
It is the blue print of class.
It is another way to achieve the abstraction.
It provides the fully implementation of abstraction.
It is the combination public static final data member and public abstract method.
It is the contract between two parties programmer and programming language.
Syntax:-
interface Identifier
{}
Rule:-
1. If a class wants to use and interface then we have to use the implements
keyword.
2. If a class implements an interface then class need to override all the method of
interface with public access specifier otherwise child class need be abstract.
3. A class can implements more than one interface simultaneously and can inherit
another class also. In this case firstly we have use the extends then implements.
4. One interface can extends another interface.
5. One interface can extends more than one interface and this is called multiple
inheritance
6. We can’t create the object of interface but we can have reference variable of
interface.
7. Interface can’t inherit a class.
8. Class can’t inherit interface.
95
96
97
String Handling
int x[];
char c[]={‘j’,’a’,’v’,’a’};
‘A’,‘B’,‘C’. “ABC”
The process of performing operation over the String (length count, con cat, replace, substring etc.) is called String
handing.
1. java.lang.String
2. java.lang.StringBuffer
3. java.lang.StringBuilder
4. java.util.StringTokenizer
String class:-
This class extends object class and implements Serializable , Comparable, Char Sequence interface .
Immutable means in the one object of String we can not perform operation like- insert, delete, update etc.
There are two ways ate used to create the object of String class.
In java all the String literal are treated the String class object.
Note:- In java String , Wrapper classes , array objects can be created without new.
1. In case of without new we are creating the string object memory is allocated in String Constant pool area (part of
method area). Pool areas does not allowed duplicate element. (It means whenever String object is created using
this approach first it check the same name of string object is available or not if not then create a new memry
otherwise share same memory location ). In this approach memory is optimized .
2. In case of new keyword memory is allocated in both area (heap as well as pool area). Here duplicate element are
allowed.
98
String Comparison:-
1. By equals() and equalsIgnoreCase() method
2. By == operator
3. By compare To() and compareToIgnoreCase
length Vs length()
package stringhandling;
String s="surya";
String s1="surya";
String s2="Surya";
System.out.println(s.equals(s2));
System.out.println(s.equalsIgnoreCase(s2));
System.out.println(s==s2);
System.out.println(s.equals(s1));
System.out.println(s==s1);
System.out.println(s.hashCode());
System.out.println(s1.hashCode());
99
TestStr1 t1=new TestStr1();
TestStr1 t3=t1;
TestStr1 t2=new TestStr1();
System.out.println(t1.equals(t2));
System.out.println(t1.equals(t3));
System.out.println(t1==t2);
String Buffer:-
A thread-safe, mutable sequence of characters. A string buffer is like a String but can be modified.
It means in the one object of String Buffer we can do modification like- insert
update etc.
StringBuffer()
StringBuffer(CharSequence seq)
Constructs a string buffer that contains the same characters as the specified CharSequence.
StringBuffer(int capacity)
Constructs a string buffer with no characters in it and the specified initial capacity.
StringBuffer(String str)
100
In case of default constructor of String Buffer when we are creating the object
then it’s default capacity is 16 characters. and when inserted more values beyond
the size of array then this array internally automatically increased with bellow
formula.
Oldlength * 2 + 2
Or
2(Oldlength+1)
StringBuilder:-
A mutable sequence of characters. This class provides an API compatible with StringBuffer, but with no guarantee of
synchronization.
It is not a thread safe class.
Exception Handling :-
There are five keywords are used in java to handle the exception:
1.try
2.catch
3.finall
4.throw
5.throws
All the above are keyword but try, catch & finally are called block and throw and throws are called clause.
101
Exception:-
It is the abnormal situation which occurs in the program at runtime due to this interrupts the normal flow of the
program. And the rest of code will not be executed . In exception handling we learn how to handle this abnormal
situation in the program.
E.g:-
Class A
Stamemt1….
Stamemt2….
Stamemt3….
Stamemt4….
Stamemt5….
Here suppose an exception is occur at statement no-3 so the rest statement will not executed but in exception handling
we handle how to maintain this normal flow of the program.
1. Syntax error
2. Logical error
3. Runtime error
From coding pint of view exception and error is an object is java and it is represented by a class called java. lang.
Exception and java. lang. Error respectively .
In java java .lang package contains so many classes to represent exception and errors and they store in the
hierarchical manner
102
103
try
Java statement-.----------
Java block contains those set of statement where exception may occur.
catch(TypeofExcption refvariable )
{
}
Single try can have multiple catch block but at a time only one catch block is
executed. Because in a single try only one exception occur at a time.
Between try and catch only spaces are allowed not any statement.
Comments are allowed.
If exception occur in try then it directly to go catch means if in this try block
suppose we have 10 statement and exception occur at first statement then
remaining line not reachable(9 statement) .
When exception occur in try block then firstly JVM matches the it’s corresponding
class in the exception hierarchy if It found the matching class then
1. load the exception class.
2. Create the object of exception class
3. Throw the exception object into corresponding catch
4. If corresponding catch is found, then exception is handling and after
executing all statement of catch block the normal flow of program are
maintained.
5. If corresponding catch not found, then JVM put own handler and the normal
flow of program has not maintained.
104
Single Try With Multile Catch Block:-
try
{
}
catch(IllegalArgumentException e){
some code;
}
catch(SecurityException e){
someCode();
}
catch(IllegalAccessException e){
someCode();
}
catch(NoSuchFieldException e){
someCode();
}
try
{
}
catch(IllegalArgumentException e){
some code;
}
try{
catch(SecurityException e){
someCode();
}
try
{
catch(IllegalAccessException e){
someCode();
}
try{
catch(NoSuchFieldException e){
someCode();
}
try{
statement 1;
statement 2;
try{
statement 1;
statement 2;
}
catch (Exception1 e){
105
//statements to handle the exception
}
}
catch (Exception2 e2){
//statements to handle the exception
}
• When nested try blocks used, inner try block is executed first.
• Any Exception thrown in the inner try block is caught the corresponding catch block.
• If matching catch block is not found So catch block of outer block are examining until all nested try statement
exhausted.
• If no matching blocks are found,So java Runtime Ennvironment handles the execution.
106
Is there any situation in which finally will not be execute.
When we explicitly terminating the program.
System.exit(0);
Can a return statement of method stop the finally.
107
Checked Vs. Uncheck Exception :-
Partial Checked Vs. Uncheck Exception :-
Checked exception are known by compiler at compile time and uncheck exception are
known by JVM at runtime.
Throws:- This keyword is used to provide the indication to the end the what type of
exception may occur in the program.
public void show() throws Type of Exception
{
}
Throw:- This keyword is used to throwing an exception explicitly in the program.
The main purpose of throw keyword is used to throw an object of custom exception.
Throw new Type Of Exception ();
Exception Propagation:-
If a method have throws with it. Then we must have to follow the below rule:-
1. If we are calling a method which have throws some exception then into the called
method we need to handle same exception in try and catch otherwise throws
same exception with method.
108
Use of Throws In case of method overriding and Constructor creation :-
1. If parent class method does not throwing an exception.
a. Child class overridden method can throw only unchecked exception
not check exception.
2. If parent class method throwing an exception.
a. Child class method does not throw an exception.
b. Child class method can throws same exception.
c. Child class method can throws child exception but can not throws parent
exception
3. In case of constructor we need to throws same exception and parent exception in
child class constructor.
Custom Exception:-
When we are creating own exception class as per requirement then it is called custom
exception . when ever we are crating custom exception in this case we need extends
some predefine exception class in our own class.
An Exception is said to be fully checked if and only if all the child classes are also checked
exception, otherwise it is called partially checked exception.
Example:
Exception:- partially checked exception, as it's subclasses include both checked and unchecked
Exceptions.
Throwable:- partially checked exception, as it's subclasses include both checked and unchecked
Exceptions.
109
Collection Framework:-
1. It is used to achieve the Data Structure functionality in java.
2. Data Structure is the concept which facilities us to store the in organized manger.
3. It was introduced in JDK1.2.
4. Before jdk1.2 we also achieve the data structure functionality, but they are not a
framework now they are called legacy collection.
5. Collection represent group of object known as element, the object could be
homogenous or heterogeneous.
6. Why collection – so that we can further perform some operation on that –
maximum, short , mail.
7. Difference between collection(array list) and array – array is collection of
homogenous type of data but collection have homogenous as well as
heterogeneous. Once we are creating the array it’s size became fixed and we can
not dynamically increase and decrease the size of array where as in collection
framework it is possible. We can crate the array by both ways without new and
with new but in case collection we are only using new keyword.
int []=new int[10];
Student []=new Student[10];
Object []=new Object[10000];
API:- set of inbuilt libraries or predefined functionality in any language. Whose from is
varies from language to language. In c and C++ it is in the form header file and in java it
is in the form of classes interfaces and package.
Framework :- It is set of API which work on the predefined algorithm and targeted to
specific domain. Framework made the task easy.
Framework Specific domains.
Collection---------------------------------------------------D.S
JDBC----------------------------------------------------------Database connectivity
JEE------------------------------------------------------------WebApp & Enterprise App
Struts----------------------------------------------------------MVC
Hibernate……………………………………………………………..ORM
Spring……………………………………………………………………AOP & IOC etc.
Advantage:- It is use the simplify the development and maintenance of application
software. Framework never wrong output because it is already tested.
110
All the collection framework API are found in java. util. package.
Depending on behaviour collection API’s are categorised in so may parts.
1. List
2. Set
3. Queue
4. Map
From coding point of view collection is the interface and collections is the class.
111
Methods of Collection Interface :-
112
Collection Interface:-
The root interface in the collection hierarchy. A collection represents a group of objects, known as its elements. Some
collections allow duplicate elements and others do not.
List interface:-
It is the child interface of collection which does allowed the duplicate elements and have also features of index.
And also maintain the insertion order of elements.
Implementation(concrete classes ) of List interface:-
1. Array List
2. LinkedList
3. Vector
4. Stack
Array List:- It is the concreate class of List interface , an object of this class is responsible to create a dynamic
resizable array in memory with initial capacity is 10.
Constructor of array list:-
ArrayList()
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's
iterator.
ArrayList(int initialCapacity)
As we know that the initial capacity of arraylist is 10 when we added some more values beyond the size of array so
default it increase the 50 % of actual size.
113
v.v.vImp
Iterator:- It is an interface whose implementation are provided by different-2 collection
as per requirement. An implementing class object of this interface is responsible to
traverse the element in forward direction only.
How to get the object of Iterator:-
Iterator i=arralist.iterator();
Methods of Iterator:-
1. public Object next();
2. public boolean hasNext();
3. public void remove()
How Iterator works internally
Iterator internally uses the concept of iterator pointer to traverse the elements.
By default the pointer position is just first index(-Ve) . next method iterator is use to
traverse the iterator pointer to next Index and return same value where iterator pointer
is available. hash Next() method is used to check the collection data or not of yes the
return true otherwise return false.
List Iterator:-
It is the Child interface of Iterator whose implementation are only provide by List
interface . And It’s implementing class object of this interface is responsible to traverse
the elements in both direction (forward and backword).
Vector:-
Constructs an empty vector so that its internal data array has size 10 and its standard capacity increment is zero.
Constructs a vector containing the elements of the specified collection, in the order they are returned by the
collection's iterator.
Vector(int initialCapacity)
Constructs an empty vector with the specified initial capacity and with its capacity increment equal to zero.
114
Vector(int initialCapacity, int capacityIncrement)
Constructs an empty vector with the specified initial capacity and capacity increment.
Linked List:- It is the concreate class of list interface an object of this class is responsible
to creating doubly linked list in memory apart from doubly linked list this class also
provide the implementation of Queue and Stack.
115
What is Concurrent Modification ?
When one or more thread is iterating over the collection, in between, one thread changes
the structure of the collection (either adding the element to the collection or by deleting the
element in the collection or by updating the value at particular position in the collection) is
known as Concurrent Modification
Fail fast iterator while iterating through the collection , instantly throws Concurrent
Modification Exception if there is structural modification of the collection . Thus, in the
face of concurrent modification, the iterator fails quickly and cleanly, rather than risking
arbitrary, non-deterministic behavior at an undetermined time in the future.
After the creation of the iterator , structure is modified at any time by any method other
than iterator's own remove method.
If one thread is modifying the structure of the collection while other thread is iterating over
it .
Interviewer : How Fail Fast Iterator come to know that the internal structure is
116
modified ?
Iterator read internal data structure (object array) directly . The internal data structure(i.e
object array) should not be modified while iterating through the collection. To ensure this it
maintains an internal flag "mods" .Iterator checks the "mods" flag whenever it gets the
next value (using hasNext() method and next() method). Value of mods flag changes
whenever there is an structural modification. Thus indicating iterator to throw
ConcurrentModificationException.
Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over
the copied data structure.Any structural modification done to the iterator affects the copied
data structure. So , original data structure remains structurally unchanged .Hence , no
ConcurrentModificationException throws by the fail safe iterator.
2. Fail safe iterator does not guarantee that the data being read is the data currently in
the original data structure.
According to Oracle docs , fail safe iterator is ordinarily too costly, but may be more
efficient than alternatives when traversal operations vastly outnumber mutations, and is
useful when you cannot or don’t want to synchronize traversals, yet need to preclude
interference among concurrent threads. The "snapshot" style iterator method uses a
reference to the state of the array at the point that the iterator was created. This array
never changes during the lifetime of the iterator, so interference is impossible and
the iterator is guaranteed not to throw ConcurrentModificationException.The iterator
will not reflect additions, removals, or changes to the list since the iterator was created.
Element-changing operations on iterators themselves (remove(), set(), and add()) are not
supported. These methods throw UnsupportedOperationException.
117
One of the start up java interview questions on Collections topic is difference between
ArrayList and LinkedList , interviewer may also ask to write examples . We already
discussed some other basic interview questions like difference between array and
arraylist , difference between arraylist and vector . In this post difference between arraylist
and linkedlist , apart from the differences , we will also discuss the similarities , examples
and when to prefer arraylist over linkedlist.
a. get(int index) or search operation : ArrayList get(int index) operation runs in constant
time i.e O(1) while LinkedList get(int index) operation run time is O(n) .
The reason behind ArrayList being faster than LinkedList is that ArrayList uses index
based system for its elements as it internally uses array data structure , on the other hand
,
LinkedList does not provide index based access for its elements as it iterates either from
the beginning or end (whichever is closer) to retrieve the node at the specified element
index.
In LinkedList adding or insertion is O(1) operation . While in ArrayList, if array is full i.e
worst case, there is extra cost of resizing array and copying elements to the new array ,
which makes runtime of add operation in ArrayList O(n) , otherwise it is O(1) .
While in ArrayList remove(int) method involves copying elements from old array to new
updated array , hence its run time is O(n).
In real world applications , you will more frequently use ArrayList than LinkedList. But in a
very specific situations LinkedList can be preferred.
1. ArrayList is preferred when there are more get(int) or search operations need to be
performed as every search operation runtime is O(1).
Lambda Expression:-
119
Set interface:-
It is the interface which does not have any extra method it only changes the behaviour
of add method in such a way that it does not allowed duplicate element. And not
maintaining order as well.
Implementation of Set interface: -
1. Hash Set
2. Linked Hash Set
Map Interface:-
It is the part of collection framework but not a collection(because of it does not extends
collection interface).
It store the data in the form of key and value pair.
Internally map interface uses the Entry interrace
hashMap
Linkedm
120
JDBC (Java Database Connectivity)
It is the API by which we can connect a java program with data base.
All JDBC API’s are available in java.sql package.
Any database provides following ways to store the data-
1. CUI
2. GUI
3. API
There are furthers following ways are used to work with API-
1. By using vender specific API
2. By using ODBC API
3. By using JDBC API
121
Commonly used JDBC classes & Interface (JDBC API):-
1. Driver(I)
2. DriverManager(C)
3. Stataement(I)
4. PreparedStatement(I)
5. ResultSet(I)
6. Callable(I)
7. Connnection(I)
8. SQLException(C)
9. ResultSetMeteData
DatabaseMeta Data
Etc.
Steps to connect a java program with any database:-
1. Register the Driver With Driver manager in your java program.
122
123
Task-
1.Single Task
It is the process of executing only one task at a time.
2.Multitasking-
It is the process of executing multiple task simultaneously at a time.
Multitasking is the just a concept its implementation is provided by –
1.Process
2.Thread.
MultiProcessing.
MutiThreading.
124