0% found this document useful (0 votes)
139 views423 pages

Core J

Uploaded by

subham220915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
139 views423 pages

Core J

Uploaded by

subham220915
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 423

Importance of CORE JAVA:

 Every Software Company Starts technical interviews right from CORE JAVA only
 If you attend any JAVA based Interview, 70% of the Questions are coming from
CORE JAVA only.
 If you are Strong in CORE JAVA then it is very simple to clear any type of technical
written test on java.
 If you are Strong in CORE JAVA getting Job is very Easy.
 If you are Strong in CORE JAVA learning any Java based technologies like Jdbc,
Servlets, Jsps,... and the frameworks like struts, JSF, hibernate, Spring,... are very
easy.
 Every real time project implementation is provided in core java only even though
projects are using the frameworks like struts, JSF, Hibernate, Spring.

Why NAGOOR BABU sir CORE JAVA:

 Covered Core java topics in more depth.


 Provide live execution for each and every program in the class itself.
 Very good notes dictation for each and every topic which contains 1000+ pages.
 Certification Oriented training on each and every topic.
 Conducting classes Even in Sundays for the benefit of Students i.e Covering each
and every topic from scratch and also to complete course with in the time.
 Reviewing previous day topic before starting the class.
 Conducting interview questions sessions at the end of each and every topic.
 Covering interview questions and answers in detail in the notes dictation.
 Providing 2 mini projects on core java.

Java Details:

Home SUN Mc Systems.[ Oracle Corporation]

Author James Gosling.


Objective To prepare simple electronic consumer
goods.
Project Green
First Version JDK1.0 [1996,Jan]
Used version some org JDK5.0, some other JAVA6
Latest Version JAVA7,JAVA8
Type of Software open source software.
Strong Features Object-oriented, Platform Independent,
Robust, Portable, Dynamic, Secure..
Java Evolutions

Version Code Name Enhancements

1.JDK1.0[Jan,23,1996] OAK Language Introduction


2.JDK1.1[Feb,19,1997] ----- Java Beans,Inner classes
RMI,JDBC,Reflection API
3.JDK1.2[Dec,8,1998] Playground Strictfp,Swing,CORBA,
Collection Framework
4.JDK1.3[May,8,2000] Kestrel Updations on RMI,JNDI
5.JDK1.4[Feb,6,2002] Merlin Regular Expression, NIO,
assert keyword,JAXP,...
6.JDK5.0[Sep,30,2004] Tiger Autoboxing, var-arg method,
static import,Annotations,..
7.JAVA SE6[Dec,11,2006] Mustang JDBC4.0,GUI updations,
Console class.
8.JAVA SE7[July,28,2011] Dolphin Strings in switch
'_' symbol in literals
try-with-resources
9.JAVA SE8 [Mar,18,2014] spider interface improvements
Lambda Expression
Date-Time API
Updations on Collections

J2SE:[Core Java]

1)Introduction:
1)Java History

2)Differences between java and others

3)Java Features

4)Java Naming Conventions

5)Java Programming Format

2)First Java Application Development:


1)Java Installation

2)Editor

3)Java Application and Java File Saving.

4)Compile Java File


5)Execute Java Applications.

3)language Fundamentals:
1)Tokens

2)Identifiers

3)Literals

4)KeyWords/Reserved WordS

5)Operators

2)Data Types and Type casting

3)Java Statements

4)Arrays

4)OOPS:
1)Types of Programming Languages

2)Unstructered Programming Languages

3)Structered Programming Languages

4)Object Oriented Programming Languages

5)Aspect Oriented Programming Languages

6)Object Oriented Features

7)Class,Object,encapsulation,abstraction,inheritance,Pol,MP

8)Object Based PL VS Object Oriented PL

9)class syntax

10)Method Syntax

11)Var-arg method.

12)Accessor Methods VS Mutator Methods

13)Syntax to create an object

14)Immutable Objects VS Mutable Objects

15)Object Vs Instance

16)Constructors
1)Default Con.

2)User defined con.

1)0-arg-con.

2)param-con.

17)Instance Context

1)instance variable

2)instance method

3)instance block.

18)this keywords

19)static keyword

1)static variable

2)static method

3)static block

4)static import

20)main() method

1)public static void main(String[] args)

2)why public?

3)why static?

4)why void?

5)why main

6)why String[] as parameter?

7)is it posible to overload main(-) method?

8)is it posible to override main(--) method?

9)is it posible to provide more than one main(--) method with in a single
java appl?

10)is it posible to execute any java application without using main


method?

21)Factory Method
22)Singleton classes and Doubleton classes

23)final

1)final variable

2)final method

3)final class

24)enum keyword

25)Inheritance

1)IS-A Vs HAS-A Vs USE-A

2)Assiciations

3)one-one

4)one-many

5)many-one

6)many-many

26)Types of inheritance

1)single, multiple, multilevel, hierarchical, hybrid.

2)Staic flow in inheritance

3)constructors in inheritance

4)instance flow in inheritance

5)super keyword

6)class level type casting

27)Poly Morphism

1)static PM

2)method oveloading

3)Dynamic PM

4)method overriding

28)Abstract Methods Vs Concreate Methods

29)Abstract class Vs concreate Class


30)class Vs Abstract class Vs interface

31)"instanceof" operator

32)what is Adapter class?

33)What is marker interface?

34)Object Cloning

1)Shallow Cloning

2)Deep Cloning

35)JAVA8 features in interfaces

5)Inner classes:
1)Member Inner class

2)Static Inner class

3)Method local Inner class

4)Anonymous Inner class

6)Wrapper classes:
Byte, Short, Integer, Long, Float, Double, Boolean, Character

7)Packages:
1)What is a package?

2)Adv. of packages

1)Modularity

2)Abstraction

3)Security

4)Reusability

5)Sharability

3)Types of packages

1)Predefined packages

2)User defined packages

4)Jar file preparation


5)Executable Jar files

6)Batch file preparation

8)String manipulations:
1)String

2)StringBuffer

3)StringBuilder

4)StringTokenizer

9)Exception Handling:
1)Error VS Exception

2)Exception Def.

3)Types of Exceptions

1)Predefined Exceptions

2)User defined Exceptions

4)Checked Exception VS Unchecked Exception

5)Pure Checked Exceptions Vs Partially Checked Exceptions

6)throw Vs throws

7)try-catch-finally

8)Custom Exceptions

9)Java7 Features in Exception Handling

1)Automatic Resource management

2)Multi catch block.

10)Multi Thredding:
1)process Vs Proccessor Vs Procedure

2)Single Proccessing Mech. Vs Multi Proccessing Mech.

3)Single Thread model And Multi Thread Model

4)Thread Design

1)Extending Thread class


2)Implementing Runnable interface.

5)Thread lifecycle

1)New/Born

2)Runnable

3)Running

4)Blocked

5)Dead

6)Thread class library

1)sleep()

2)join()

3)yield()

4)stop()

7)Daemon Thread

8)Synchronization

9)Inter Thread communication

1)wait()

2)notify()

3)notifyAll()

10)Deadlocks

11)IOStreams:
1)What is stream?

2)Types of Streams?

1)Byte-oriented Stream

1)InputStreams

2)OutputStreams

2)Character-Oriented Streams

1)Reader
2)Writer

3)FileInputStream Vs FileOutputStream

4)FileReader Vs FileWriter

5)File Vs RandomAccessFile

6)Serialization vs Deserialization

7)Externalization

12)Networking:
1)Standalone Appl. Vs Distributed Appl.

2)Client-Server Arch.

3)Socket Vs ServerSocket

4)Network Appl. Arch.

5)Socket Programming.

13)Collection Framework:
1)Collection Arch.

2)List and its implementations

1)ArrayList

2)Vector

3)Stack

4)LinkedList

3)Set and its implementations

1)HashSet

2)LinkedHashSet

3)TreeSet

4)Map and its implementations

1)HashMap

2)Hashtable

3)Properties
4)TreeSet

5)Queue and its implementations

1)Priority Queue

2)Blocking Queue

3)Priority Blocking Queue

4)Linked Blocking Queue

6)Iterators

1)Iterator

2)ListIterator

3)Enumeration

14)AWT:
1)TextField,TextArea,Button,Label,CheckBox,List,.....

15)Swing:
1)JTextField,JPasswordField,JCheckBox,JRadioButton,JColorChooser,...

2)Event Delegation Model

16)I18N:
1)NumberFormat

2)DateFormat

3)ResourceBundle

17)Reflection API:
1)Class

2)Field

3)Method

4)Constructor
18)Annotations:
1)What is Annotation?

2)Adv of annotations

3)Comments Vs Annotations

4)Types Of annotations

1)Built-in Annotations

@Override

@Deprecated

@SupressWrnings

@Documented

@Inherited

@Target

@Retention

2)User Defined Annotations

19)Remote Method Invocation[RMI]:


1.Introduction

2.RMI Architecture

3.Steps To Design RMI Application

4.Parameters In Remote methods

20)Regular Expressions:
1.Introduction

2.Pattern

3.Character

4.Quantifiers
21)Garbage Collector

22)JVM Arch.

23)Generics

24)Basics of JDBC

25)Basics of XML

Introduction:

Java was Introduced in 1996 January.But it was started by Sun MicroSystems in 1991.

At that time Sun MicroSystems had a requirement to prepare a software electronic


consumer devices in 1991.They need a programming language to prepare those devices.

30 members team with James Gosling & patrickNaughton starts "Green" project.For this
project they need a simple programming language that is simple,tight coded and
architectural neutral programming language.

How can we justified that programming language is Simple....?

Ans:The electronic consumer devices with less memory,less power,less execution time the
programming language which is used to prepare these devices must be simple programming
language.

For Example:I want to prepare stack operation in "C"

Stack Output:

1.push ----> 15 to 20 lines of code we need

2.pop ----> 15 to 20 lines of code we need

3.peep ----> 15 to 20 lines of code we need

--------------------------------------------------

Total ----> 45 to 60 lines of code we need


JAVA:

To perform stack operations.

Ex:

Stack s=new Stack();

s.push("A");

s.pop();

s.peep();

-----------------------------

4 lines of code we need to write stack operations in Java

To write less no.of instructions in a programming language,then that is called as tight coded
programming language.It achieving more complex requirements.

Q)What is Architectural Neutral?

Ans:Number of electronic devices manufactures are available in now a days like


Panasonic,LG,Sony,Samsung...etc.They have their own remote controllers.Each remote
controller have their own hardware Architecture.These architecture differ from
manufacturer to manufacturer.If they want my software,after the demonstration,then I sell
my product to Sony Company(If it accept my Quotation).

If my software is compatible to,then there is no possible to run my software on H2 and H3


hardware devices.Then my business is down.If I wanna to go to improve my business,my
software product should not compatible to only one hardware i.e my software is hardware
independent.It increases my business.It is called "hardware neutral software" in another
way.

To prepare this hardware independent software,I used programming language.This


programming language should be common to all hardware systems.That programming
language is called as independent "Architectural Neutral Programming language".

Operating System independent ===> platform Independent.

In 1991,one programming language is famous at that time i.e PASCAL it is implemented by


"Niclous Wirth" (Invented of Pascal).

He gave a software to James Gosling on the base of PASCAL programming


language(Procedure Oriented programming language).But James Gosling expected object
oriented programming language.So he rejected the solution given by Niclous Wirth.
Because all the team members came from Object Oriented
background.Because of this mismatch they rejected the PASCAL Programming Language
solution.So in 1992,December,James Gosling and his team create a new programming
language.

James Gosling always likes to see a "Oak Tree" through his cabin
window.Immediately he thought to put this "Oak" name for his new programming
language.But his team rejected this name.Because this "Oak PL" is already existed.So all
the Green Project people think a new name for a new Programming language.

While they are doing Green project,they used to go a cafeteria in Sun


MicroSystems.They drank a Coffee daily that is named as "JAVA".So they decided to keep
"JAVA" is a name for new programming language.

Java is one of Island in Indonesia.Java is famous for coffee trees.So that


symbol for Java T.B is Coffee cup and a saucer with flames.

Dec 1992:

The first product prepared on Java is "*7".It is a remote controller.But unfortunately,no


customer had an internet to take this product upto 1994.It is a failure product.

In the middle of 1994,very good boom is available for "www" internet.People


are identified a key role for www is "browser".The name of this browser is "Musaik".It is
prepared by "Mark Anderson".He is an under graduate student.He went to Netscape
communication to prepare "Musaik Browser".He got a stipend 6.25$ per hour at Netscape
Communication.

Then Sun MicroSystems decided to prepare its own browser.So patrik Naughton
and Janadhan paine in 1995,Dec prepared "Hot Java" browser using Java programming
language.

Sun MicroSystems got very good reputation for this "Hot Java Browser". The key
concept for this browser is "Applets" so in January 23,1996--->JDK 1.0 version released.

Now Java 8.0 version is introduced in Mar 2014


Java Details:

Home SUN Mc Systems.[ Oracle Corporation]

Author James Gosling.


Objective To prepare simple electronic consumer
goods.
Project Green
First Version JDK1.0 [1996,Jan]
Used version some org JDK5.0, some other JAVA6
Latest Version JAVA7,JAVA8
Type of Software open source software.
Strong Features Object-oriented, Platform Independent,
Robust, Portable, Dynamic, Secure..

Java Evolutions:

Version Code Name Enhancements

1.JDK1.0[Jan,23,1996] OAK Language Introduction


2.JDK1.1[Feb,19,1997] ----- Java Beans,Inner classes
RMI,JDBC,Reflection API
3.JDK1.2[Dec,8,1998] Playground Strictfp,Swing,CORBA,
Collection Framework
4.JDK1.3[May,8,2000] Kestrel Updations on RMI,JNDI
5.JDK1.4[Feb,6,2002] Merlin Regular Expression, NIO,
assert keyword,JAXP,...
6.JDK5.0[Sep,30,2004] Tiger Autoboxing, var-arg method,
static import,Annotations,..
7.JAVA SE6[Dec,11,2006] Mustang JDBC4.0,GUI updations,
Console class.
8.JAVA SE7[July,28,2011] Dolphin Strings in switch
'_' symbol in literals
try-with-resources
9.JAVA SE8 [Mar,18,2014] spider interface improvements
Lambda Expression
Date-Time API
Updations on Collections
Differences between Java and Others[C and C++]

1.C and C++ are Static programming Languages But Java is a dynamic
programming language:

If any programming language allows memory allocation at compilation time then that
programming language is called as Static programming language.

Ex: C and C++

In C and C++,memory will be allocated for the primitive data Types at compilation time
only.

If any programming language allows memory allocation at runtime then that programming
language is called as Dynamic Programming language.

Ex: JAVA

In Java applications,memory will be allocated for the primitive dataTypes at runtime


only,because,in Java applications objects will be created at runtime.

2.C and C++ are required pre-processor but Java is not required pre-processor:

In case of C and C++,the complete predefined library in the form of header files.

Ex:stdio.h

conio.h

math.h

If we want to include header files in C and C++ applications we have to use "#include<>"
statements.

Ex: #include<stdio.h>

#include<conio.h>

#include<math.h>

If we compile C and C++ application,pre-processor will recognize #include<> statements


and pre-processor will load the specified header files content to the memory at compilation
time, this type of loading is called as "Static loading".
In C and C++ applications,it is mandatory to use header files and #include<> statement so
that pre-processor is required in C and C++.

In case of Java,the complete predefined library is provided in the form of "packages".

Ex: java.util

java.io

java.net

In Java applications,if we want to include packages then we have to use "import"


statement,not #include<> statement.

Ex: import java.util.*;

import java.io.*;

import java.net.*;

when we compile java files compiler will recognize import statements, where compiler will
check whether the specified packages are available or not,if not, compiler will rise an error
like "package java.util does not exist".If the specified package is available in java predefined
library then compiler will not load package content to the memory, at runtime JVM will load
the required classes or interfaces of the specified package, this type of loading is called as
"Dynamic Loading".

In Java, include<> statements are not available, so that,Pre-Processor is not required in


Java.

Q)What are the differences between #include<> statement and "import"


statement?

1.#include<> statement is available in C. import statement is available in Java.


2. #include<> statement can be used to import statements can be used to include
include the predefined library specified with the predefined library specified with
header files. packages.
3. #include<> statements will be recognized import statements will be recognized by the
and executed by the pre-processor. compiler.
4. #include<> statement will provide static import statement will provide dynamic
loading. loading.
5. If we want to include more than one If we want to include more that one class or
header file in C and C++ applications then interface of the same package then it is
we have to use sufficient
more than one #include<> statements. to use single import statement with '*'
Ex: #include<stdio.h> notation.
#include<conio.h> Ex:import java.util.*;
#include<math.h>
Internal Mechanism of „C‟ Compilation

3.C and C++ are platform Dependent but Java is platform independent:

If any programming language allows its applications to compile and to execute on the same
operating system then that programming language is called as "Platform Dependent
Programming Language".

Ex: C and C++

If we compile C program on windows operating system then compiler will generate .obj or
.exe file with the same windows operating system representations.If we want to execute C
program then we must require the same windows operating system,this nature of C
programming language is "Platform Dependent Programming Language".

Compilation of “C”

If any programming language allows its applications to compile on one operating system
and to execute on another operating system then that programming language is called as
"Platform InDependent Programming Language".

Ex: JAVA
If we compile Java program on windows operating system then compiler will generate .class
file, it is neutral every operating system, which contains bytecode,it is an intermediate code,
it is not directly executable code. If we want to execute neutral bytecode then we must
require converters to convert neutral bytecode to the local operating system
representations.

To perform the above conversions and to make Java as platform independent programming
language,Sun MicroSystems has provided a tool called as "JVM"[Java Virtual Machine].

NOTE:Java is a platform independent programming language due to the


availability of JVM.

NOTE:Java is a platform independent programming language but JVM is platform


dependent tool.

Compilation of JAVA

4.Multiple inheritance is not possible in Java:

The process of getting variables and methods from one class to another class is called as
Inheritance.

The main objective of inheritance is to provide "Code Reuseability".

There are two types of inheritances at basic level of Object orientation.


1.Single Inheritance

2.Multiple Inheritance

1.Single Inheritance:

The process of getting variables and methods from only one super class to one or more
no.of subclasses is called as Single Inheritance.

2.Multiple Inheritance:

The process of getting variables and methods from more than one super class to one or
more no.of sub classes is called as Multiple Inheritance.
If we declare same variable with different data and same method with different
implementation at both the super classes in multiple inheritance and if access that variable
and that method in sub class then which super class variable will be accessed and which
super class method will be accessed is a confusion state.
Java is a simple programming language,it should not allow confusion oriented feature,so
that multiple inheritance is not possible in Java

5.pointers are available in C and C++ but pointers are not possible in JAVA:

pointer is a variable, it able to store the starting address location of a dataStructurer,where


the dataStructurer may be a variable,an array or another pointer variable.

Pointers are not possible in JAVA, because

1.Pointer variables will be recognized and initialized at the time of compilation, pointer
variables must require static memory allocation but JAVA is following dynamic memory
allocation.

2.Pointer variables could be supported by static programming languages.

3.Pointer variables are suitable for platform dependent programming language but Java is
platform independent programming language.

4.pointer variables will reduce security for the application data but Java is more secure
programming language,it has to provide very good security for the application data.

5.Pointers will increase confusion to the developers but Java is a simple programming
language, it should not provide confusion to the developers.
6.Destructors are required in C++ but Destructors are not required in JAVA:

In Object Oriented programming languages, it is convention to create objects at beginning


in order to store data and it is convention to destory object at the end of our application.

In Object Oriented Programming language,to create objects we will use "constructor" and to
destroy objects we will use destructors.

In case of C++,developers must take responsibility to create objects and to destroy object,
with this, developers must require both constructors and destructors.

In case of Java, Developers should take responsibility only to create object, not to destroy
objects will be destroyed automatically by an implicit tool called as "Garbage Collector".

Due to the availability of "Garbage Collector" in Java it is not required to use Destructors in
Java.

Due to the unavailability of "Garbage Collector" in C++,it is required to use Destructors in


C++

7.Operating overloading is not possible in Java:

Declaring one operator with multiple operations or functions is called as


OperatorOverloading.

Operator overloading is not possible in Java,because,

1.Operator overloading is a rarely used feature in the application development.

2.Operator overloading is able to increase confusion to the developers.

NOTE:Java has declared some few predefined operators like +,*...as overloaded operators
implicitly,but Java has not given any environment to do operator overloading explicitly at
developers level.

Ex: int a=10;

int b=20;

int c=a+b;// + operator is used to perform arithmetic addition.

String str1="abc";

String str2="def";

String str3=str1+str2;//here + is used for String concantation.


8.C,C++ are following "call by value" and "call by reference" parameter
passing mechanism but Java is following only "call by value" parameter
passing mechanism.

In any programming language,if we pass primitive data as parameters to the methods then
the parameter passing mechanism will be call by value.

In any programming language,if we pass address location as parameter to the methods


then the parameter passing mechanism will be "call by reference".

In the case of C and C++,if we pass pointer variable as parameter to the methods then the
parameter passing mechanism will be "call be reference" because, pointer variable are able
to store address location directly.

In the case of Java,if we pass reference variables as parameter to the methods then the
parameter passing mechanism will be call by value only,because,in Java application
reference variables are able to store object reference variable value,which is not address
location.

9.In C and C++,2 bytes of memory is allocated for integer and 1 byte of
memory is allocated for characters but in Java 4 bytes of memory is allocated
for integers and 2 bytes of memory is allocated for character.

In general,in C and C++,memory allocation for the primitive dataTypes is not fixed,which is
variable depending on type of operating system which we used.

In case of Java,memory allocation for the primitive dataTypes is fixed irrespective of the
operating system which we used.In case of Java,4 bytes of memory is allocated for integers
and 2 bytes of memory is allocated for characters.

Java Features:

To expose the nature of Java, Java has given the following features:

1.Simple

2.Object Oriented

3.platform Independent

4.Arch.Neutral

5.Portable
6.Robust

7.Secure

8.Dynamic

9.Distributed

10.Multi Threaded

11.Interpretive

12.HighPerformance

1.Simple:

Java is a simple Programming language,

Java has eliminated all the confusion oriented features like multiple inheritance,operator
overloading,pointers...

Java applications will take less memory and less execution time.

Java is using all simplified syntaxes of C and C++.

2.Object-Oriented:

Java is Object-Oriented Programming language,because it able to store the data in the form
of objects.

3.platform Independent:

Java is platform independent programming language,because it able to allow its


applications to compile on one operating system and it will execute on another operating
system.

4.Arch.Neutral:

Java is Arch.Neutral Programming language because it able to allow its applications, to


compile one hardware arch.system and to execute on another hardware arch.system.
5.Portable:

Java is portable programming language because it able to allow its applications on any
operating system and also to execute on any hardware system.

6.Robust:

If any programming languages is having very good at memory management system and
also exception handling features then that programming language is called as Robust
programming language.

Java is Robust programming language,because,

Java is having very good at memory management System that is


HeapMemory,StackArea,Method Area.. and also memory management system will take only
at runtime in Java.

java is having very good at exception handling mechanisms due to the availability of very
good predefined library to represent each and every exceptional features.

7.Secure:

Java is a very good secure programming language,because,

Java is having a separate component like "securityManager" as part of JVM to provide


implicity Security.

Java is having a separate middle ware service in the form of "JAAS"

[java Authentication and Authorization Service] to provide web Secuirty.

Java has provided implementation for all the network security algorithm to provide network
security.

8.Distributed:

If we design any Java application with out using client-server arch. then that

application is called as "standalone application".

If we design any Java application using client-server arch. then that

application is called as "Distributed application".


9.Multi-Threaded:

Thread is a flow of execution to perform a particular task.

There are two types of thread Models:

1.Single Thread Model

2.Multi Thread Model.

Single Thread Model will allow only one thread at a time to perform tasks,it increase
execution time,it decrease application performance.

Multi Thread model is able to allow to create and execute more then one thread at a time,

it will reduce application execution time,it will improve application performance.

Java is a multi threaded programming language,it will provide very good environment to
design and execute more than one thread at a time.

11.Interpretive:

Java both compilative and inteprative programming language. because,

1)To check use provided syntax voilations we must require compilation for Java program.

2)To execute Java program,we must require an interpreter inside JVM.

12.HighPerformance:

Java is a high performance programming language due to its rich set of features like
Robust,Dynamic,Secure,object oriented,platform Independent...

Java Programming Format:

To design java applications,we have to use the following Structure.


Comment Section:

 As part of java applications development,it is convention to provide description about


our application before starting application implementation,here the description may
contain objective of implementation,Author details,Clients information,dead line
details,module details...
 In the above context,to descrobe the above information we have to use Comment
Sction,where we have to use Comments.

There are three types of comments in java:

1.Single Line Comment:

It will allow the description with in a single line.

Syntax:

//------description-------

2.Multi Line Comment:

It will allow the description in more than one line.


Syntax:

/*

----

---Description----

----

*/

3.Documentation Comment:

It will allow the description in more than one page.

Syntax:

/*

*---------------

--------

*-------

*/

In general we will utilize documentation comment to prepare API documentation but it is not
suggestable or recommended.

NOTE:API documentation is a document,which contains the description about


classes declarations,constructors declarations,variables declarations,method
declarations....

To simply API documentation,JAVA has provided a predefined tool in the form "javadoc".

C:\abc\Employee.java

/* Programme for preparing JAVADOC*/

public class Employee{

public static final String eid;

public String ename;

public float esal;

public String eaddr;


public Employee(String eid,String ename,float esal,String eaddr){}

public void add(String eid,String ename,float esal,String eaddr){}

public void search(String eid){}

public void delete(String eid){}

c:\abc>javadoc Employee.java

In java applications,to describe metadata JDK5.0 version has provided a new feature called
as "Annotation".

Q)To describe metadata in java applications,already we are using comments then


what is the requirement to go for "Annotations"?

Ans:In java applications,if we provide metadata by using comments then that metadata will
be available upto .java file,it will not be available upto .class files and upto RUNTIME of our
application,because,LexicalAnalyzer will remove the provided commented metadata from
Java application as part of compliation.

As per the application requirement,if we want to bring the metadat upto .java file,upto
.class file and upto RUNTIME of our application then we have to use "Annotation".

Q)In Java applications to provide metadata at runtime we are able to use XML
documents but what is the requirement to go for annotations?

Ans:To provide metadata upto runtime of our java applications if we use XML documents
then we are able to get following problems:

1)We must learn XML technology.

2)We have to check whether XML documents are located properly or not.

3)We have to check whether XML tags are formatted properly or not.

4)We have to check whether we are using right parsing mechanism or not to access the
data from XML documents.

To Overcome all the above problems we have to use a java alternative that is
"Annotations".

Example:

If we want to design any servlet by using XML document then we have to provide almost all
10 lines of code in XML file.

web.xml:

<web-app>
<servlet>

<servlet-name>ls</servlet-name>

<servlet-class>LoginServlet</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>ls</servlet-name>

<url-pattern>/login</url-pattern>

</servlet-mapping>

</web-app>

LoginServlet.java

public class LoginServlet extends HttpServlet{

--------

If we design any servlet by using annotations then it is sufficient to provide only one line of
java code[Annotation]

@webServlet("/login")

public class LoginServlet extends HttpServlet{

--------------------

NOTE:In JAVA/J2EE applications,we can utilize annotations as an alternative for XML tech or
XML documents.

XML-Based Tech Annotation Based Tech

JDK 1.4 JDK 5.0 and above


JDBC 3.0 JDBC 4.0
Servlets2.5 Servlets3.x
Struts1.x Struts2.x
JSF1.x JSF2.x
Hibernate3.2.2 Hibernate3.2.5
Spring2.x Spring3.x
EJBs2.x EJBS3.x
2.Package Section:

 Package is a collection of related classes and interfaces as single unit.

In java,packages will provide the following advantages

1.Modularity

2.Abstraction

3.Security

4.Sharability

5.Re usability

There are two types of packages in java:

1.Predefined packages

These packages are provided by java along with software.

Ex: java.io

java.util

java.awt

2.User-defined Package

 These packages are provided by the developers as per their


application requirements.
 To declare user defined packages in java program we have to use "Package section".

If we want to declare user defined packages in java programme then we have to use
the following Syntax.

package Package_Name;

where package declaration statement should be first statement

after comment section in java program.

Where package_Name must be unique,it should not be duplicated and it should not
be sharable.

To provide package names,Java has a given convention like to include our company
domain name in reverse.
Ex:

package com.durgasoft.icici.transaction;

com.durgasoft---->company domain name in reverse

icici--------->client name/project name

transaction---->module name

Q)Is it possible to provide more than one package declaration statements


with in a single java file?

Ans:No,it is not possible to provide more than one package declaration statements
with in a single java file,because,always package declaration statement must be first
statement in java file

Ex:

abc.java

package p1;----valid

package p2;--->Invalid

package p3;--->Invalid

import Section:

 In general,we are able to design java applications by distributing all the classes and
interfaces over multiple no of packages.
 In the above context,if we want to use a particular package classes and interfaces in
the present java file,first,we have to make available that package provided classes
and interfaces to present java file.
 To make available a particular package provided classes and interfaces to the
present java file,we have to import the respective package to present java file

To import a particular package into present java file,we have to use the following
syntaxes.

import package_Name.*;

It will import all the classes and intefaces from the specified package.
Ex:

import java.io.*;

import package_Name.Member_Name;

It will import only the specified class or interface from the specified package.

Ex:

import java.io.BufferedReader

Q)Is it mandatory to import packages to use classes and interfaces of a particular


package in present java file?

Ans:No,It is not mandatory to import packages in java file inorder to use the classes and
interfaces of a particular package,because it is possible to use classes by using their fully
qualified names without using "import" statements.

NOTE:Specifying classes along with their package names is called as Fully


qualified name.

Ex:java.io.BufferedReader,java.util.ArrayList

java program with import statement:

import java.io.*;

BufferedReader br=new BufferefReader(new InputStreamReader(System.in));

java program with out import statement:

java.io.BufferedReader br=new java.io.BufferedReader(new


java.io.InputStreamReader(System.in));

NOTE:In java files,we are able to provide at most one package declaration
statement but we are able to provide more than one import statement.

classes/interfaces section:

 In java applications,the main purpose of classes and interfaces is to represent all real
world entities like Persons,Animals,Students,Customers,Account....
 In java program,to write classes and interfaces we have to use classes/interfaces
section.
 In java files,we are not having any restrictions about the no classes and interfaces,it
is possible to provide any no of classes and interfaces with in a single java file but it
is suggestable to provide one class or one interface per java file.
Note:In java,a single .java file may contains more than one class but a
single .class file contains only one class or one interface.

Main class Section:

The purpose main() method in java application is,

1.To manage application logic in java applications.

2.To define starting point and ending point for the application execution.

Note:In general,main() method starting point is the starting point of the


application execution and main() method ending point is the ending point of
the application execution.

 In java applications,we will provide main() method in a class called as "Main Class",it
is mandatory for each and every java application beacuse main() method is
mandatory to start application execution.

Steps To Design First Java Application:

1.Install java Software

2.Select Java Editor

3.Write Java Program

4.Save java File

5.Compile JAVA File

6.Execute Java Application

1.Install JAVA Software

2.Download jdk-7-windows-i586.exe file from Internet

3.Double Click on jdk-7-windows-i586.exe file.

4.Click on "Yes" button

5.Click on "Next" button

6.Change "JDK" installation location from "c:\program Files\java\JDK1.7.0" to


"c:\java\jdk1.7.0"

by click on "Change" button


7.Click on "Next" Button

8.Change "JRE" installation location from "c:\program Files\java\JDK1.7.0" to


"c:\java\jdk1.7.0"by click on "Change" button

9.Click on "Next" Button

10.Click on "Finish" button

After installation of JDK and JRE software's as part of Java installation process we
have to set

"C:\java\jdk1.7.0\bin" location to "path" environment variable

To set "path" environment variable temporarily we have to use the following


command on command prompt.

set path=c:\java\jdk1.7.0\bin;

The above command is valid upto the present command prompt.we want to set
"path" environment variable permanently,we have to use the following procedure.

a)Right click on Computer[Desktop icon]

b)Select "properties"[Last option]

c)click on "Advanced System settings"[in Windows7 and above]

d)click on Advanced[By default it is selected]

e)Click on "Environment Variables" button

f)Click on "New" button in User Variables section

g)Provide variable name and variable value

variable name:path

variable value:c:\java\jdk1.7.0

h)Click on "OK" button

i)Click on "OK" button

j)Click on "OK" button


If we want to switch one version of java to another version of java in a simplified
way then we have to use batch files with the following steps.

a)Take a normal text file

b)Provide "path" command

c)Save text file with ".bat" extension

d)open command prompt,go to the batch files location,type batch file name and click
on enter button

java6.bat

set path=c:\java\jdk1.6.0_11\bin;

java7.bat

set path=c:\java\jdk1.7.0\bin;

on command prompt

d:\java7>java6.bat ----> enter button

Select Java Editor:

Editor is a software or tool,it will provide very good environment to type and save
programs.

Ex:NotePad,EditPlus,NotePad++........

Note:Editors are not suggestible or not sufficient to design real time


projects,IDEs are suggestable to design real time projects.

Ex:Eclipse,MyEclipse,NetBeans,JDeveloper.....

Write JAVA Program:

In general,to design java programme some predefined library

provided by JAVA API[Application programming Interface].

4.Save JAVA File:

To save java file,we have to follow the following two rules and regulations.
1.If any public class,abstract class,interface and enum is identified in java file then
we must save that java file with public element name only,if we violate this condition
then complier will raise an error.

2.I f no element is public in java file then it is possible to save java file with any
name like abc.java,xyz.java but it is suggestible to save java file with main() method
class name

NOTE:All the java files are able to allow atmost one public
element[class,abstract class,interface,enum] NO java file is able to allow
more than one public element.

abc.java

class A{

Status:Valid

abc.java

class B{

public static void main(String[] args){

}}

Status:valid,but not suggestable

abc.java

public class Abc{

public static void main(String args[]){

}}

Status:invalid

A.java

public class A{

}
class Test{

public static void main(String args[]){

Status:Valid

A.java:

public class A{

public class B{

}}

Status:Invalid

A.java:

public class A{

public static void main(String args[]){

}}

public class B{

Status:InValid

Compile JAVA File:

1.The main purpose of compiling JAVA file is to convert JAVA programme from
HighLevelRepresentation to LowLevelRepresentation.

2.To Check compilation errors.

To compile JAVA file,we have to use the following command on command prompt
from the location where JAVA File is Saved

javac File_Name.java

Ex:

d:\java7>javac FirstApp.java
If we use the above command on command prompt then operating System will
perform the following actions.

1.Operating System will take "javac" command from command prompt and search
for it at its predefined commands lists and at the locations referred by "path"
environment variable.

2.If the required "javac" program is not available at the above two locations then
operating System will give a message on command prompt.

"javac can not be recognized as an internal command,external command or operable


program and a batch file"

NOTE:To make available all JDK tools like javac,java...to the operating
System we have to set "path" environment variable to
"c:\java\jdk1.7.0\bin" location.

3.If the required "javac" program is identified at "c:\java\jdk1.7.0\bin" location


through "path" environment variable then operating System will execute "javac"
program and activate "Java Compiler" software.

4.When Java Complier Software is activated then Java Complier will perform the
following tasks.

a)Compiler will take java File name from command prompt.

b)Compiler will search java file at current location.

c)If the required java file is not available at current location then compiler will
provide the following message on command prompt.

javac : file not found : FirstApp.java

d)If the required java file is available at current location then compiler will start
compilation from starting point to ending point of the java file.

e)In compilation process,if any syntax violations are identified then compiler will
generate error messages on command prompt.

f)In compilation process,if no syntax errors are identified then compiler will generate
.class files at the same current location.
NOTE:Generating no of .class files is completely depending on the no of
classes,no of abstract classes,no of interfaces,no of enums and no of inner
classes which we used in the present java File

If we want to compile java file from current location and if we want to send the
generated .class Files to some other target location then we have to use the
following command on command prompt

javac -d target_location File_Name.java

Ex:

d:\java7>javac -d c:\abc FirstApp.java

If we use package declaration statement in java file and if we want to store the
generated .class files by creating directory structure w.r.t the package name in
compilation process then we have to use

"-d" option along with "javac" command.

D:\java7\Employee.java

package com.durgasoft.core;

public class Employee{

D:\java7>javac -d c:\abc Employee.java

Compiler will compile Employee.java File from "D:\java7" location and it will
generate Employee.class file at "C:\abc" target location by creating directory
structure w.r.t the package name

"com.durgasoft.core".

If we want to compile all the java files which are available at current location then we
have to use the following command.

D:\java7>javac *.java

D:\java7>javac -d C:\abc *.java

If we want to compile all the java files which are prefixed with a word then we have
to use the following command.

D:\java7>javac Employee*.java

D:\java7>javac -d C:\abc Employee*.java


If we want to compile all the java files which are postfixed with a common word then
we have to use the following command.

D:\java7>javac *Address.java

D:\java7>javac -d C:\abc *Address.java

If we want to compile all the java Files which contain particular word then we have to
use the following command

D:\java7>javac *Account*.java

D:\java7>javac -d C:\abc *Account*.java

Execute JAVA Application:

If we want to execute java program then we have to use the following command
prompt.

java Main_Class_Name

Ex:

d:\java7>java FirstApp

If we use the above command on command prompt then operating System will
execute "java" operable program at "C:\java\jdk1.7.0\bin",with this,JVM software
will be activated and JVM will perform the following actions.

1.JVM will take Main_Class name from command prompt.

2.JVM will search for Main_Class at current location,at Java predefined library and at
the locations referred by "classpath" environment variable.

3.If the required Main_Class .class file is not available at all the above locations then
JVM will provide the following.

JAVA6:java.lang.NoClassDefFoundError:FirstApp

JAVA7:Error:Could not find or load main class FirstApp

NOTE:If main class .class file is available at some other location then to
make available main class.class file to JVM we have to set "classpath"
environment varaible.

D:\java7>set classpath=E:\XYZ;

4.If the required main class .class file is available at either of the above locations
then JVM will load main class bytecode to the memory by using "Class Loaders".
5.After loading main class bytecode to the memory,JVM will search for main()
method.

6.If main() method is not available at main class byteCode then JVM will provide the
following.

JAVA6:java.lang.NoSuchMethodError:main

JAVA7:Error:Main method not found in class FirstApp,please define main method as:

public static void main(String args[])

7.If main() method is available at main class bytecode then JVM will access main()
method by creating a thread called as "main thread".

8.JVM will access main() method to start application execution by using main
thread,when main thread reached to the ending point of main() method then main
thread will be in destroyed/dead state.

9.When main Thread is in dead state then JVM will stop all of its internal processes
and JVM will go to ShutDown mode.

Language Fundamentals:

To design Java applications, Java has provided some building blocks in the form of the
following Language Fundamentals.

1.Tokens

2.Data Types

3.Type Casting

4.Java Statements

5.Arrays

1.Tokens

 The smallest logical unit in Java programming is called as "Lexeme".


 The collection of "Lexemes" come under a particular group called as "Token".
To design Java Applications,Java has provided the following tokens:

1.Identifiers

2.Literals

3.Keywords/Reserved words

4.Operators

1.Identifiers:

 Identifier is a name assigned to the Java programming constructs like


variables,methods,classes,interfaces......
 To provide identifiers in Java programs we have to use the following rules and
regulations.

1.Identifiers should not start with a number,identifiers may start with an


alphabet,_symbols,$ symbols but the subsequent symbols may be a number,_symbols,$
symbols,an alphabet.

Ex:

int eno=111; ---> valid

String _empAddr="Hyd"; ---> Valid

float $empSal=50000.of; --->valid

String 9eid="999"; ---->InValid

int emp9No=999; ---->Valid

String emp_Addr="Hyd"; -->Valid

2.Identifiers will not allow all the operators,the special symbols like #,@,.,:,.......except
$ and_ symbols

Ex:

int emp+No=111; --->Invalid

String #empAddr="Hyd"; --->Invalid

String emp@Hyd="Durga"; --->Invalid

String emp-Name="Durga" --->Invalid

String emp_Name="Durga"; --->valid


3.Identifiers will not allow spaces in the middle.

Ex:

forName(); -->Valid

for Name(); -->InValid

get Input Stream(); -->InValid

getInputStream(); -->Valid

4.Identifiers should not be duplicated with in the same scope but identifiers may be
duplicated in two different scopes.

Ex:

class A{

int i=10;

float i=22.22f;--->Error

double f=23.32;

void m1(){

long i=20;

float f=10.0f;

byte f=23; ---->Error

}}

NOTE:In java,all the instance varaibles will be stored in "Heap Memory",all the
local varaibles will be stored in "Stack Memory" and all the static variables will be
stored in "Method Area".

5.In java applications,all the predefined class names and interface names are able to use
as identifiers.

Ex:

class Test{

public static void main(String args[]){

int Exception=10;

System.out.println(Exception);
}}

class Test{

public static void main(String args[]){

float Thread=22.22f;

System.out.println(Thread);

}}

class Test{

public static void main(String args[]){

String String="String";

System.out.println(String);

}}

class Test{

public static void main(String args[]){

int System=10;

System.out.println(System);

}}

Status:Compilation Error,int cannot be dereferenced

Reason:In java program,once if we declare any predefined class name as an


integer variable then compiler and JVM will treat that predefined class name as an
integer only in the remaining program,it can not be used as class.

In the above context,if we want to use System as class then we have to provide that
predeifined class [System] as fully qualified name.

NOTE:Specifying class names along with their package names is called as Fully
Qualified Name.

Ex:

java.lang.System

java.util.ArrayList

java.io.BufferedReader
class Test{

public static void main(String args[]){

int System=10;

java.lang.System.out.println(System);

System=System+10;

java.lang.System.out.println(System);

}}

Along with the above rules and regulations,JAVA has given the following suggestions to
declare and use identifiers.

1.Identifiers should be meaning ful,they should reflect particular meaning.

Ex:

String x="abc123";---->Not Suggestible

String accNo="abc123" --->Suggestible

2.In java applications,there is no length restriction for the identifiers but is is suggestible to
manage the length of the Identifiers around 10 Symbols.

Ex:

String temporaryemployeeaddress="Hyd";---->Not Suggestible

String tempEmpAddr="Hyd";----> Suggestible

3.If we have multiple words with in a single identifier then it is suggestible to separate
multiple words with special notations like '_' symbol.

Ex:

String tempEmpAddr="Hyd";---->Not Suggestible

String temp_Emp_Addr="Hyd";----> Suggestible

2.Literals:

 Literal is a constant assigned to the variables.


Ex:

int a=10;

int--->data type

a----->variable

= ---->operatot

10 --->constant[literal]

; --->special symbol/terminator

To design Java applications,Java has provided the following literals.

1.Integer Literals/Integer Literals:

byte,short,int,long ---->10,20......

char ---->'a','b'.....

2.Floating point Literals:

float --->11.11f,12.234f,...............

double --->12.23,23.345..................

3.Boolean literals:

boolean --->true,false

4.String Literals:

String --->"abc","xyz"...

Number systems in Java:

To represent number in Java,we are able to use the following number system.

1.Binary Number System[Base-2]

2.Decimal Number System[Base-10]


3.Octal Number System[Base-8]

4.HexaDecimal Number System[Base-16]

 In Java,the default number system will be Decimal number system.


 If we want to represent a number in binary number system then we have to prepare
the number by using the Symbols like '0's and '1's and the number must be prefixed
with either "0b or 0B"

Ex:

int a=10;--->Invalid,not a binary number

int b=0b10;-->Valid

int c=0B10;-->Valid

int d=0b102;-->Invalid

NOTE:Binary number system is not possible upto JAVA6 versions it is possible in


JAVA7 version and above,because,Binary number System is a new features in
JAVA7 version.

 In Java applications,if we want to represent any number in octal number system


then we have to prepare the number by using the symbols like 0,1,2,3,4,5,6 and 7
but the number must be prefixed with '0'[zero]

Ex:

int a=10;--->Invalid,it is not octal number

int b=010;--->Valid

int c=0345;-->Valid

int d=0678;-->Invalid

NOTE:Octal number System is supported by both JAVA6 and JAVA7 versions.If we


want to represent any number in Hexadecimal number system then we have to
prepare the number by using the symbols like 0,1,2,3,4,5,6,7,8,9,c,d,e and f but
the number must be prefixed with either '0x' or '0X'.

Ex:

int a=10; --->Invalid,it is not a hexadecimal number.

int b=0x56 -->Valid

int c=0x789 -->Valid

int d=0xbcde; -->Valid


int e=0xdefg; -->Invalid.

NOTE:Hexadecimal number system is supported by both JAVA6 and JAVA7


versions.

 To improve readability of literals,JAVA7 version is allowing '_' symbols in the middle


of the literals.

Ex:

long l=1_23_45_677;

System.out.println(l);

O/P:12345677

If we compile the above code then compiler will remove all '_' symbols from the number
and it will process that number as original number only.

3.Keywords/ReserveWords:

 Keyword is a predefined,which must have both word recognization and basic


functionality.
 Reserved word is a predefined word,which must have only word recognization
without basic functionality.
 To design Java applications,Java has given the following list of keywords and
reserved words.

Keywords:

1.Datatypes and return Types:

Byte,short,int,long,float,Double,boolean,char,void.

2.Access Modifier:

public,protected,private,static,final,abstract,native,volatile,

strictfp,transient,synchronized..
NOTE:The keywords public,private,protected are not access specifiers,there are
come under access modifiers only,because,in Java programming languages no
features like access specifiers.

3.Flow controllers:

if,else,switch,case,default,break,continue,return,for,while,do..

4.class/object related:

class,extends,interface,implements,enum,this,super,new,package,import......

5.Exception Handling:

throw,throws,try,catch,finally

Reserved Words:

goto,const.

Operators:

 Operator is a symbol it able to perform a particular operation over the provided


operands.

To design Java applications java has provided the following list of operators.

1.Arithmetic Operators:

+,-,*,/,%,++,--

2.Assignment Operator:

=,+=,-+,/+,%=

3.Comparsion Operators:

==,!=,<,><=,>=

4.logical Boolean Operators:

&,|,^,............
5.logical Bitwise Operators:

&,|,^,<<,>>,.............

6.Ternary Operator:

exp1?exp2:exp3;

7.Shortcircuit Operator:

&&,||

Ex:1

class Test{

public static void main(String args[]){

int a=10; O/P:

System.out.println(a); 10

System.out.println(a++); 10

System.out.println(++a); 12

System.out.println(a--); 11

System.out.println(--a); 11

System.out.println(a); 10

}}

class Test{

public static void main(String args[]){

int a=5;

System.out.println(a++-++a);

}}
class Test{

public static void main(String args[]){

int a=7;

System.out.println(++a+--a*++a);

}}

class Test{

public static void main(String args[]){

int a=4;

System.out.println(a++-++a*++a+--a);

}}

class Test{

public static void main(String args[]){

int a=6;

System.out.println((++a+--a)*(--a+--a)+(++a-++a)*(--a-a--));

}}

Boolean Operator:

boolean b1=true;

boolean b2=false;

System.out.println(b1&b1); //true

System.out.println(b1&b2); //false

System.out.println(b2&b1); //false

System.out.println(b2&b2); //false

System.out.println(b1|b1); //true

System.out.println(b1|b2); //true
System.out.println(b2|b1); //true

System.out.println(b2|b2); //false

System.out.println(b1^b1); //false

System.out.println(b1^b2); //true

System.out.println(b2^b1); //true

System.out.println(b2^b2); //false

A B A&B A|B A^B

T T T T F
T F F T T
F T F T T
F F F F F

A B A&B A|B A^B

0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Bitwise Operator:

int a=10;

int b=2;

System.out.println(a&b); --->2

System.out.println(a|b); --->10

System.out.println(a^b); --->8

System.out.println(a<<b); --->40

System.out.println(a>>b); --->2
Short Circuit Operators:

 In the case of boolean "or" operator,if the first operand is true then it is possible to
predict the over all expression result is "true" with out checking second operand.
 In java applications,in the case of "|" and "&" boolean operators,even though the
first operand value is sufficient to predict the overall expression result still JVM will
execute second operand,here,it is unnecessary to execute second operand value,it
will reduce the performance of the application.
 In the above context,to improve the performance of the applications, we have to use
ShortCircuit operators like "||" and "&&".
 In the case of short circuit operators,if the first operand value is sufficient to predict
overall expression result then JVM will not execute second operand value,this
approach will increase the application performance.
 In the case of "||",if the first operand value is true then JVM will not check second
operand value and it will predict overall expression result is true.
 In the case of "&&",if the first operand value is false then JVM will not check second
operand value,JVM will predict the overall expression result is false.

Ex:

class Test{

public static void main(String args[]){

int a=10;

int b=10;

if((a++==10) | (b++==10)){

System.out.println(a);

System.out.println(b);

int c=10;

int d=10;

if((c++==10) || (d++==10)){

System.out.println(c);

System.out.println(d);

}}}
Ex:

class Test{

public static void main(String args[]){

int a=10;

int b=10;

if((a++!=10) | (b++!=10)){

System.out.println(a);

System.out.println(b);

int c=10;

int d=10;

if((c++!=10) || (d++!=10)){

System.out.println(c);

System.out.println(d);

}}}}

DataTypes:

 Java is Strictly a typed programming language,where in java applications,before


going to represent the data first we have to decide which type of data we are
representing.To decide the type of data which we are representing we have to use
"data types".

In java applications,data types are able to provide the following advantages:

1.We can identify memory sizes for the data to store.

2.We can identify the range of values which we want to

assign to the varaibles.

Note:Memory sizes for the primitive data types is fixed in Java irrespective of the
operating system which we used,this nature of the data types will make java as a
platform independent programming language.
int i=10;---->valid

a=20---> invalid

int i;

i=10;---->Valid

To desgin java applications,java has provided the following list of datatypes:

1)Primitive Data Tyeps/Primary data types

1)Numeric Data Types:

1)Integral data Types/Integer data Types

Size Default value

byte 1 byte 0
short 2 bytes 0
int 4 bytes 0
long 8 bytes 0

2)Non-Integral Datatype/Floating point Datatypes

Size Default value

float 4 bytes 0.0f


double 8 bytes 0.0

2.Non-Numeric Data Types:

Size Default value

Char 2 bytes “[singlespace]


boolean 1 bit false
2.User defined Datatypes/Secondary Datatypes

 All classes,All Interfaces,All Arrays......If we want to identify the range values of each
and every datatypes then we have to use the following formula

n-1 n-1

-2 to 2 -1

where n is no.of bits

Ex:

byte data type ---> 1 byte --> 8 bits

8-1 8-1

-2 to 2 -1

7 7

-2 to 2 -1

-128 to 128 -1

-128 to 127

Calculate min&max long data type exact value

long data type --> 8 bytes -->64 bits

64-1 64-1

-2 to +2 - 1

 To get the minimum value and maximum value of each and every primitive data
type,we have to use "MIN_VALUE" and "MAX_VALUE" constants from each and every
Wrapper class.

Note:Wrapper classes are the classes representation of primitive datatypes.


Primitives Wrapper classes

Byte Byte

Short Short

Int Integer

long Long

Float Float
Double Double

char Character
Boolean Boolean

class Test{

public static void main(String args[]){

System.out.println(Byte.MIN_VALUE+" -->"+Byte.MAX_VALUE);

System.out.println(Short.MIN_VALUE+"-->"+Short.MAX_VALUE);

System.out.println(Integer.MIN_VALUE+"--->"+Integer.MAX_VALUE);

System.out.println(Long.MIN_VALUE+"--->"+Long.MAX_VALUE);

System.out.println(Float.MIN_VALUE+"--->"+Float.MAX_VALUE);

System.out.println(Double.MIN_VALUE+"--->"+Double.MAX_VALUE);

}}

TypeCasting:

 The process of converting the data from one data type to another data type is called
as TypeCasting.

There are two types of Type Castings:

1)primitive datatypes casting.

2)userdefined datatypes casting

 The process of converting the data from one user defined data Type to another user
defined data Type is called as User defined data types Type Casting.
 To perform User Defined data types type casting,we must provide either "extends"
relation or "implements" between two user-defined data types.
Primitive data types type Casting:

 The process of converting the data from one primitive data type to another primitive
data type is called as Primitive data types type casting.

There are two types of primitive data types type casting.

1.Implicit type casting.

2.Explicit type casting.

1.Implicit Type Casting:

 The process of converting the data from lower datatype to higher datatype is called
as Implicit Type Casting.
 To cover all the possibilities of implicit type casting,Java has provided a predefined
chart.
 To perform implicit type casting in Java,simply we have to assign lower data type
variable to higher data type variable.

byte b=10;

int i=b;

 when we compile the above code,compiler will check right side variable[b] datatype
is compatible with left side variable data type for = ,if right side variable data type is
not compatible with left side variable data type then compiler will rise an error like
"Possible loss of precision".If right with left side variable datatype then compiler will
not rise any error.

Note:In Java,all lower datatypes are compatible with higher datatypes but
higher datatypes are not compatible with lower data types.Due to this
reason,we can assign lower dataTypes to higher data types directly.

When we execute the above code then JVM will perform the following two actions.

1.JVM will convert the right side data type to left side data type implicitly and
automatically.

2.JVM will copy the value from right side variable to left side variable.
byte b=10;

int i=b;

status:No Compilation error

o/p:10 10

byte b=65;

char c= b;

status:Compilation Error,possible loss of Precision

Reason:No conversions are existed between byte and char,short and char as per
implicit type casting chart.

float f=22.22f;

long l=f;

Status:Compilation Error,possible loss of Precision

long l=10;

float f=l;

Status:No Compilation error

o/p 10 10.0

float f=22.2f;

long l=f;

Status:Compilation Error,possible loss of Precision

Reason:Float datatype is taking 4 bytes of memory and long datatype is taking 8


bytes of memory.

 Float datatype is able to store more data when comapred with long datatype as per
their internal data arrangement.Therefore,float is higher data types when compared
with long data types.

byte b=128;

Status:Compilation Error,possible loss of Precision


Reason:If assign a value to a particular datatype variable which is more than the
maximum limit of the respective data type then compiler will treate that value is of
the next higher data type so compiler will rise an error.

Note:For byte and short the next higher data type is "int".

byte b1=10;

byte b2=20;

byte b=b1+b2;

Status:Compilation Error,possible loss of Precision

Reason:X,Y and Z are primitive data types

X+Y=Z

Where if X and Y belongs to {byte,short,int} then Z should be "int".

Whether if either X or Y both belongs to {long,float,double} then Z should be


max(X,Y) as per implict type casting chart.

Ex:

byte+byte=int

byte+short=int

short+int=int

int+long=long

long+float=float

float+double=double

short s=10;

byte b=20;

int i=s+b;

System.out.println(i);
Explicit Type Casting:

 The process of converting the data from higher data type to lower data type is called
as Explicit type casting.

To perform explicit type casting,we have to use the following pattern.

P a=(Q) b;

where P and Q are primitive data types and Q must be either same as P or lower
than P as per implicit type casting chart.

Ex:

int i=10;

byte b=(byte)i;

System.out.println(i+" "+b);

Status:No compilation Error

o/p:10 10

 When we compile the above code then compiler will check whether right side data
type and left side datatype are compatible or not,if not compiler will rise an error like
"Possible loss of Precision".
 If both the datatypes are compatible then compiler will not rise any error.
 In the above example,compiler will not rise any error because,both left side data
type and right side data type are "byte" data types.
 When we execute the above code,JVM will perform the following actions.

1.JVM will convert the right side variable data type to the datatype which we
specified inside braces[()] i.e cast operator.

2.JVM will copy the value from right side variable to left side variable.

Ex:

byte b=65;

char ch=(char)b;

System.out.println(b+" "+c);

Status:No Compilation Error.

O/P:65 A
char c='B';

short s=(Short)c; or short s =(byte)c;

System.out.println(c+" "+s);

Status:No Compilation Error

O/P:B 66

Note:In the case of implicit type casting,conversions are not existed


between char and byte,char and short but in the case of explicit type casting
conversions are possible between char and byte,char and short.

Ex:

float f=22.22f;

long l=(long)f; or long l=(int)f;

System.out.println(f+" "+l);

Status:No Compilation Error

O/P:22.22 22

Ex:

byte b1=10;

byte b2=10;

byte b=(byte)(b1+b2); or byte b=(byte)b1+b2;

[Status:Compilation Error,possible loss of Precision]

System.out.println(b);

Status:No Compilation Error

O/P:20

Ex:

float f1=10.0f;

long L1=10;

long L=f1+L1; or long L=(int)f1+L1;


System.out.println(L);

Status:No Compilation Error

O/P:20

Ex:

double d=22.22;

byte b=(byte)(short)(int)(long)(float)d;

System.out.println(b);

Status:No Compilation Error

O/P:22

Ex:

int i=135;

byte b=(byte)i;

System.out.println(i+"----------------"+b);

Status:No Compilation Error

O/P:135 -121

Reason:

int i=X;

byte b=(byte)X;

If X is 127+n then b should be calculated from the below formula.

b=-128+n-1;

Ex:

int i=129;

short s=(byte)i;

System.out.println(i+" "+s);
Status:No compilation Error

O/P:129 -127

JAVA Statements:

 Statement is a collection of expressions.

To design java applications,Java has given following list of statements.

1.General Purpose Statements:

Declaring varaibles,methods,classes........

Accessing varaibles,methods...........

Creating objects,packages..............

2.Conditional Statements:

if , switch

3.Iterative Statements:

for,while,do-while

4.Transfer Statements:

break,continue,return

5.Exception Handling Statements:

throw,try-catch-finally

6.Synchronized Statements[Multi threading]

synchronized methods,synchronized blocks

Conditional Statements:

 These are the Java Statements,which will allow to execute a block of Java code
under a particular condition.
There are two types of conditional Statements.

1.if

2.switch

1.if:

Syntax-1:

if(condition)

----statements-------

Syntax-2:

if(condition)

----statements----

else

----statements---

Syntax-3:

if(condition)

-----statements---

else if(condition)

----statements---
}

------

------

else{

---statements---

Ex:

int i=10;

int j;

if(i==10){

j=20;

System.out.println(j);

Status:Compilation Error

int i=10;

int j;

if(true){

j=20;

System.out.println(j);

Status:No Compilation Error

O/P:20

int i=20;

int j;

if(i==10){

j=20;

}
else{

j=30

System.out.println(j);

Status:No Compilation Error

O/P:20

final int i=10;

int j;

if(i==10){

j=20;

System.out.println(j);

Status:No Compilation Error

O/P:20

int i=10;

int j;

if(i==10){

j=20;

else if(i==20){

j=30;

System.out.println(j);

Status:Compilation Error
1.In Java,only class level varaibles are having default values,local variables are not
having default values.

2.If we declare any local variable then we must provide initialization for that local
variable either at the same declarative statement or atleast before accessing that
local variable.

3.In java applications,complier is able to recoginze and execute constant expressions


which are having only constants.

4.In java,compiler is unable to recognize and execute variable expressions which are
having atleast one variable.

Switch:

 In Java applications,"if" conditional statement is able to allow single condition


checking but switch is able to allow multiple conditions checking.

In general,Switch will be utilized to prepare menu driven applications.

Syntax:

switch(var){

case 1:

-------statements-----------

break;

------

------

case n:

-------statements--------

break;

default:

---------statements------

break;

}
Ex:

class Test{

public static void main(String args[]){

int i=10;

switch(i){

case 5:

System.out.println("FIVE");

break;

case 10;

System.out.println("TEN");

break;

case 15;

System.out.println("FIFTEEN");

break;

case 20;

System.out.println("TWENTY");

break;

default:

System.out.println("Default");

break;

}}}

Rules To write switch:

1.Switch is able to allow the data types like byte,short,int and char as parameter.

Ex:

char c='A';

switch(c){

case 'A';
System.out.println("A");

break;

case 'B'

System.out.println("B");

break;

default

System.out.println("Default");

break;

Ex:

long l=10;

switch(l){

---------

status:Compilation Error

2.JAVA7 is able to allow String data type as parameter,which is not possible upto JAVA6
version.

Ex:

String str="BBB";

switch(str){

case "AAA":

System.out.println("FIVE");

break;

case "BBB";

System.out.println("TEN");

break;

case "CCC";

System.out.println("FIFTEEN");
break;

case "DDD";

System.out.println("TWENTY");

break;

default:

System.out.println("Default");

break;

}}}

3.In switch,all the cases are optional,it is possible to write switch with out having cases.

int i=10;

switch(i){

default:

System.out.println("Default");

break;

Status:No Compilation Error

O/P:Default

4.In Switch Default is optional,it is possible to write switch even without "default".

Ex:

int i=100;

switch(i){

case 50:

System.out.println("50");

break

case 60:

System.out.println("60");
break;

Status:No Compilation Error

O/P:No OutPut

5.In Switch,all the cases and default are optional,it is possible to write switch with out cases
and default.

Ex:

int i=10;

switch(i){

6.In switch break statement is optional,if we write switch with out break statement then
JVM will execute all the instructions right from matched case untill it encounter either break
statement or end of the switch.

Ex:

int i=10;

switch(i){

case 5:

System.out.println("FIVE");

case 10:

System.out.println("TEN");

case 15:

System.out.println("FIFTEEN");

case 20:

System.out.println("TWENTY");

default:

System.out.println("Default");

}
Status:No Compilation Error

O/P: TEN

FIFTEEN

TWENTY

Default

7.In switch,all the case values must be available with in the range of the datatype which we
passed as parameter to switch.

Ex:

byte b=126;

switch(b) {

case 125;

System.out.println("125");

break;

case 126;

System.out.println("126");

break;

case 127;

System.out.println("127");

break;

case 128;

System.out.println("128");

break;

default:

System.out.println("Default");

break;

Status:Compilation Error(Possible loss of precision)


8.In Switch,all the case values must be either direct constants or final constants.

Ex:

final int i=125,j=126,k=127,l=128;

switch(126){

case i:

System.out.println("125");

break;

case j:

System.out.println("126");

break;

case k:

System.out.println("127");

break;

case l:

System.out.println("128");

break;

default:

System.out.println("default");

break;

Iterative Statements:

These are the java statements,which will allow to execute a block of instructions repeatedly
under a condition.

There are three types of iterative statements in java.

1.for 2.while 3.do-while


1.for:

Syntax:

for(expr1;expr2;expr3){

-----body------------

Ex:

for(int i=0;i<10;i++){

System.out.println(i);

expr1-----> 1 time

expr2----->11 times

expr3----->10 times

body------> 10 times

Ex:

int i=0;

for(;i<10;i++){

System.out.println(i);

Status:No Compilation Error

O/P:0 to 9

Ex:

int i=0;

for(System.out.println("Hello");i<10;i++){

System.out.println(i);

Status:No Compilation Error


Reason:

In for loop syntax,expr1 is optional,we can write for loop with out expr1,we can write any
statement as expr1 including System.out.println(----); method but it is Suggestible to utilize
expr1 to declare and initialize loop variables.

Ex:

for(int i=0;float f=0;i<10 && f<10.0f;i++,f++){

System.out.println(i+" "+f);

Status:Compilation Error

Ex:

for(int i=0;int j=0;i<10 && j<10;i++,j++){

System.out.println(i+" "+j);

Status:Compilation Error

Ex:

for(int i=0;j=0;i<10 && j<10;i++,j++){

System.out.println(i+" "+j);

Status:No Compilation Error

Reason:In for loop syntax,expr1 is able to allow atmost one declarative statement,it will not
allow more than one declarative statement.

Ex:

for(int i=0;;i++){

System.out.println(i);

Status:No compilation Error

O/P:Infinite loop
Reason:In Java,in for loop,expr2 is optional,if we have not provided expr2 then "for" loop
will take true as boolean value in place of expr2 even though the default value for boolean
variables is false in Java

Ex:

for(int i=0;System.out.println("Hello");i++){

System.out.println(i);

Reason:In for loop,expr2 is optional,if we want to provide any statement as expr2 then that
Statement must be boolean statement,it must generate a boolean value as result.

Ex:

System.out.println("Before loop");

for(int i=0;i>=0;i++){

System.out.println("Inside loop");

System.out.println("After loop");

Status:No Compilation Error

O/P:Before Loop

Inside Loop(Infinite)

Ex:

System.out.println("Before loop");

for(int i=0;true;i++){

System.out.println("Inside loop");

System.out.println("After loop");

Status:Compilation Error(unreachable statement)


Ex:

System.out.println("Before loop");

for(int i=0;;i++){

System.out.println("Inside loop");

System.out.println("After loop");

Status:Compilation Error(unreachable statement)

Reason:In Java,if we provide any statement immediately after infinite loop then that
statement is called as "UnReachableStatement".

 In the above context,rising an error or not is completely depending on how much


compiler is recognized the provided loop is infinite loop.
 If compiler is recognized the provided loop is infinite loop and if the compiler is
identified an instruction immediately after infinite loop then compiler will rise an
error like "Unreachable Statement".
 If compiler is not recognized the loop is an infinite loop then there is not chance
getting "Unreachable Statement".
 Deciding a loop is infinite loop or not is totally depending on the conditional
expression,if the conditional expression is constant expression and it results true
then compiler will recognize that loop is an infinite loop.
 If the conditional expression is variables then compiler will not recognize that loop is
an infinite loop.

Ex:

for(int i=0;i<10;){

System.out.println(i);

i=i+1;

Status:No Compilation Error

Ex:

for(int i=0;i<10;System.out.println("Hello")){

System.out.println(i);

i=i+1;

}
Status:No Compilation Error

Reason:In for loop,expr3 is optional,we can write for loop with out expr3,in place of
expr3 we can write any statement but we will utilize expr3 to perform loop variables
incrementation or decrementation operations.

Ex:

for(final int i=0;i<10;i++){

System.out.println(i);

Status:Compilation Error.

Reason:In General loops it is not suggestible to declare loop variables as


final,because,we are able to perform increment and decrement operations over loop
variables.

Ex:

for(;;)

Status:Compilation Error

Ex:

for(;;);

Status:No Compilation Error

Ex:

for(;;)

Status:No Compilation Error

Ex:

for(;;){

Status:No Compilation Error

Reason:In for loop,curly braces are optional in the case of single statement body.
In the case of single statement body we must provide either curly braces or ; to
terminate the loop.

In general in Java applications,we are able to utilize for loop when we aware the no.of
iterations before writing for loop.

Ex:

To retrieve elements from an array we are able to use "for" loop because we are able to
identify the size of the array before writing for loop.

Note:Size of the array is equals to the no of iterations which are required to


retrieve elements from array.

int[] a={1,2,3,4,5};

for(int i=0;i<a.length;i++){

System.out.println(a[i]);

If we use the above for loop to retrieve elements from an array and from collection
objects then we are able to get the following problems.

a)We have to manage a loop variable explicitly.

b)We have to execute conditional expression at each and every iteration.

c)We have to perform either increment or decrement operations over loop variables
explicitly.

d)We have to retrieve the elements on the basis of array index values,it may provide
ArrayIndexOutOfBoundsException when we mishandle with index value.

The above problems may decrease application performance while iterating values from
an array or from collection.

In the above context,to improve the application performance,JDK5.0 version has


provided a new version of for loop called as "for-Each" loop.

Syntax:

for(Array_Data_Type var:Array_Ref_Var){

---body--------------

}
This for-each loop will iterate values from the specified array and assign values to the
specified variable at each and every iteration.

Ex:

for(int x : a){

System.out.println(x);

class Test{

public static void main(String args[]){

String[] str={"AAA","BBB","CCC","DDD","EEE"};

for(int i=0;i<str.length;i++){

System.out.println(str[i]);

System.out.println();

for(String s: str){

System.out.println(s);

}}}

2.while loop:

 In Java applications,we are able to utillize while loop when we are not aware the no.
of iterations before writing loop.

Syntax:

while(conditional_Expression){

----body--------

class Test{

public static void main(String args[]){


int i=0;

while(i<10){

System.out.println(i);

i=i+1;

}}}

Ex:

int i=0;

while(){

System.out.println(i);

i=i+1;

Status:Compilation Error

Reason:In the case of while loop,conditional expression is mandatory.

Ex:

int i=0;

System.out.println("Before Loop");

while(i<10){

System.out.println("Inside loop");

System.out.println("After loop");

Status:No Compilation Error

O/P:Infinite loop
Ex:

int i=0;

System.out.println("Before for Loop");

while(true){

System.out.println("Inside loop");

System.out.println("After loop");

Status:Compilation Error

do-while loop:

Q)What are the differences between while loop and do-while loop?

Ans:1.In the case of while loop there is no gaurnatee whether the loop body is executed
minimum one time.

In the case of do-while loop body will be executed minimum one time.

2.In the case of while loop,first condition will be executed then body will be executed.

In the case of do-while loop,first body will be executed then condition will be checked.

3.In the case of while loop condition will be checked to perform present iteration.

In the case of do-while loop condition will be checked to perform next iteration.

Syntax:

do{

---body--

}while(condition);

Ex:

int i=0;

do{

System.out.println(i);

i=i+1;

}
while(i<10);

Ex:

int i=0;

do{

System.out.println(i);

i=i+1;

while();

Status:Compilation Error

Reason:Conditional Expression is mandatory

Transfer Statements:

These are Java Statements,which can be used to bypass the flow of execution from one
instruction to another instruction.

There are 3 transfer statements in java

1.break

2.continue

3.return

1.break:

 This transfer statement can be used to skip all the remaining instructions at present
iteration,it will skip all the remaining iterations and it will bypass flow of execution to
outside of the loop

Ex:

for(int i=0;i<10;i++){

if(i==5){

break;
}

System.out.println(i);

Ex:

for(int i=0;i<10;i++){

if(i==5){

System.out.println("Before break");

break;

System.out.println("After break");

System.out.println(i);

Status:Compilation Error(unreachable statement)

Reason:If we provide any statement immediately after "break" statement then that
statement is "unreachable statement".

Ex:

for(int i=0;i<10;i++){

for(int j=0;j<10;j++){

System.out.prinltn(i+" "+j);

if(j==5){

break;

System.out.println(i+" "+j);

}}

 In Java,if we provide break statement in an inner loop then that "break" statement
will give effect to inner loop only,it will not give effect to outer loop.
 In the above context,if we want to give effect to outer loop by keeping "break"
statement in inner loop then we must go for "labelled break" statement break label;
where "label" must be marked with outer loop.

Ex:

for(int i=0;i<10;i++){

for(int j=0;j<10;j++){

System.out.prinltn(i+" "+j);

if(j==5){

break l1;

System.out.println(i+" "+j);

}}

continue:

This transfer statement can be used to skip the remaining instructions in the present
iteration and continue with the next iteration.

Ex:

for(int i=0;i<10;i++){

if(i==5){

continue;

}}

System.out.println(i);

Ex:

for(int i=0;i<10;i++){

if(i==5){

System.out.println("before continue");

continue;

System.out.println("After continue");

}}

System.out.println(i);
Status:Compilation Error

Reason:If we provide any statement immediately after continue statement then that
statement is called as unreachable statement where compiler will rise an error.

Ex:

for(int i=0;i<10;i++){

for(int j=0;j<10;j++){

if(j==5){

continue;

System.out.println(i+" "+j);

}}

If we provide continue statement inside an inner loop then continue statement will give
effect to inner loop only,it will not give effect to outer loop.

Ex:

for(int i=0;i<10;i++){

for(int j=0;j<10;j++){

System.out.prinltn(i+" "+j);

if(j==5){

continue l1;

System.out.println(i+" "+j);

}}

 In the above context,if we want to give continue statement effect to outer loop by
keeping continue statement in inner loop then we have to use "labelled continue"
statement continue label;

where "label" must be marked with outer loop.


Object Orientation:

 To design any enterprise application,we have to use a particular programming


language.Before selecting a particular programming language,first we have to select
a particular type of programming language.

There are four types of programming languages:

1)Unstructured Programming languages.

2)Structured Programming languages.

3)Object Oriented Programming languages.

4)Aspect Oriented Programming languages.

1)Unstructured Programming languages:

 These Programming languages are outdated programming languages,they are


introduced at the beginning stages of computers.

Ex: BASIC --->First interpretive programming language.

FOTRAN- -->First compilative programming language.

 Unstructured Programming languages are not following any structure to design


applications,it is not suggestable in application development.
 Unstructured Programming languages are using mnemonic codes like
ADD,SUB,MUL,DIV,GOTO...LOAD..to design applications.Basically,mnemonic codes
are available in very less number and which may provide very less no. of features to
design applications.
 Unstructured Programming languages are using only "goto" statement to define flow
of execution,only "goto" statement is not sufficient to define flow of execution.
 Unstructured Programming languages are not allowing functions feature,it may
increase code redundancy (duplicate),it will reduce code reusability,it is not
suggestable in application development.

2)Structured Programming languages:

 Structured Programming languages are very good when compared with Unstructured
Programming languages,because,
 These Programming languages are not outdated programming languages,which are
in use at present application development.
 These Programming languages are using high level syntaxes.
 These Programming languages are using more no.of flow controllers to define very
good flow of execution.
 These Programming languages are using functions feature to improve code
reusability.

Structured Programming languages are not good when compared with Object Oriented
Programming languages,because

1)Modularity is not good in Structured Programming languages.

2)Abstraction is not good in Structured Programming languages.

3)Code Reusability is not good in Structured Programming languages.

4)Structured Programming languages are able to provide tightly coupled design for the
applications.

5)Security is not good with Structured Programming languages.

3)Object Oriented Programming Languages:

 Object Oriented Programming Languages are very good when compared with
Structured Programming Languages,because

1)It will provide modularity.

2)It will provide Abstraction.

3)It will provide Security.

4)It will provide Code reusability.

5)It will provide Loosely coupled design.

 Object Oriented Programming Languages are not good when compared with Aspect
Oriented Programming Languages,because,

1)It will not provide very good sharability.

2)It will not provide very good Reusability.

3)It will not provide very good loosely coupled design.

4)Aspect Oriented Programming Languages:

 If we design any enterprise application on the basis of Object Oriented then we have
to provide the services like Authentication,Authorization,Validation,Logging..along
with Business logic in combined manner,it will make
compilation,debugging,testing...all the preprocessings are difficult.
 To overcome the above problem,we have to apply Aspect Orientation on Enterprise
application.In the case of Aspect Orientation,we have to separate all the services
logic form Bussiness Logic,we have to declare each and every service as an aspect
and we have to inject these services to the enterprise application at runtime.
 In enterprise application development,Aspect Orientation will provide Loosely
Coupled Design,more Sharability and More ReuseAbility.

Note:Aspect Oriented Programming Languages is misterminalogy,no


programming language is defined on the basis of Aspect Orientation,Aspect
Orientation is a methodology,it is a set of rules and regulations
applied on Object Oriented Programming inorder to get more loosely
coupled design.

Object Oriented Features:

 To expose the nature of Object Orientation,Object Orientation has provided the


following features.
1)Class
2)Object
3)Encapsulation
4)Abstraction
5)Inheritance
6)Polymorphism
7)Message Passing

 On the basis of above Object Oriented features,there are two types of Programming
languages.
1)Object Oriented Programming Languages
2)Object Based Programming languages.

Q)What is the difference between Object Oriented Programming languages


and Object Based Programming languages?

Ans:

Object Oriented Programming languages Object Based Programming languages


will allow allmost all the Object Oriented will all allmost all the Object Oriented
Features including "Inheritance" features excluding "Inheritance".
Ex:Java Ex:Java Script

Q)What is the difference between Class and Object?

Ans:

1)Class is a group of elements having Object is an individual element


similar properties and behaviours. among the group of elements having
physical identity,physical properties
and physical behaviours.

2)Class is virtual. Object is physical.

3)Class is virtual encapsulation of Object is physical encapsulation of


properties and behaviours. properties and behaviours.

4) Class is generalization. Object is specialization.

5) Class is a model or blue print for Object is an instance of the class.


the objects but

Q)What is the difference between encapsulation and abstraction?

Ans:Encapsulation is the process of binding data and coding part as a single unit.
The process of visualizing necessary implementation or elements and the process of
hiding unnecessary elements or implementation part is called as Abstraction.
In Application development,both Encapsulation and Abstraction are achieving
"Security".
Inheritance:

 The process of getting variables and methods from one class to another class is
called as "Inheritance".
 The main Objective of Inheritance is "Code Reusability".

PolyMorphism:

 PolyMorphism is a greek word,where poly means many and morphism means


Structures.
 If one thing is existed in more than one form then it is called as PolyMorphism.

Message Passing:

 The process of bypassing the data along with flow of execution from one instruction
to another instruction is called as Message Passing.

Containers in Java:

 Container is an element,which contains some other java elements like


varaibles,methods,blocks....

There are three types of containers in java:

1)class

2)Interface

3)Abstract

class:

 The main intention of classes in java programming is to represent the real world
entities like Customer,Employee,Student,Account…
 If we want to use classes in java Applications,then we have to use the following
steps.

1)Declare a class by using "class" keyword.

2)Declare entity data in the form of variables.

3)Declare entity behaviours in the form of methods.

4)In main class,In main() method,create an object and reference variable for the class.

5)Access the members of the class by using reference variable.


Ex:

class Employee{

String eid="E-111";

String ename="Durga";

float esal=50000.0f;

String eaddr="Hyderabad";

void display_Employee(){

System.out.println("Employee Details");

System.out.println("------------------");

System.out.println("Employee Id :"+eid);

System.out.println("Employee Name :"+ename);

System.out.println("Employee Salary:"+esal);

System.out.println("Employee Address:"+eaddr);

}}

class Test{

public static void main(String args[]){

Emloyee emp=new Employee();

emp.display_Employee();

}}

Output:

Employee Details:

---------------------

Employee Id :E-111

Employee Name: Durga

Employee Salary:50000.0

Employee Address:Hyderabad
Ex:

class Student{

String sid=”S-111”;

String sname=”Durga”;

String saddr=”Hyderabad”;

int smarks=100;

void display_Student(){

System.out.println(“Student Details”);

System.out.println(“------------------”);

System.out.println(“Student ID:”+sid);

System.out.println(“Student name:”+sname);

System.out.println(“Student Marks :”+smarks);

System.out.println(“Student Address:”+saddr);

}}
class Test{

public static void main(String[] args){

Student s=new Student();

s.display_Student();

}}

Output:

Student Details

------------------

Student ID:S-111

Student name:Durga

Student Marks:100

Student Address:Hyderabad

class Syntax:

[Access_Modifiers] class class Name[extendsSuper_Class][implements interface_List]

----variables------------

----constructors---------

----methods------

----blocks-------

----classes------

----abstract classes-----

----interfaces------

}
NOTE:Inside the class,we can write a class,an abstract classes and Interfaces.

Inside the abstract class,we can write a class,an abstract class and an Interface.

Inside the interface,we can write a class,an abstract class and an Interface.

Access_Modifiers:

There are two types of Access Modifiers:

 To define Scope for the java elements like varaibles, methods,classes,.............we


have to use the following access modifiers.
o public
o protected
o default
o private

 Where “private” members will be available upto the present class where we have
declared private members.

 Where “ <default>” members will be available upto all the classes and interfaces
available in the current package.

 Where “protected” members will be available upto all the classes and interfaces
available in the present package and the child classes available in the other
packages.

 Where “public” members will be available to all the classes and interfaces available in
all the packages.
Q)Which access-modifiers are suitable for classes and which access-modifiers
are not suitable for classes?

Ans:From the above access modifiers,only public and <default> are allowed for the
classes,private and protected are not allowed for the classes.

NOTE:The access modifiers private and protected scopes are defined on the
boundaries of classes so we can not apply them for the classes,we can apply
them for the members of the classes.

NOTE:All the access modifiers like public,protected,default and private are


allowed for the inner classes.

Some Examples on Access Modifiers:

class Test{

public static void main(String args[]){

System.out.println(“class Test”);

}}

Status:No Compilation Error

public class Test{

public static void main(String args[]){

System.out.println(“class Test”);

}}

Status:No Compilation Error

==================

private class Test{

public static void main(String args[]){

System.out.println(“class Test”);

}}

Status:Compilation Error

Error:modifier private not allowed here.

========================
protected class Test{

public static void main(String args[]){

System.out.println(“class Test”);

}}

Status :Compilation Error

Error:modifier protected not allowed here

=========================

class A{

public class B{

System.out.println(“Hai”);

}}

Status:No Compilation Error

=================

class A{

private class B{

System.out.println(“Hai”);

}}

Status:No Compilation Error

==================

class A{

protected class B{

System.out.println(“Hai”);

}}

Status:No Compilation Error

=================
class A{

class B{

System.out.println(“Hai”);

}}

Status:No Compilation Error.

==================

class A{

Note:If we don’t mention the scope to the class,then it automatically


recognize the scope of the class is “default”.

Memory Management System:

Ex:

Class A{

int i=10;

static int j=20;

void m1(){

int k=30;

}}
All the class variables are called as Instance Variables.

In Java memory management System,it have 3 memories.They are:

1.Heap Memory

2.Stack Memory

3.Method Area

Heap Memory:All the class level variables are stored in Heap Memory.

Stack Memory:All the local variables are stored in Stack Memory.

Method Area:All the static variables are stored in Method Area.

Note:static variables are always declared in the class scope only.

From the second type of access modifiers,which are allowed for classes and which
are not allowed for the classes

Ex:

static class A{

}
class Test{

public static void main(String args[]){

System.out.println(“Hai”);

}}

Output:

modifier static not allowed here.

====================

Ex:

abstract class A{

class Test{

public static void main(String args[]){

System.out.println(“Hai”);

}}

Output:

No Compilation Error.

=============

Note:static keyword is not allowed for the classes

Note:abstract keyword is allowed for the classes.

Ex:

native class A{

class Test{

public static void main(String args[]){

System.out.println(“Hai”);

}}
Ouput:modifier native not allowed here.

=========================

Note:native keyword is not allowed for the classes.

Ex:

final class A{

class Test{

public static void main(String args[]){

System.out.println(“Hai”);

}}

Output:No Compilation Error.

==================

Note:final keyword is allowed for the classes.

Ex:

transient class A{

class Test{

public static void main(String args[]){

System.out.println(“Hai”);

}}

Output:modifier transient not allowed here

===========================

Note: transient keyword is not allowed for the classes.

Note: synchronized modifier is not allowed for the classes.

Note:strictfp modifier is allowed for the classes.


Note:volatile modifier is not allowed for the classes.

Ex:

class A{

static int i=10;

int j=20;

class Test{

public static void main(String args[]){

A a=new A();

System.out.println(a.j);

System.out.println(A.i);

System.out.println(a.i);

}}

Output:

20

10

10

If we want to access the non-static members outside of the class, then we must
create an object for the class, with the generated reference variable for the class, we
are able to access them.

Note:static keyword is allowed for the inner classes.

final keyword is allowed for the inner classes.

abstract keyword is allowed for the inner classes.

native keyword is not allowed for the inner classes.

volatile keyword is not allowed for the inner classes.

transient keyword is not allowed for the inner classes.


synchronized keyword is not allowed for the inner classes.

strictfp keyword is allowed for the inner classes.

Note: All the access modifiers like “public”,”protected”,”default”

And “private” are allowed for the inner classes.

 To define some extract nature to the Java elements like


variables,methods,classes.....we will use the following access modifiers.

static

final

abstract

native

volatile

transient

synchronized

strictfp

--------

---------

---------

----------

 From the above list of access modifiers,classes are able to allow abstract,final and
strictfp.

NOTE:Inner classes are able to allow static,final,abstract and strictfp access


modifiers from the above list.

Q)Is it possible to declare a class is static or not?

 Ans:No,In Java,it is not possible to declare an outer class as static,it is possible to


declare an inner class as static,because in Java,static keyword is defined on the basis
of classes origin,so that,it can not be applied for the classes,It can be applied for the
members of the class including inner classes.
“class” Keyword:

 Where "class" is a keyword,it can be used to represent "class" object oriented feature
in Java.

class_Name:

 Where "class_name" is an identifier assigned to the classes to recognize the classes


independently.

“extends” keyword:

 Where "extends" is a keyword,it can be used to specify super class in class syntax
inorder to reuse the members of super class in the present subclass.

NOTE:In class syntax,extends keyword will not allow more than one super
class names,because,if we provide more than one super class names in along
with extends keywords then it is becoming as multiple inheritance,it is not
possible in Java.

“implements” keyword:

 Where "implements" is a java keyword,which can be used to specify one or more


interface names inorder to implement all the interface methods in the present
class.

NOTE:In class syntax,extends keyword will allow only one super class but
implements keyword will allow more than one interface.

NOTE:In class syntax,both extends and implements keywords are optional,we


can write a class with out extends keyword,with out implements keyword and
without extends and implements keywords.If we want to write both extends
and implements keywords in class syntax then first we have to write extends
keyword then we have to write implements keyword.

Ex1:

class A{} -- Valid

public class A{} --Valid

private class A{}--InValid

class A{ private class B{} }-Valid


class A extends B{ }-Valid

class A extends B,C{ }-InValid

class A implements I{ }-Valid

class A implements I1,I2{ }-Valid

class A implements I extends B{ }-->Invalid

class A extends B implements I{ }-->Valid

static class A{ }--Invalid

class A{ static class B{ } }--->Valid

Abstract Classes:

 Abstract Classes are Java classes,which will allow both concrete methods and
abstract methods.
 In Java applications for Abstract Classes we are able to declare reference
variables,we are unable to create Objects.
 If we want to use Abstract classes in java applications,then we have to use the
following steps

a)Declare an abstract class by using "abstract" keyword

b)Declare concrete methods and abstract methods as per the application requirement.

c)Declare a sub class for the abstract class.

d)Implement all the abstract methods of abstract class at the sub class,if we voilate this
rule then compiler will rise an error.

e)In main class,in main() method,declare reference variable either for abstract class or
for sub class but we must create object for sub class.

f)Access abstract class members.

NOTE:If we declare reference variable for abstract class then we are able to
access only abstract class members.If we declare reference variable for sub
class then we are able to access both abstract class members and sub class
members.
Example programme on abstract classes:

abstract class A{

void m1(){

System.out.println("m1-A");

abstract void m2();

abstract void m3();

class B extends A{

void m2(){

System.out.println("m2-B");

void m3(){

System.out.println("m3-B");

void m4(){

System.out.println("m4-B");

}}

class Test{

public static void main(String args[]){

//A a=new A();//Error

A a=new B();

a.m1();

a.m2();

a.m3();

//a.m4();--->Error

B b=new B();
b.m1();

b.m2();

b.m3();

b.m4();

}}

status:No Compilation Error

Output:

m1-A

m2-B

m3-B

m1-A

m2-B

m3-B

m4-B

Q)What are the differences between Concrete class and Abstract class?

Ans:

1.Concrete Class is a normal Java class,it will Abstract class is a Java class,it will allow
allow 0(zero) or more number of concrete 0(zero) or more number of concrete
methods. methods.

2.In Java applications,for classes only both For abstract classes,we are able to create
reference variables and objects. only reference variables,we are unable to
create objects.

3.To declare concrete classes it is not To declare abstract classes,we must use
required to use any keyword separately. "abstract" keyword explicitly.
Interface:

 Interface is a Java container,it able to allow only abstract methods,it will not allow
concrete methods.
 Interface is a Java element,it can be utilized declare or expose only service names in
the form of abstract methods,it will not provide service implementations.
 In java applications,for the interfaces,we are able to create only reference
variables,we are unable to create objects.
 In the case of interfaces,bydefault,all the variables are "public static final".
 In the case of interfaces,by default,all the methods are "public and abstract".

NOTE:While implementing abstract methods,we must declare the methods with


public otherwise compiler will rise an error.

Procedure to use Interfaces in Java Applications:

a)Declare an interface by using "interface" keyword.

b)Declare all the service names in the form of abstract methods[Here no need to use
"abstract" keyword]

c)Declare an implementation class by including "implements" keyword for the interface[Like


sub class in the case of abstract classes but not sub class].

d)Implement all the interface methods at implementation class by declaring "public".

e)In main class,in main() method,declare reference variable either for interface or for
implementation class but we must create object for implementation class.

f)Access the interface members.

NOTE:If we declare reference variable for interface then we are able to access only
interface members,we are unable to access implementation class own members.

If we declare reference variable for implementation class then we are able


to access both interface members and implementation class own members.

Example Programme on Interfaces:

interface AccountService{

void create(String accNo,String accName,String accType);

void search(String accNo);

void delete(String accNo);


}

class AccountServiceImple implements AccountService{

public void create(String accNo,String accName,String accType){

System.out.println("Account "+accNo+" is created successfully with the following details.");

System.out.println("Account details");

System.out.println("------------------");

System.out.println("Account Number :"+accNo);

System.out.println("Account Name :"+accName);

System.out.println("Account Type :"+accType);

public void search(String accNo){

System.out.println("Account "+accNo+" Search Success");

System.out.println("Account details");

System.out.println("----------------");

System.out.println("Account Number :"+accNo);

System.out.println("Account Name :Durga");

System.out.println("Account Type :Savings");

public void delete(String accNo){

System.out.println("Account "+accNo+" Deleted Successfully");

}}

class MainProject{

public static void main(String args[]){

AccountService account=new AccountServiceImple();

account.create("abc123","Durga","Savings");

System.out.println();

account.search("abc123");
System.out.println();

account.delete("abc123");

}}

Output:

Account abc123 is created successfully with the following details.

Account details

-----------------

Account Number :abc123

Account Name : Durga

Account Type :Savings

Account abc123 Search Success

Account details

------------------

Account Number :abc123

Account Name :Durga

Account Type :Savings

Account abc123 Deleted Successfully

Q)What are the differences between classes,abstract classes and interfaces?

Ans:

1.Classes will allow only Abstract classes will allow Interfaces will allow only
concrete methods. both concrete methods and abstract methods.
abstract methods
2.For classes only,we are For abstract classes,we are For interfaces,we are able to
able to create both reference able to create only reference create only
variables and objects. variables,we are unable to referencevariables,we are
create objects. unable to create objects.
3. No default cases for the No default cases for the In the case of interfaces,by
variables in the case of variables in the case of default,all the variables are
classes. abstract classes. "public static final".
4. No default cases for the No default cases for the In the case of interfaces,by
methods in the case of methods in the case of default ,all the methods are
classes. abstract classes. "public and abstract".
5. Constructors are possible Constructors are possible in Constructors are not possible
in classes. abstract classes. in interfaces.
6. Classes will provide less Abstract classes will provide Interfaces will provide more
share ability. middle level share ability.
share ability.

Methods in Java:

 In Java applications, the main intention of providing methods is to represent entities


actions.
 To provide methods in java applications, we have to use the following syntax.

Syntax:

[Access_Modifiers] return_Type method_Name([param_List]) [throws Exception_List]

---body/implementation---

 Where Java methods are able to allow the access modifiers like
public,protected,<default> and private one at a time.
 Where Java methods are able to allow the access modifiers like
static,final,abstract,native,synchronized,strictfp.
 From the above list of access modifiers java methods are able to allow more than
one access modifier but they must be available in valid combination.

Ex:static and final are valid combination

static and abstract are invalid combination

final and abstract are invalid combination

static and synchronized valid combination

 The main intention of providing return type to the methods is to specify which type
of data we are returning from methods.
 Java is strictly typed programming language, where in java applications before
representing data first we have to decide which type of data we are representing. In
the case of methods, before returning data first we have to decide which type of data
we are returning, for this we must require return type for the methods.
 For the methods, we are able to use all primitive data types like
byte,short,int,long,float,double,char,boolean and all user defined data types like
arrays,classes,abstract classes,interfaces and "void" as return types.
 Where "void" return type is representing that the method is not returning any
value.

Where Method_Name is an identifier,it will be assigned to the methods inorder to


recognize the methods independently.

Where the main intention of parameter list is to provide some input data in order to
perform an action.

In Java methods,we are able to allow all primitive data types,all user defined data types as
parameters.

Note:"void" is only return type,it should not be used as parameter to the methods.

where "throws" can be used to bypass the generated exception from present method to
caller method.

In method syntax, "throws" keyword is able to allow more than one exception name.

With respect to the Object state insertion and retrieval there are two types of methods in
Java.

1.Mutator Methods

2.Accessor Methods
Q)What is the difference between Mutator Methods and Accessor Methods?

Ans:

1.Mutator Method is a normal Java method,it Accessor Method is a normal Java method,it
can be used to set/modify data on an object. can be used to get the data from an Object.

2. Ex: All setter methods[setXXX(-)} Ex: All getter methods[getXXX()] in Java


methods in Java Bean classes are treated as bean classes are treated as Accessor
Mutator Methods. methods.

NOTE:Java Bean class is a normal Java class having variables and the respective
setXXX(-) methods and getXXX() methods.

Example Programme on Mutator Methods and Accessor Methods:

class Employee //Java Bean class

private int eno;

private String ename;

private float esal;

public void setEno(int eno1)//Mutator Method

eno=eno1;

public void setEname(String ename1)//Mutator Method

ename=ename1;

public void setEsal(float esal1)//Mutator Method

esal=esal1;

}
public int getEno()//Accessor Method

return eno;

public String getEname()//Accessor Method

return ename;

public float getEsal()//Accessor Method

return esal;

}}

class Test{

public static void main(String[] args){

Employee e=new Employee();

e.setEno(111);

e.setEname("Durga");

e.setEsal(5000.0f);

System.out.println("Employee Details");

System.out.println("-------------------");

System.out.println("Employee Number :"+e.getEno());

System.out.println("Employee Name :"+e.getEname());

System.out.println("Employee Salary :"+e.getEsal());

}}
Output:

Employee Details

-------------------------

Employee Number :111

Employee Name :Durga

Employee Salary :5000.0

Variable-Argument method[Var-Arg Method]:

 In general,in Java applications,if we define any method with "n" no of parameters


then to access that method we must pass the same "n" no.of parameters values
otherwise compiler will rise an error.
 As per the requirement,we want to define a method and we want to access that
method by passing variable no.of parameters values.To achive this
requirement,JDK5.0 version has provided a separate method convention called as
"variable-Argument" method.
 Variable-Argument method is a normal java method,which contains variable-
Argument parameter,where Variable-Argument parameter is an array
representation,it able to store all the argument values in the form of an array while
accessing variable-argument method with a parameter values set.

Syntax:

return_Type method_Name(Data_Type ... var_Name)

----impl-----
}

Example Programme on Variable-Argument Method:

class A{

void add(int ...a)//int[] a

System.out.println("No of Arguments :"+a.length);

System.out.println("Arguments List :");

int result=0;

for(int i=0;i<a.length;i++){

System.out.println(a[i]+" ");

result=result+a[i];

System.out.println();

System.out.println("Addition :"+result);

System.out.println("--------------------------");

}}

class Test{

public static void main(String args[]){

A a=new A();

a.add();

a.add(10);

a.add(10,20);

a.add(10,20,30);

}}
Output:

No of Arguments :0

Argument List :

Addition :0

-------------------------------------

No of Arguments :1

Argument List :10

Addition :10

-------------------------------------

No of Arguments :2

Argument List :10 20

Addition :30

-------------------------------------

No of Arguments :3

Argument List :10 20 30

Addition :60

-------------------------------------

 In the case of var-arg method,we are able to pass normal parameters along with
var-arg parameter but they must be provided before var-arg parameter because
in var-arg methods var-arg parameter is always last parameter.
 Due to the above reason,it is not possible to provide more than one var-arg
parameter to a single var-arg method.

Ex:

void m1(int ... a){} --->Valid

void m1(float f,int ... a){} ---> Valid

void m1(int ... a,float f){} ---> InValid

void m1(int ... a,float ... f){} --->InValid


Syntax to create Object:

 In Java applications,the main intention to create objects is,

1.To store entities data.

2.To access the members of a particular class.

 To create an object for a particular class,we have to use the following syntax.

Class_Name ref_var=new Class_Name([param_List]);

| |

==============
|

Constructor

class A{

A a=new A();

When JVM encounter the above instruction,JVM will perform the following actions.

1.creating memory

2.Generating Identities

3.Providing initializations

1.Creating Memory:

 JVM will send a request to Heap manager to create an object when it encounter
"new" keyword.
 JVM will identify object memory size by recognizing all the instance variables
available in the respective class.
 As per JVM requirement,Heap Manager will create a block of memory at Heap
Memory.

2.Generating Identities:

 After creating a block of memory for JVM requirements,heap manager will assign a
random integer value as an identity for the object called as "HashCode" value.
 After getting HashCode value,Heap Manager will send that hashCode value to
JVM,where JVM will convert that hashCode value in the form of its Hexa Decimal
value called as "Reference Value".
 After getting Object reference value,JVM will assign that reference value to a variable
called as "Reference Variable".

3.Providing initializations:

 After creating object and its identities,JVM will allocate memory blocks of the
instance variables in the object on the basis of their data types.
 After getting memory blocks for the instance variables,JVM will provide inital values
to the instance variables by searching initializations at the respective constructor
and at the class level declarations.
 If instance variables are not having initializations at both constructor and at class
level declarations then JVM will provide default values as initial values on the
basis of their datatypes.

To get hashcode value of an object we have to use the following method.

public native int hashcode()

To get reference value of an object,we have to use the following method.

public String toString()

Example programme on hashCode() and toString():

class A extends Object{ //Super Class for any Java Class(Object)


int i=10;

float f=22.22f;

class Test{

public static void main(String args[]){

A a=new A();

int hashCode=a.hashCode();

System.out.println(hashCode);

String ref_Value=a.toString();

System.out.println(ref_Value);

}}

Output:

1802307482

A@6b6d079a

 In Java Programming language there is a common and default super class for each
and every java class[Predefined classes,user defined classes] that is
"java.lang.Object" class.

java.lang.Object class contains the following methods.

hashCode()

toString()

equals()

clone()

finalize()

wait()

wait(int time)

wait(int time,int time)

notify()

notifyAll()
getClass()

 All the above methods are common to each and every class,we can access these
methods on any class reference variable.
 In the above programme,when we access hashCode() method and toString()
method on "class A" reference variable then JVM will search for the respective
method first on the respective class, if these methods are not available at the
respective class then JVM will search for these methods in the respective super
class.If no super class is existed explicitly then JVM will search for these methods in
the common and default super class that is "Object" class.

Q)In Java applications,every class having a default super class that is


"java.lang.Object" class.In Java applications,if we declare a "class B" and if we
extend this from "class A" explicitly then "class B" is having two super classes
[class A,Object],it shows multiple inheritance clearly then how can we say
multiple inheritance is not possible in Java?

Ans:

class A{

class B extends A,Object{

}
 Ans:In Java applications,Object class is a common and default super class for every
java class when ever they are not extending from any super class explicitly.If any
class is extending super class then the respective subclass is not having Object class
as a super class directly,
 Object class is a super class for the respective sub class through the explicit super
class that is through "multi level" inheritance not through multiple inheritance.

class A extends Object{

class B extends A{

In Java applications,if we pass any reference variable as parameter to System.out.println()


method then JVM will access toString() method on the provided reference variable.

In this case,JVM will search for toString() method in the respective class,if it is not available
then JVM will search for toString() method in explicit super class,still if toString() method is
not available then JVM will search and execute toString() method in Object class.
Example Programme on toString() method:

class A

class Test

public static void main(String args[])

A a =new A();

String ref_Val=a.toString();

System.out.println(ref_Val);

System.out.println(a.toString());

System.out.println(a);

Output:

A@546da8eb

A@546da8eb

A@546da8eb

In Java applications,any reference variable as parameter to System.out.println(-) method


then JVM will access Object class toString() method,it will display object reference
value,but,as per the application requirement,we want to display the respective entity details
instead of object reference value.

To achieve the above requirement,we have to define our own toString() method in the
respective entity class.

In this case JVM will execute our own toString() method instead of executing Object
class toString() method.
Example programme on User-Defined toString() method:

class Employee{

String eid="E-111";

String ename="Durga";

String eaddr="Hyderabad";

public String toString(){

System.out.println("Employee Details");

System.out.println("------------------");

System.out.println("Employee Id :"+eid);

System.out.println("Employee Name: "+ename);

System.out.println("Employee Address: "+eaddr);

return "";

}}

class Test{

public static void main(String args[]){

Employee emp=new Employee();

System.out.println(emp);

}}

Output:

Employee Details

-------------------------

Employee Id :E-111

Employee Name : Durga

Employee Address : Hyderabad


NOTE:In Java some predefined classes like String,StringBuffer,Exception,Thread,
all wrapper classes..are not depending on Object class toString() method,they are
having their own toString() methods inorder to display their own data instead of
Object reference value.

Example programme on toString() method on Predefined Classes:

class Test{

public static void main(String args[]){

String str=new String("abc");

System.out.println(str);

Exception e=new Exception("My Exception");

System.out.println(e);

Thread t=new Thread();

System.out.println(t);

Integer i=new Integer(10);

System.out.println(i);

}}

Output:

abc

java.lang.Exception: My Exception

Thread[Thread-0,5,main]

10

There are two types of Objects in Java:

1.Immutable Objects

2.Mutable Objects
Q)What is the difference between Immutable Object and Mutable Object?

(or)

Q)What is the difference between String and StringBuffer?

Ans:Immutable Object is a Java object,it will not allow modifications on its content,if we
perform operations over immutable objects content,data will be allowed for the operations
but the resultent data must be stored by creating new object,not in original object.

Ex: String class objects are immutable

All wrapper classes like Byte,Integer,Float,....are immutable

Mutable Object is a Java object,it will allow modifications over the data directly.

Ex:All Java Objects including StringBuffer by default mutable.

class Test{

public static void main(String args[]){

String str1=new String("Durga");

String str2=str1.concat("Software");

String str3=str2.concat("Solutions");

System.out.println(str1);

System.out.println(str2);

System.out.println(str3);

StringBuffer sb1=new StringBuffer("Durga");

StringBuffer sb2=sb1.append("Software");

StringBuffer sb3=sb2.append("Solutions");

System.out.println(sb1);

System.out.println(sb2);

System.out.println(sb3);

}}
Output:

Durga

DurgaSoftware

DurgaSoftwareSolutions

DurgaSoftwareSolutions

DurgaSoftwareSolutions

DurgaSoftwareSolutions

Q)What is the difference between Object and Instance?

Ans:Object is a memory element to store data.

Instance is a copy of values available in an object at a particular point of time.

Every object is able to manage no. of instances but we are able to access only
the latest instance.
Constructors:

1)Constructor is a Java feature,it can be used to construct the objects.

2)The role of the constructors in Object creation is to identify memory size and to
provide initializations for the object.

3)Constructors will be executed exactly at the time of creation objects,not before creating
object,not after creating objects.

4)Constructors will be utilized to provide initializations for the class level variables at the
time of creating Object.

5)Constructors should have the same name of class name.

6)Constructors will not have return types.

7)Constructors will not allow the access modifiers like static,final,abstract,...

8)Constructors will allow the access modifiers like public,protected,<default> and


private.

9)Constructors will allow "throws" keyword as part of its syntax to bypass the generated
exception from present Constructor to caller.
Syntax of Constructors:

[Access_Modifier] Class_Name([param_List])[throws Exception_List]

-----body------------

NOTE1:If we declare a constructor with out its class name then compiler will not
treate the provided constructor as a constructor,compiler will treate the provided
constructor as normal Java method with out the return type,compiler will rise an
error like

"Invalid method declaration; return type required".

NOTE2:If we provide return type to the constructor then compiler and JVM will
treate that constructor as a normal java method,which satisfies method Syntax.In
this case compiler will not rise any error and JVM will not rise any exception.If we
access the provided constructor as normal java method then it will be executed.

NOTE3:Java methods may allow the same class name as method name.

Example programme on,classname same as methodname:

class A{

void A(){

System.out.println("A-con");

}}

class Test{

public static void main(String args[]){

A a =new A();

a.A();

}}

Output:

A-con
NOTE4:If we declared the constructors to the access modifiers like
static,final,abstract...then compiler will rise an error like "modifier XXX is not
allowed here".

NOTE:If we declare any constructor as private then we have to access that


constructor with in the same class,it is not possible to access that constructor in
outside of the respective class.

In Java,there are two types of constructors.

1)Default Constructors

2)User-defined Constructors

If we provide any constructor explicitly in any class then that constructor is called as "User-
Defined Constructor".

There are two types of user-defined Constructors

1.0-argument Constructor:It is a constructor with out parameters provided by the


developers as per their application requirements.

2.Parametrized Constructor:It is a constructor with at least one parameter provided


by the developers as per their application requirements.
Example programme on parameterized constructor:

class Account{

String accNo;

String accName;

String accType;

public Account(String accNo1,String accName1,String accType1){

accNo=accNo1;

accName=accName1;

accType=accType1;

public String toString(){

System.out.println("Account is created Successfully with the following details");

System.out.println("Account details");

System.out.println("--------------------");

System.out.println("Account Number :"+accNo);

System.out.println("Account Name :"+accName);

System.out.println("Account Type :"+accType);

return "";

}}

class Test{

public static void main(String args[]){

Account acc=new Account("abc123","Durga","Savings");

System.out.println(acc);

}}
Output:

Account is created Successfully with the following details

Account details

------------------------

Account Number : abc123

Account Name :Durga

Account Type :Savings

In the above programme,if we set account details by using any method like
setAccountDetails() then account details will be set to Account class Object after creating
Object as secondary data,not as initial data,here in account object initial data will be null
values [default values of String].

In the above context,if we want to set our data as initial data in the object then we
have to set account details at the time of creating object,not after creating object.To
achieve this,we have to use constructor to set data to Object.
Default Constructor:

 It is a 0-argument constructor provided by the compiler when ever we are not


provided any constructor explicitly.
 Compiler will provide 0-argument constructor always,compiler will not provide
parametrized constructor as default constructor.

NOTE:In Java,default constructors is provided by the compiler only,not by JVM.

D:\JAVA7\Test.java

class Test{

On Command prompt.

D:\JAVA7\javac Test.java

D:\JAVA7\javap Test

compiler from Test.java

class Test extends java.lang.Object{

Test();------default constructor

NOTE:In Java,always default constructors are 0-argument constructors but all the
0-argument constructor need not be default constructors,some 0-argument
constructors are provided by compiler and some other 0-argument constructors
are provided by user explicitly.

 If we provide more than one constructor with the same name and with different
parameter list then it is called as "Constructor Overloading".

Example programme on Constructor Overloading:

class Person{

Person(){

System.out.println("0-argument Con");

}
Person(String name){

System.out.println("String-Parameterized Constructor");

Person(String name,String address){

System.out.println("String,String-parameterized con");

}}

class Test{

public static void main(String args[]){

Person p1=new Person();

Person p2=new Person("Durga");

Person p3=new Person("Durga","Hyderabad");

}}

Output:

0-argument Con

String -Parameterized Constructor

String,String-parameterized con

Q)Is it possible to overload the constructors or not?

Ans:Yes,it is possible to overload the constructors in Java,but it is not possible to override


the constructors in Java because constructors are not inheritable from super class to
subclass.

Realtime utilization of Constructors:

Consider the following Java class,

class EmployeeService{

void add(String eid,String ename,String eaddr){

---load and register the driver----

---establish connection-------
---create Statement----

---execute insert sql query---

void search(String eid){

---load and register the driver----

---establish connection-------

---create Statement----

---execute insert sql query---

void delete(String eid){

---load and register the driver----

---establish connection-------

---create Statement----

---execute insert sql query---

}}

NOTE:If we use the above convention in java applications then JVM has to execute
the instructions related to "load and register driver","establish
connection","Create Statement" repeatedly for each and every method call like
add(),search() and delete() method,it is unnecessary execution,it will increase
Connection objects and Statement Objects unnecessarly and it will increase
overall application execution time,it may increase overall application execution
time,it may reduce application performance.

 To overcome the above problems,we have to use constructors inorder to provide and
execute the commonly used code at the time of creating object.

class EmployeeService {

EmployeeService{

---load and register the driver----

---establish connection-------

---create Statement----
}

void add(String eid,String ename,String eaddr){

---execute insert sql query---

void search(String eid){

---execute insert sql query---

void delete(String eid){

---execute insert sql query---

}}

NOTE:In Java,we can utilize constructors to execute some instructions related to


the resources creation like Streams creation,FilesCreation,Connection and
Statement Objects creation...at the time of creating object.

Instance Context/Instance Flow of execution:

In Java,instance context is represented in the form of the following elements.

1.Instance Variables

2.Instance Methods

3.Instance Blocks

 In Java,for every Object a separate instance context will be created.

Instance Variables:

 Instance Variables is a normal Java variable,whose values will be varied from one
instance to another instance of an object.
 Instance Variable is a variable,which will be recognized and initialized just before
executing the respective class constructor.
 In Java applications,instance variables must be declared at class level and non-static,
instance variables never be declared as local variables and static variables.
 In Java applications,instance variables data will be stored in Object memory that is
"Heap Memory".
2.Instance Methods:

 Instance Method is a normal Java method,it is a set of instructions,it will represent


an action of an entity.
 In Java applications,instance methods will be executed when we access that
method.In Java applications,all the methods wont be executed with out the proper
method call.

class Account{

public void add(String accNo,String accName,String accType){

public void search(String accNo){

}}

where add(),search() methods are instance methods.

Example programmes on Instance variables are executed before executing the


constructors:

class A{

int i=m1();

A(){

System.out.println("A-Con");

int m1(){

System.out.println("M1-A");

return 10;

}}

class Test{

public static void main(String args[]){

A a =new A();

}}
Output:

M1-A

A-con

class A {

int j=m1();

int m2(){

System.out.println("m2-A");

return 10;

A(){

System.out.println("A-con");

int m1(){

System.out.println("m1-A");

return 20;

int i=m2();

class Test{

public static void main(String args[]){

A a =new A();

System.out.println(a.i);

System.out.println(a.j);

a.m1();

a.m2();

}}
Output: m1-A

m2-A

A-con

10

20

m1-A

m2-A

Instance Block:

 Instance Block is a set of instructions which will be recognized and executed just
before executing the respective class constructors.
 Instance Block as are having the same power of constructors,it can be used to
include the code related to resource creation like Streams,Files,Database
Connections....

Syntax:

---instructions----

Example programme on Instance Block:

class A {

A(){

System.out.println("A-CON");

System.out.println("IB-A");

}}

class Test{
public static void main(String args[]){

A a=new A();

}}

Output:

IB-A

A-CON

Example programmes on Instance variables,blocks and methods:

class A {

A(){

System.out.println("A-CON");

System.out.println("IB-A");

int m1(){

System.out.println("m1-A");

return 10;

int i=m1();

class Test{

public static void main(String args[]){

A a=new A();

}}
Output:

IB-A

m1-A

A-CON

class A{

int m1(){

System.out.println("m1-A");

return 10;

System.out.println("IB-A");

int i=m2();

A(){

System.out.println("A-con");

int i=m1();

System.out.println("IB1-A");

int m2();

System.out.println("m2-A");

return 20;

}}
class Test{

public static void main(String args[]){

A a1=new A();

A a2=new A();

}}

Output:

IB-A

m2-A

m1-A

IB1-A

A-con

IB-A

m2-A

m1-A

IB1-A

A-con

'this' keyword:

 'this' is a Java keyword,it can be used to represent current class object.

In Java applications,we are able to utilize 'this' keyword in the following four ways.

1.To refer current class variable

2.To refer current class methods

3.To refer current class constructors

4.To refer current class object


1.To refer current class variables:

 If we want to refer current class variables by using 'this' keyword then we have to
use the following syntax.

this.var_Name

 NOTE:In Java applications,if we have the same set of variables at local and
at class level and if we access that variables then JVM will give first priority
for local variables,if local variables are not available thenJVM will search for
that variables at class level,even at class level also that variables are not
available then JVM will search at super class level.At all the above
locations,if the specified variables are not available then compiler will rise
an error.
 NOTE:In Java applications,if we have same set of variables at local and at
class level then to access class level variables over local variables we have
to use 'this' keyword.

Example programme To refer current class variables:

class A{

int i=10;

int j=20;

A(int i,int j) {

System.out.println(i+" "+j);

System.out.println(this.i+" "+this.j);

}}

class Test{

public static void main(String args[]){

A a=new A(100,200);

}}

Output:

100 200

10 20
NOTE:Real time utilization of 'this' keyword while accessing class level
variables.In general,in enterprise applications,we are able to write no. of
Java bean classes as per application requirement.In Java bean classes,we
are able to provide variables and their setter methods and getter
methods.In Java bean classes,in setter methods,always we have to assign
local variable value to class level variable.In this context,to refer class level
variable over local variable we have to use 'this' keyword.In getter
methods,always,we have to return class level variables but where it is not
required to use 'this' keyword,because,in getter methods no local variables.

Example programme on “this” keyword:

class User{

private String uname;

private String upwd;

public void setUname(String uname) {

this.uname=uname;

public void setUpwd(String upwd) {

this.upwd=upwd;

public getUname() {

return uname;

public getUpwd(){

2.To refer current class method:

 If we want to refer current class method by using 'this' keyword then we have to use
the following syntax.

this.method_Name([param_List]);
Example programme on “this” to refer current class method:

class A{

void m1(){

System.out.println("m1-A");

void m2(){

System.out.println("m2-A");

m1();

this.m1();

}}

class Test{

public static void main(String args[]){

A a=new A();

a.m2();

}}

Output:

m2-A

m1-A

m1-A

3.To refer current class constructors:

 If we want to refer current class constructor by using 'this' keyword then we have to
use the following syntax.

this([param_List]);
Example programme on “this” to refer current class constructors:

class A{

A(){

this(10);

System.out.println("A-0-arg-con");

A(int i){

this(22.22f);

System.out.println("A-float-int-con");

A(float f){

this(10.0);

System.out.println("A-float-param-con");

A(double d){

System.out.println("A-double-param-con");

}}

class Test{

public static void main(String args[]){

A a=new A();

}}

Output:

A-double-param-con

A-float-param-con

A-float-int-con

A-0-arg-con
NOTE:In the above programme we have provided more than one constructor with
the same name and with the different parameter list,this process is called as
"Constructor Overloading".

In the above programme,we have called all the current class constructors by using
'this' keyword in chain fashion,this proccess is called as "Constructor Chaining".

NOTE:If we want to access current class constructor by using 'this' keyword then
the respective 'this' statement must be provided as first statement.

NOTE:If we want to refer current class constructor by using 'this' keyword then
the respective 'this' statement must be provided in the current class another
constructor,not form normal Java method.

 If we violate the above two rules then compiler will rise an error like "call to this
must be first statement in constructor".
 Due to the above reasons,we are able to access only one current class constructor by
using 'this' keyword from another current class constructor,it is not possible to
access more than one current class constructors by using 'this' from a single current
class constructor.

Example programme on,How to use “this” keyword in a valid form:

class A{

A(){

this(10);

this(22.22f);---->InValid

A(int i){

A(float f){

}}

Example programme on “this” keyword:

class A{

A(){

this(10);

System.out.println("A-0-arg-con");
}

A(long d){

System.out.println("A-long-param-con");

A(double d){

System.out.println("A-double-param-con");

}}

class Test{

public static void main(String args[]){

A a =new A();

}}

Output:

A-long-param-con

A-0-arg-con

 In the above application, when JVM encounter 'this(10)' then JVM will search for a
constructor having matched parameter, if it is not available then JVM will search for
a constructor having next higher data type parameter.
 In the above application,JVM will search for int- parameterized constructor for
'this(10)' constructor call, if it is not available then JVM will search for long-
parameterized constructor, if it is not available then JVM will search for float
parameterized and double parameterized constructors in the same class.

4.To return Current class Object:

Example programme on “this” to return current class Object:

class A{

A getRef1(){

A a=new A();

return a;

}
A getRef2(){

return this;

}}

class Test{

public static void main(String args[]){

A a=new A();//[a=abc123]

System.out.println(a);

System.out.println();

System.out.println(a.getRef1());//[abc123.getRef1()]

System.out.println(a.getRef1());//[abc123.getRef1()]

System.out.println(a.getRef1());//[abc123.getRef1()]

System.out.println();

System.out.println(a.getRef2());//[abc123.getRef2()]

System.out.println(a.getRef2());//[abc123.getRef2()]

System.out.println(a.getRef2());//[abc123.getRef2()]

}}

Output:

A@5e3a78ad

A@50c8d62f

A@3165d118

A@138297fe

A@5e3a78ad

A@5e3a78ad

A@5e3a78ad
 In the above programme,for every call of getRef1() method JVM will encounter "new"
keyword,JVM will create new Object for class A every time and JVM will return
one(new) object reference every time.This approach will increase no. of objects in
Java application,it will not provide Objects reusability.
 In the above programme,for every call of getRef2() method JVM will encounter
"return this" statement,JVM will not create new Object for class A every time,JVM will
return the same reference value on which we calling getRef2() method.This approach
will increase Objects reusability.

'static' keyword:

 Static is a Java keyword,it will improve sharability in Java applications.In Java


applications,static keyword will be utilized in the following four ways.

1.Static variables

2.Static methods

3.Static blocks

4.Static import

1.Static variables:

 Static variables are normal Java variables,which will be recognized and executed
exactly at the time of loading the respective class bytecode to the memory.
 Static variables are normal java variables,they will share their last modified values to
the future objects and to the past objects of the respective class.
 In Java applications,static variables will be accessed either by using the respective
class reference variable or by using the respective class name directly.
 In Java applications,static variables are always class level variables,they never be
local variables.
 In Java applications,static variable vlaues will be stored in method area,not in Stack
memory and not in Heap Memory.

NOTE:To access static variables we can use the respective class reference
variable which may or may not have reference value.To access static
variables it is sufficient to take a reference variable with null value.

NOTE:If we access any non-static variable by using a reference variable


with null value then JVM will rise an exception like
"java.lang.NullPointerException".
NOTE:In Java applications,to access current class static variables we can
use "this" keyword.

Example programme on static variables:

class A{

static int i=10;

int j=10;

void m1(){

//static int k=30;--->error

System.out.println("m1-A");

System.out.println(this.i);

}}

class Test{

public static void main(String args[]){

A a=new A();

System.out.println(a.i);

System.out.println(A.i);

a.m1();

A a1=null;

//System.out.println(a1.j);--->NullPointerException

System.out.println(a1.i);

}}

Output:

10

10

m1-A

10

10
Example Programme on Static and Instance variables(allocation of variables in
memory):

class A{

static int i=10;

int j=10;

class Test{

public static void main(String args[]){

A a1=new A();

System.out.println(a1.i+" "+a1.j);

a1.i=a1.i+1;

a1.j=a1.j+1;

System.out.println(a1.i+" "+a1.j);

A a2=new A();

System.out.println(a2.i+" "+a2.j);

a2.i=a2.i+1;

a2.j=a2.j+1;

System.out.println(a1.i+" "+a1.j);

System.out.println(a2.i+" "+a2.j);

A a3=new A();

System.out.println(a3.i+" "+a3.j);

a3.i=a3.i+1;

a3.j=a3.j+1;

System.out.println(a1.i+" "+a1.j);

System.out.println(a2.i+" "+a2.j);

System.out.println(a3.i+" "+a3.j);
}}

Output:

10 10

11 11

11 10

12 11

12 11

12 11

12 10

13 11

13 11

13 11
NOTE:In Java applications,Instance variable is specific to each and every
object that is a separate copy of instance variables will be maintained by
each and every object but static variable is common to every object that is
the same copy of static variable will be maintained by all the objects of the
respective class.In Java for a particular class Byte-Code will be loaded only
one time but we can create any no.of objects.

2.Static Methods:

 Static method is a normal java method,it will be recognized and executed the time
when we access that method.
 Static methods will be accessed either by using reference variable or by using the
respective class name directly.
 In the case of accessing static methods by using reference variables,reference
variable may or may not have object reference value,it is possible to access static
methods with the reference variables having 'null' value.
 Static methods will allow only static members of the current class,static methods
will not allow non-static members of the current class directly.
 If we want to access non-static members of the current class in static methods
then we have to create an object for the current class and we have to use the
generated reference variable.
 Static methods will not allow 'this' keyword in its body but to access current class
static methods we are able to use 'this' keyword.

Example Programme on Static methods:

class A{

int i=10;

static int j=20;

static void m1(){

System.out.println("m1-A");

System.out.println(j);

//System.out.println(i);---->error

//System.out.println(this.j);----------->error

A a=new A();

System.out.println(a.i);

void m2(){

System.out.println("m2-A");

this.m1();

}}

class Test{

public static void main(String[] args){

A a=new A();

a.m1();

a=null;

a.m1();

A.m1();

}}
Output:

m1-A

20

10

m1-A

20

10

m1-A

20

10

Q)Is it possible to print a line of text on command prompt with out using
main() method?

Ans:Yes,it is possible to display a line of text on command prompt with out using a
static variable and static method.

Example programme on without main() method:

class Test{

static int i=m1();

static int m1(){

System.out.println("Welcome to durga software soultions");

System.exit(0);//to terminate the application

return 10;

}}

Output:

Welcome to durga software soultions

 If we provide 'Test' class name along with 'java' command on command prompt then
JVM will take main class from command prompt,JVM will search for its .class file,if it
is available then JVM will load main class bytecode to the memory that is Test class
bytecode.At the time of loading Test class bytecode to the memory,JVM will
recognize and initialize static variable,as part of initialization,JVM will execute static
method.
 By the execution of static method,JVM will display the required message on
command prompt, when JVM encounter System.exit(0) statement then JVM will
terminate the application.

NOTE:The above question and answer is valid upto JAVA6 version,it is not valid
in JAVA7 version,because,In JAVA6 version JVM will load main class bytecode
to the memory irrespective of main() method availability.In JAVA7,JVM will
load main class bytecode to the memory with main() method availability only.If
we run the above code in JAVA7 version then JVM will display the following
error message.

Error:Main Method not found in class Test,please define the main method as:

public static void main(String args[])

3.Static Block:

 Static Block is a set of instructions,which will be recognized and executed at the time
of loading the respective class bytecode to the memory.
 Static blocks will allow static members of the current class directly.
 Static blocks will not allow non-static members of the current class directly,where if
we want to access non-static members in static block then we must create object for
the current class and we have to use the generated reference variable.
 Static blocks will not allow 'this' keyword in its body.

Example programme on Static Blocks:

class A{

int i=10;

static int j=20;

static{

System.out.println("SB-A");

System.out.println(i);//-------->Error

A a=new A();

System.out.println(a.i);
System.out.println(j);

System.out.println(this.j);-------->Error

}}

Output:

SB-A

10

20

Exception in thread "main" java.lang.NoSuchMethodError:main

Q)Is it Possible to print a line of text on command prompt with out using
main() method,static variable and static method?

Ans:Yes,it is possible to display a line of text on command prompt without using


main() method,static variable,static method but by using static block.

Example Programme on with out using main() method,static variable and static
method:

class Test{

static{

System.out.println("Welcome to DurgaSoftware Soultions");

System.exit(0);//To terminate the programme

}}

Output:

Welcome to DurgaSoftware Soultions

 If we provide main class name 'Test' along with 'java' command on command prompt
then JVM will take main class name i.e Test and JVM will search for its .class file.If
Test.class file is identified then JVM will load its bytecode to the memory,at the time
of loading bytecode to the memory static block will be executed,with this,the
required message will be displayed on command prompt.When JVM encounter
System.exit(0) then JVM will terminate the programme.

NOTE:The above question and answer is valid upto JAVA6 version,it is


invalid in JAVA7 version, because,in JAVA6 version JVM will load main class
bytecode to the memory with out checking main() method availability but in
JAVA7 JVM will load main class bytecode to the memory after checking
main() method availability.If main() method is available then only JVM will
load main class bytecode otherwise JVM will not load main class bytecode.

If we use JAVA7 version to run the above programme then JVM will provide the
following message on command prompt.

Error:Main method not found in class Test,please define main method as:public static
void main(String args[])

Q)Is it possible to display line of text on command prompt with out using
main() method,static variable,static method,static block?

Ans:Yes,it is possible to display a line of text on command prompt with out using
main() method,a static variable,a static method and static block but by using "static
Anonymous Inner class".

Example programme with out using main() method,static variable,static


method,static block:

class Test{

static Object obj=new Object(){

System.out.println("Welcome To durga Software Solutions");

System.exit(0);//TO termiante the application.

}};}

Output:

JAVA6:Welcome to Durga Software Soultions

JAVA7:Error:main method not found in class Test,please define the main method
as:public static void main(String[] args)

4.static import:

 In Java,applications,if we import a particular package to the present java file then it


is possible to access all the classes and interfaces of that package directly with out
using package name every time as fully qualified name.
 If we want to access classes and interfaces of a particular package with out
importing then we must use fully Qualified name every time that we have to use
package name along with class names.
With out import statement:

java.io.BufferedReader br=new java.io.BufferedReader(new


java.io.InputStreamReader(System.in));

With import statement:

import java.io.*;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

 In Java applications,if we want to access static members of a particular class in


present java file then we must use either reference variable of the respective
class or directly class name.
 In Java applications,if we want to access static members without using the
respective class name and with out using the respective class reference variable then
we have to import static members of that respective class in the present Java file.
 To import static members of a particular class in the present java file,JDK 5.0
version has provided a new feature called as "static import".

Syntax:

import static package_Name.Class_Name.*;

It will import all the static members from the specified class.

Ex:import static java.lang.Thread.*;

import static package_Name.Class_Name.member_Name;

It will import only the specified member from the specified class.

Example programme on “static import”:

import static java.lang.Thread.MIN_PRIORITY;

import static java.lang.Thread.*;

import static java.lang.System.out;

class Test{

public static void main(String args[]){

out.println(MIN_PRIORITY);

out.println(MAX_PRIORITY);
out.println(NORM_PRIORITY);

}}

Output:

10

Static Context / Static Flow of Execution:

In Java,Static Context will be represented in the form of the following three


elements.

1.Static variables.

2.Static methods.

3.Static blocks

 In Java applications,instance context will be created separately for each and every
object but static context will be created for each and every class.
 In Java applications,static context will be recognized and executed exactly at the
time of loading the respective class bytecode to the memory.
 In Java applications,when we create object for a particular class,first,JVM has to
access constructor,before executing constructor,JVM has to load the respective class
bytecode to the memory.At the time of loading class bytecode to the memory,JVM
has to recognize and execute static context.

Example programmes on static context or static Flow of Execution:

class A{

static {

System.out.println("SB-A");

static int i=m1();

static int m1(){

System.out.println("m1-A");

return 10;
}}

class Test{

public static void main(String args[]){

A a=new A();

}}

Output:

SB-A

m1-A

class A{

static int i=m2();

static int m1(){

System.out.println("m1-A");

return 10;

static{

System.out.println("SB-A");

static int m2(){

System.out.println("m2-A");

return 20;

static int j=m1();

}
class Test{

public static void main(String args[]){

A a1=new A();

A a2=new A();

}}

Output:

m2-A

SB-A

m1-A

class A{

static int i=m2();

A(){

System.out.println("A-con");

int m1(){

System.out.println("m1-A");

return 10;

static{

System.out.println("SB-A");

int j=m1();{

System.out.println("IB-A");

}
static int m2(){

System.out.println("m2-A");

return 10;

}}

class Test{

public static void main(String args[]){

A a1=new A();

A a2=new A();

}}

Output:

m2-A

SB-A

m1-A

IB-A

A-con

m1-A

IB-A

A-con

class A{

private A(){

System.out.println("A--con");

void m1(){

System.out.println("m1--A");

}}
class Test{

public static void main(String args[]){

A a=new A();

}}

error: Test.java:10: A() has private access in A

A a=new A();

Factory Method:

 Factory Method is a method,it can be used to return the same class Object where
we have declared that method.
 Factory Method is an idea provided by a design pattern called as "Factory Method
Design Pattern".

NOTE:Design pattern is a System,it will provide problem definition and its


solution inorder to resolve design problems.

Example Programme On Factory Method:

class A{

private A(){

System.out.println("A-con");

void m1(){

System.out.println("m1-A");

static A getRef()//Factory Method

A a=new A();

return a;

}}
class Test{

public static void main(String args[]){

A a=A.getRef();

a.m1();

}}

Output:

A-con

m1-A

There are two types of Factory Methods

1.Static Factory Method

2.Instance Factory Method

Static Factory Method:

 Static Factory Method is a static method returns the same class object.

Ex:

NumberFormat nf=NumberFormat.getInstance(-);

DateFormat df=DateForamt.getInstance(--);

ResourceBundle rb=ResourceBundle.getBundle(--);

Instance Factory Method:

 If any non-static method returns the same class object then that method is called as
"Instance Factory Method".

Ex:Allmost all the String class methods are Instance Factory methods.

String str=new String("DurgaSoftware Solutions");

String str1=str.concat(" Hyderabad");

String str2=str.trim();

String str3=str.toUpperCase();
String str4=str.substring(5,14);

Singleton Class:

 If any JAVA class allows to create only one Object then that class is called as
"Singleton Class".
 Singleton Class is an idea provided by a design pattern called as "Singleton Design
Pattern".

Example programme on Singleton class:

class A{

static A a=null;

private A(){

static A getRef(){

if(a==null){

a=new A();

return a;

}}

class Test{

public static void main(String args[]){

System.out.println(A.getRef());

System.out.println(A.getRef());

System.out.println(A.getRef());

}}

Output:

A@a6eb38a

A@a6eb38a

A@a6eb38a
Example programme on,Alternative Logic for Singleton Class:

class A{

static A a=new A();

private A(){

static A getRef(){

return a;

}}

class Test{

public static void main(String args[]){

System.out.println(A.getRef());

System.out.println(A.getRef());

System.out.println(A.getRef());
}}

Output:

A@69cd2e5f

A@69cd2e5f

A@69cd2e5f

Example programme on,Another Alternative for Singleton Class:

class A{

static A a=null;

static{

a=new A();

private A(){

static A getRef(){

return a;

}}

class Test{

public static void main(String args[]){

System.out.println(A.getRef());

System.out.println(A.getRef());

System.out.println(A.getRef());

}}

Output:

A@a6eb38a

A@a6eb38a

A@a6eb38a
final Keyword:

final is a Java Keyword it can be used to declare constant expressions.

In Java applications,there are three ways to utilize 'final' keyword.

1.final variable

2.final method

3.final class

1.final variable:

final variable is a variable,it will not allow modifications on its value.

Ex:

final int i=10;

i=i+10;

Output:

CE: Test.java:4: cannot assign a value to final variable i

i=i+10;

1 error

Ex:

for(final int i=0;i<10;i++)-error

System.out.println(i);

}
Output:

CE: Test.java:2: illegal start of type

for(final int i=0;i<10;i++)

Test.java:2: ')' expected

for(final int i=0;i<10;i++)

NOTE:In general, in bank applications, after creating an account it is


possible to change the account details like account name, address
details....but it is not possible to update 'accNo' value once it is created. Due
to this reason, we have to declare 'accNo' variable as 'final'.

2.final method:

final method is a Java method,it will not allow method overriding.

3.final class:

final class is a Java class,it will not allow inheritance.In Java applications,super
classes never be declared as final classes,but subclasses may be final.

final class A

class B extends A

Status:Invalid

class A

}
final class B extends A

Status:Valid

In Java applications to declare constant variables Java has provided a convention like
to declare constants with "public static final".

Examples programmes on “final” keyword:

System:

public static final PrintStream out;

public static final InputStream in;

public static final PrintStream err;

Thread:

public static final int MIN_PRIORITY=1;

public static final int NORM_PRIORITY=5;

public static final int MAX_PRIORITY=10;

Example Programme on to declare constants with "public static final":

class MailStatus{

public static final String AVAILABLE="Available";

public static final String BUSY="Busy";

public static final String IDLE="Idle";

class Test{

public static void main(String args[]){

System.out.println(MailStatus.AVAILABLE);

System.out.println(MailStatus.BUSY);

System.out.println(MailStatus.IDLE);

}}
Output:

Available

Busy

Idle

To declare constant variables in Java applications if we use the above convention


then we are able to get the following problems.

1.We must declare "public static final" for each and every constant variable explicitly.

2.It is possible to allow multiple data types to represent one type,it will reduce
typedness feature for Java applications.

3.If we access constant variables then these variables will display their values,here
constant variable values may or may not reflect the actual meaning of constant
variables.

To overcome all the problems,we have to go for "enum".

In case of enum,

1.All the constant variables are by default "public static final",no need to declare
"public static final" explicitly.

2.All the constant variables are by default the same enum type,it will improve
Typedness in Java applications.

3.All the constant variables are by default "Named Constants" that is,these constant
variables are displaying their names instead of their values.

Example programme on "enum" keyword:

enum MailStatus{

AVAILABLE,BUSY,IDLE;

class Test{

public static void main(String args[]){

System.out.println(MailStatus.AVAILABLE);

System.out.println(MailStatus.BUSY);
System.out.println(MailStatus.IDLE);

}}

Output:

Available

Busy

Idle

NOTE:The default super class for every enum is “java.lang.Enum” class and
“Object” class is Super class to “Enum” class.

Internal Flow:

If we compile the above Java file then Compiler will translate "MailStatus" enum into
"MailStatus" final class like below.

final class MailStatus extends java.lang.Enum{

public static final MailStatus AVAILABLE;

public static final MailStatus BUSY;

public static final MailStatus IDLE;

---------

NOTE:In Java,java.lang.Object class is common and default super class for


all the classes.Similarly,All the Java enums are having a common and
default super class that is "java.lang.Enum".

In Java applications,it is possible to implement inheritance between two classes but it


is not possible to implement inheritance between two "enums".

In Java applications,we can utilize enum like as classes,where we can provide normal
variables,methods,constructors....
Example programme on "enum" keyword by using reference :

enum Apple{

A(500),B(250),C(100);

int price;

Apple(int price){

this.price=price;

public int getPrice(){

return price;

}}

class Test{

public static void main(String args[]){

System.out.println("A-Grade Apple :"+Apple.A.getPrice());

System.out.println("B-Grade Apple :"+Apple.B.getPrice());

System.out.println("C-Grade Apple :"+Apple.C.getPrice());

}}

Output:

A-Grade Apple :500

B-Grade Apple :250

C-Grade Apple :100

If we compile the above programme,then compiler will translate enum into the
following class:

Translated Code for the above enum(Apple):

final class Apple extends Enum{

public static final Apple A=new Apple(500);

public static final Apple B=new Apple(250);

public static final Apple C=new Apple(100);


int price;

Apple(int price){

this.price=price;

public int getPrice(){

return price;

----

Another Example programme on "enum" keyword by using reference :

enum Book{

A(500,250),B(300,150),C(200,100);

int no_of_pages;

int cost;

Book(int no_of_pages,int cost){

this.no_of_pages=no_of_pages;

this.cost=cost;

public void getBookDetails(){

System.out.println(no_of_pages+"--------->"+cost);

}}

class Test{

public static void main(String args[]){

System.out.println("Durga Books Store");

System.out.println("-------------------");

System.out.println("No of Pages Cost");


System.out.println("-------------------");

Book.A.getBookDetails();

Book.B.getBookDetails();

Book.C.getBookDetails();

}}

Output:

Durga Books Store

---------------------------

No of Pages Cost

---------------------------

500------------->250

300------------->150

200------------->100

If we compile the above program,then compiler will translate the enum

Into the following class

Translated Code for the above enum(Book):

final class Book extends Enum{

public static final Book A=new Book(500,250);

public static final Book B=new Book(300,150);

public static final Book C=new Book(200,100);

int cost;

int no_of_pages;

Book(int no_of_pages,int cost){

this.no_of_pages=no_of_pages;

this.cost=cost;

public void getBookDetails(){


System.out.println(no_of_pages+"--------->"+cost);

----

Class.forName(--):

Consider the following programme:

class A{

static{

System.out.println("Class Loading");

A(){

System.out.println("Object Creating");

}}

class Test{

public static void main(String args[]){

A a=new A();

}}

In the above programme,when we access 'A' class constructor along with 'new'
keyword then JVM will perform automatically the following two actions.

1.Loading the class bytecode to the memory.

2.Creating object for the respective class

In the above context,as per the application requirement we want to load the
respective class bytecode to the memory without creating object.To achieve this
requirement,we have to use the following method from "java.lang.Class" class.

public static Class forName(String class_Name) throws ClassNotFoundException

Ex:Class c=Class.forName("A");
When JVM encounter the above instruction,JVM will perform the following actions.

1.JVM will take the provided class name from “forName()” method.

2.JVM will search for the respective .class file at current location,at Java predefined
library and at the locations refereed by "classpath" environment variable.

3.If the required .class file is not available at the above three locations then JVM rise
an exception like "java.lang.ClassNotFoundException".

4.If the required .class file is available at either of the above three locations then
JVM will load its bytecode to the memory and JVM will collect the loaded class
metadata and JVM will manage that metadata in the form "java.lang.Class" object
at heap memory.

After loading class bytecode to the memory by using "forName(-)" method,if we


want to create object for the loaded class explicitly then we have to use the following
method from "java.lang.Class" class.

public Object newInstance() throws InstantiationException,IllegalAccessException

Ex:Object obj=c.newInstance();
When JVM encounter the above instruction,JVM will perform the following actions.

1.JVM will go to the respective "Class" object in Heap memory.

2.JVM will search for non-private and 0-arg constructor in the "Class" object.

3.If the required constructor is available then JVM will execute it and JVM will
create object for the respective class in Heap Memory.

4.If the constructor is not 0-argument,if the constructor is parametrized


constructor then JVM will rise an exception like "java.lang.InstantiationException".

5.If the constructor is private then JVM will rise an exception like

"java.lang.IllegalAccesException".

6.If the constructor is private and parametrized constructor the JVM will rise only
one exception that is "java.lang.InstantiationExecption".

Example programme on creating Object using newInstance():

class A{

static{

System.out.println("Class Loading");

A(){

System.out.println("Object creating");

}}

class Test{

public static void main(String args[]) throws Exception{

Class c=Class.forName("A");

Object obj=c.newInstance();

}}

Output:

Class Object

Object creating
NOTE:In Jdbc Applications,to perform database operations it is mandatory
to load driver class bytecode to the memory.To load Driver class bytecode to
the memory we have to use Class.forName() method.

Ex:Class.forName("oracle.jdbc.OracleDriver");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

NOTE:"Servlet" is a server side componet in web applications,it will be


executed by the Container[A part in Server] by following lifeCycle actions
with out using main() method.To perform Servlet life cycle actions like
"Servlet loading","Servlet Instantiation" container will execute
Class.forName() and newInstance() internally.

Importance of main() method in Java:

The main intention of main() method in Java applications is,

1.To define application logic in Java programme.

2.To define starting point and ending point for the applications execution.
Syntax:

public static void main(String args[])

----application logic---

 main() method is not predefined method and user defined method,it is a


conventional method with fixed prototype and with user defined implementation.
 In Java,JVM is implemented in such a way to access main() method automatically in
order to execute application logic.

Q)What is the requirement to declare main() method as public?

 In Java applications,JVM has to access main() method inorder to start application


execution.
 To access main() method by JVM first main() scope must be available to JVM.In
this context,to bring main() method scope to JVM,we must declare main() method
as "public".

Case-1:

 If main() method is declared as "private" then main() method will be available upto
the main class,not to JVM.

Case-2:

 If main() method is declared as "default" then main() method will be available upto
the package where main class is existed,not to the JVM.

Case-3:

 If main() method is declared as "protected" then main() method will be available


upto the package where main class is existed and upto child classes available other
packages but not to the JVM.

Case-4:

 To make available main() method JVM,only one possibility we have to take that is
"public",public members will be available through out our system,so that,JVM can
access main() method to start application execution.
NOTE:In Java applications,if we declare main() method without "public" then
compiler will not rise any error but JVM will provide the following.

JAVA6:Main Method not public.

JAVA7:Error:Main method not found in class Test,please define main method as:public
static void main(String args[])

Q)What is the requirement to declare main() method as "static"?

 Ans:In Java applications,to start application execution JVM has to access main()
method.JVM was implemented in such a way that to access main() method by using
the respective main class directly.
 In Java applications,only static methods are eligible to access by using their
respective class name,so that,as per the JVM predefined implementation we must
declare main() method as static.

NOTE:In Java applications,if we declare main() method without "static" then


compiler will not rise any error but JVM will provide the following.

JAVA6:java.lang.NoSuchMethodError:main

JAVA7:Error:Main method is not static in class Test,please define main method as:public
static void main(String[] args)

Q)Is it possible to interchange "public" and "static" in main() method syntax?

 Ans:Yes,it is possible to interchange "public" and "static" in main() method


syntax,because, normal Java methods will allow more than one access modifier in
any order but in valid combination.

public static void main(String args[]) -->valid

static public void main(String args[]) -->Valid

public static final main(String[] args) -->Valid

public static abstract void main(String args[]) -->invalid

public void static main(String[] args) -->Invalid

Q)What is the requirement to provide "void" as return type to main() method?

 Ans:In Java applications,as per Java conventions,JVM will start application execution
at the starting point of main method and JVM will terminate application execution at
the ending point of main() method.Due to this convention,we must start application
logic at the starting point of main() method and we must terminate application logic
at the ending point of main() method.To follow this Java convention we must not
return any value from main() method for this,we must provide "void" as return type.
NOTE:In Java applications,if we declare main() method with out void return
type then compiler will not rise any error but JVM will provide the following

JAVA6: java.lang.NoSuchMethodError:main

JAVA7:Error:Main method must return a value of type void in class Test,please define
the main method as:

public static void main(String[] args)

NOTE:The name of this method "main" is to show the importance of this


method.

Main method parameters:

Q)What is the requirement to provide parameter to main() method?

 Ans:In Java applications,there are three ways to provide input to the Java programs.

1.Static Input

2.Dynamic Input

3.Command Line Input

1.Static Input:

 Providing input to the Java program at the time of writing Java program.

Ex:

int i=10;

int j=20;

void add()

System.out.println(i+j);

}
2.Dynamic Input:

 Providing Input to the Java program at runtime or at execution time.

D:\Java7>javac Add.java

D:\java7>java Add

First value : 10

Second value :20

Addition :30

3.Command Line Input:

 Providing input to the Java program along with "java" command on command
prompt.

Ex:

D:\java7>javac Add.java

D:\java7>java Add 10 20

Addition : 30

If we provide command line input like above in Java applications then JVM will perform
the following actions.

a)JVM will read all the command line input at the time of reading main class name from
command prompt.

b)JVM will store all the command line inputs in the form of String[]

c)JVM will pass the generated String[] as parameter to main() method at the time of
calling main() method.

Due to the above JVM actions,the main requirement to provide main() method
parameters is to store all the command line inputs in the form String[] array.
Q)What is the requirement to provide only String data type as parameter to
the main() method?

 Ans:In general,from application to application or from developer to developer the


types of command line input may be varies,here even developers are providing
different types of command line input our main() method must store all the
command line input.In Java only String data types is able to represent any type of
data so that String data types is required as parameter to main() method.
 To allow different types of command line input main() method must require String
dataType.

Q)What is the requirement to provide an array as parameter to main() method?

 Ans:In general,from application to application and from developer to developer no.of


command line inputs may be varied,here even developers are providing variable
no.of command line inputs our main() method parameter must store them.In Java,to
store more than one value we have to take array.Due to this reason,main() method
must require array type as parameter.
 main() method will take array type as parameter is to follow multiple no.of command
line input.

Example programmes on Command Line Input():

class Test{

public static void main(String args[]){

for(int i=0;i<args.length;i++){

System.out.println(args[i]);

}}
O/P:D:\java7>javac Test.java

D:\java7>java Test 10 "abc" 22.22f 34.345 'A' true

10

"abc"

22.22f

34.345

'A'

true

class Test{

public static void main(String args[])throws Exception{

int fval=Integer.parseInt(args[0]);

int sval=Integer.parseInt(args[1]);

System.out.println("Addition :"+(fval+sval));

System.out.println("Subtraction :"+(fval-sval));

System.out.println("Multiplication :"+(fval*sval));

}}

O/P:D:\java7>javac Test.java

D:\java7>java Test 10 5

Addition :15

Subtraction :5

Multiplication:50

 If we declare main() method without String[] parameter then compiler will not rise
any error but JVM will provide the following.

JAVA6:java.lang.NoSuchMethodError:main

JAVA7:Error:Main Method not found in class Test,please define main method as:public
static void main(String args[])
Q)Find the valid syntaxes of main() method from the following list?

1.public static void main(String[] args) --->valid

2.public static void main(String[] abc) --->valid

3.public static void main(String args[]) --->valid

4.public static void main(String []args) --->valid

5.public static void main(string[] args) --->Invalid

6.public static void Main(String[] args) --->Invalid

7.public static int main(String[] args) --->Invalid

8.public static final void main(String[] args) --->valid

9.public final void main(String[] args) --->Invalid

10.static public void main(String[] args) --->valid

11.static void main(String[] args) --->Invalid

12.public static void main(String ... args) --->valid

Q)Is it possible to provide more than one main() method with in a single java
application?

 Ans:Yes,is it possible to provide more than one main() method with in a single java
application,but,we have to provide more than one main() method in different
classes,not in a single class.

Ex:

D:\java7\abc.java

class A{

public static void main(String args[]){

System.out.println("main()-A");

}}

class B{

public static void main(String args[]){

System.out.println("main()-B");

}}
O/P:D:\java7>javac abc.java

D:\java7>java A

main()-A

D:\java7>java B

main()-B

NOTE:If we compile the above abc.java file then compiler will generate two .class
files[A.class,B.class].To execute the above program,we have to give a class name
along with "java" command,here which class name we are providing along with
"java" command that class main() method will be executed by JVM.

NOTE:In the above program,it is possible to access one main() method from
another main() method by passing String[] as parameter and by using the
respective class name as main() method is static method.

Ex:

D:\java7\abc.java

class A{

public static void main(String args[]){

System.out.println("main()-A");

String[] str={"AAA","BBB","CCC"};

B.main(str);

B.main(args);

}}

class B{

public static void main(String args[]){

System.out.println("main()-B");

}}
O/P:D:\java7>javac abc.java

D:\java7>java A

main()-A

main()-B

main()-B

Q)Is it possible to overload main() method?

 Ans:In Java,it is possible to overload main() method but it is not possible to override
main() method,because,in Java applications static method overloading is possible but
static method overriding is possible but static method overriding is not possible.

Example programme on overload of main() method:

class Test{

public static void main(String args[]){

System.out.println("String[]-param-A");

public static void main(int[] args){

System.out.println("int[]-param-A");

}}

Output:

String[]-param-A

Relationships in JAVA:

As part of Java application development,we have to use entities as per the


application requirements.

In Java application development,if we want to provide optimizations over memory


utilization,code reusability,execution time,sharability then we have to define
relationships between entities.
There are three types of relationships between entities.

1.Has-A relationship

2.IS-A relationship

3.USE-A relationship

1.Has-A relationship:

Has-A relationship will define associations between entities in Java applications,here


associations between entities will improve communication between entities and it will
improve data navigation between entities.

There are four types of associations between entities

1.One-To-One Association

2.One-To-Many Association

3.Many-To-One Association

3.Many-To-Many Association

To achieve associations between entities,we have to declare either single reference


or array of references of an entity class in another entity class.

Ex:

class Address{

----

class Student{

----

Address[] addr;-->It will establish One-To-Many Association

}
1.One-To-One Association:

It is a relationship between entities,where one instance of an entity should be


mapped with exactly one instance of another entity.

Ex:

Every employee should have exactly one Account.

Example programme on One-To-One Association:

class Account{

String accNo;

String accName;

String accType;

Account(String accNo,String accName,String accType){

this.accNo=accNo;

this.accName=accName;

this.accType=accType;

}}

class Employee{

String eid;

String ename;

String eaddr;

Account acc;
Employee(String eid,String ename,String eaddr,Account acc){

this.eid=eid;

this.ename=ename;

this.eaddr=eaddr;

this.acc=acc;

public void getEmployee(){

System.out.println("Employee Details");

System.out.println("-----------------");

System.out.println("Employee Id :"+eid);

System.out.println("Employee Name :"+ename);

System.out.println("Employee Address :"+eaddr);

System.out.println();

System.out.println("Account Details");

System.out.println("----------------");

System.out.println("Account Number :"+acc.accNo);

System.out.println("Account Name :"+acc.accName);

System.out.println("Account Type :"+acc.accType);

}}

class OneToOneEx{

public static void main(String args[]){

Account acc=new Account("abc123","Durga N","Savings");

Employee emp=new Employee("E-111","Durga","Hyd",acc);

emp.getEmployee();

}}
Output:

Employee Details

------------------------

Employee Id :E-111

Employee Name:Durga

Employee Address:Hyd

Account Details

----------------------

Account Number :abc123

Account Name :Durga N

Account Type :Savings

Data Flow Diagram on One-To-One:


2.One-To-Many Association:

It is a relationship between entity classes,where one instance of an entity should be mapped


with multiple instances of another entity.

Ex:Single department has multiple employees.

Example Programme on One-To-Many:

class Employee{

String eid;

String ename;

String eaddr;

Employee(String eid,String ename,String eaddr){

this.eid=eid;

this.ename=ename;

this.eaddr=eaddr;

}}

class Department{

String did;

String dname;

Employee[] emps;

Department(String did,String dname,Employee[] emps){

this.did=did;
this.dname=dname;

this.emps=emps;

public void getDepartmentDetails(){

System.out.println("Department Details");

System.out.println("--------------------");

System.out.println("Department Id :"+did);

System.out.println("Department Name:"+dname);

System.out.println();

System.out.println("EID ENAME EADDR");

System.out.println("----------------");

for(int i=0;i<emps.length;i++){

Employee e=emps[i];

System.out.println(e.eid+" "+e.ename+" "+e.eaddr);

}}}

class OneToManyEx{

public static void main(String args[]){

Employee e1=new Employee("E-111","AAA","Hyd");

Employee e2=new Employee("E-222","BBB","Hyd");

Employee e3=new Employee("E-333","CCC","Hyd");

Employee[] emps=new Employee[3];

emps[0]=e1;

emps[1]=e2;

emps[2]=e3;

Department dept=new Department("D-111","Admin",emps);

dept.getDepartmentDetails();

}}
Output:

Department Details

-----------------------------

Department Id :D-111

Department Name:Admin

EID ENAME EADDR

----------------------------------

E-111 AAA Hyd

E-222 BBB Hyd

E-333 CCC Hyd

Data Flow Diagram on One-To-Many:


Many-To-One Association:

It is a relationship between entities,where multiple instances of an entity should be mapped


with exactly one instance of another entity.

Ex:Multiple Student have joined with a single branch.

Example programme on Many-To-One:

class Branch{

String bid;

String bname;

Branch(String bid,String bname){

this.bid=bid;

this.bname=bname;

}}

class Student{

String sid;

String sname;

String saddr;

Branch branch;

Student(String sid,String sname,String saddr,Branch branch){

this.sid=sid;

this.sname=sname;
this.saddr=saddr;

this.branch=branch;

public void getStudentDetails(){

System.out.println("Student Details");

System.out.println("----------------");

System.out.println("Student Id :"+sid);

System.out.println("Student name :"+sname);

System.out.println("Student Address:"+saddr);

System.out.println("Branch Id :"+branch.bid);

System.out.println("Branch Name :"+branch.bname);

System.out.println();

}}

class ManyToOneEx{

public static void main(String args[]){

Branch branch=new Branch("B-111","CS");

Student std1=new Student("S-111","AAA","Hyd",branch);

Student std2=new Student("S-222","BBB","Hyd",branch);

Student std3=new Student("S-333","CCC","Hyd",branch);

std1.getStudentDetails();

std2.getStudentDetails();

std3.getStudentDetails();

}}
Output:

Student Details

----------------------

Student Id :S-111

Student name:AAA

Student Address:Hyd

Branch Id :B-111

Branch Name:CS

Student Details

------------------------

Student Id :S-222

Student name:BBB

Student Address:Hyd

Branch Id :B-111

Branch Name:CS

Student Details

-----------------------

Student Id :S-333

Student name:CCC

Student Address:Hyd

Branch Id :B-111

Branch Name:CS
Data Flow Diagram on Many-To-One:

4.Many-To-Many Associations:

It is a relationship between entities,Where multiple instances of an entity should be mapped


with multiple instances of another entity.

Ex:Multiple Students Have Joined with Multiple Courses.


Example programme on Many-To-Many:

class Course{

String cid;

String cname;

int ccost;

Course(String cid,String cname,int ccost){

this.cid=cid;

this.cname=cname;

this.ccost=ccost;

}}

class Student{

String sid;

String sname;

String saddr;

Course[] crs;

Student(String sid,String sname,String saddr,Course[] crs){

this.sid=sid;

this.sname=sname;

this.saddr=saddr;

this.crs=crs;

public void getStudentDetails(){

System.out.println("Student Details");

System.out.println("----------------");

System.out.println("Student Id :"+sid);

System.out.println("Student name :"+sname);

System.out.println("Student Address:"+saddr);
System.out.println("CID CNAME CCOST");

System.out.println("----------------------");

for(int i=0;i<crs.length;i++){

Course c=crs[i];

System.out.println(c.cid+" "+c.cname+" "+c.ccost);

System.out.println();

}}

class ManyToManyEx{

public static void main(String[] args){

Course c1=new Course("C-111","C",500);

Course c2=new Course("C-222","C++",1000);

Course c3=new Course("C-333","JAVA",5000);

Course[] crs=new Course[3];

crs[0]=c1;

crs[1]=c2;

crs[2]=c3;

Student std1=new Student("S-111","AAA","Hyd",crs);

Student std2=new Student("S-222","BBB","Hyd",crs);

Student std3=new Student("S-333","CCC","Hyd",crs);

std1.getStudentDetails();

std2.getStudentDetails();

std3.getStudentDetails();

}}
Output:

Student Details

----------------------

Student Id :S-111

Student name :AAA

Student Address:Hyd

CID CNAME CCOST

------------------------------------

C-111 C 500

C-222 C++ 1000

C-333 JAVA 5000

Student Details

------------------------

Student Id :S-222

Student name:BBB

Student Address:Hyd

CID CNAME CCOST

------------------------------------

C-111 C 500

C-222 C++ 1000

C-333 JAVA 5000

Student Details

-----------------------

Student Id :S-333

Student name:CCC
Student Address:Hyd

CID CNAME CCOST

-----------------------------------

C-111 C 500

C-222 C++ 1000

C-333 JAVA 5000

Data Flow Diagram on Many-To-Many:


Uses a RelationShip:

This is a relationship between entities,where one entity will use another entity upto a
particular action or behaviour or method.

To provide USES-A Relationship in java applications,we have to declare contained Entity


class reference variable as parameter to a method in Container entity class,not as class
level variable.

If we declared contained entity reference variable as class level reference variable in


container entity class then that relationship is "HAS-A" relationship.

Example programme on Uses a RelationShip:

class Account{

String accno;

String accName;

String accType;

int bal=10000;

Account(String accNo,String accName,String accType){

this.accNo=accNo;

this.accName=accName;

this.accType=accType;

}}

class Transaction{

String tx_tid;

String tx_Type;

Transaction(String tx_id,String tx_Type){

this.tx_Id=tx_Id;

this.tx_Type=tx_Type;

public void deposit(Account acc,int dep_Amt){


int initial_Amt=acc.bal;

int total_Avl_Amt=initial_Amt+dep_Amt;

acc.bal=total_Avl_Amt;

System.out.println("Transaction Details");

System.out.println("--------------------");

System.out.println("Transaction Id :"+tx_Id);

System.out.println("Account Number :"+acc.accNo);

System.out.println("Account Type :"+acc.accType);

System.out.println("Initial Amount :"+initial_Amt);

System.out.println("Deposit Amount :"+dep_Amt);

System.out.println("Total Avl Amount :"+total_Avl_Amt);

System.out.println("Transaction Status:SUCCESS");

System.out.println("********THANKQ,VISIT AGAIN***********");

}}

class UsesAEx{

public static void main(String[] args){

Account acc=new Account("abc123","Durga","Savings");

Transaction tx=new Transaction("T-111","Deposit");

tx.deposit(acc,5000);

}}

Output:

Transaction Details

----------------------------

Transaction Id :T-111

Account Number :abc123

Account Type :Savings


Initial Amount :10000

Deposit Amount :5000

Total Avl Amount :15000

Transaction Status:SUCCESS

********THANKQ,VISIT AGAIN**********

Q)What is the difference between Aggregation and Composition?

Ans:In Object Orientation,both Aggregation and Composition are two level of associations
or representations of associations.

Where Aggregation is representing weak association that is less dependency but


composition is representing strong association that is more dependency.

In any Association,if contained object is existed even without container object,then


this association is called as Weak Association and it is representing Aggregation.

In any Association,if contained object is not existed without container object,then


this association is called as Strong Association and it is representing Composition.

Ex:

If we take an association between "Library" and "Students","Library" and "Books".

"Students" can exist without "Library",so that,the association between "Library" and
"Student" is Aggregation."Books" can not exist without "Library",so that,the association
between "Library" and "Books" is composition

In the case of Aggregation,the life of the contained Object is independent of the container
Object life.In the case of composition,the life of contained objects is depending on the
container object life that is same as container object life.
IS-A Relationship:

It is a relationship between entity classes,it will provide inheritance between entity


classes,where inheritance relationship will improve "code reusability" in Java application.

The process of getting variables and methods from one class to another class is called as
Inheritance.
At the basic level of Object Orientation,There are two types of inheritances at basic level of
Object orientation.

1.Single Inheritance

2.Multiple Inheritance

1.Single Inheritance:

The process of getting variables and methods from only one super class to one or more
no.of subclasses is called as Single Inheritance.

Java is able to allow Single Inheritance.

2.Multiple Inheritance:

The process of getting variables and methods from more than one super class to one or
more no.of sub classes is called as Multiple Inheritance.

Java is not allowing Multiple Inheritance.


On the basis of Single & Multiple,there are 3 more Inheritances.
1. Multi-Level Inheritance
2. Hierarchial Inheritance
3. Hybrid Inheritance

1. Multi-Level Inheritance :
It is a Combination of single inheritance in more than one level.
Java is able to allow multi-level inheritance.

2. Hierarchial Inheritance :
It is the combination of single inheritance in a particular structure.Java is able to allow
Hierarchical inheritance.
Ex: class A class B extends A class C extends A
{{{
---------- ----------- -----------
---------- ----------- -----------
}}}

class D extends B class E extends B


{{
----------- -----------
----------- -----------
}}

class F extends C class G extends C


{{
------------ ------------
------------ ------------
}}
3. Hybrid Inheritance :
It is the combination of single inheritance and multiple inheritance.Java is not
allowing Hybrid Inheritance.

Example programme for Single Inheritance:


class Employee
{
String eid;
String ename;
String eaddr;
public void getEmpDetails()
{
System.out.println("Employee Id :"+eid);
System.out.println("Employee name :"+ename);
System.out.println("Employee Address :"+eaddr);
}
}
class Manager extends Employee
{
Manager(String eid1,String ename1,String eaddr1)
{
eid=eid1;
ename=ename1;
ename=eaddr1;
}
public void getManagerDetails()
{
System.out.println("manager Details");
System.out.println("-----------------");
getEmpDetails();
}
}
class Accountant extends Employee
{
Accountant (String eid1,String ename1,String eaddr1)
{
eid=eid1;
ename=ename1;
eaddr=eaddr1;
}
public void getAccountantDetails()
{
System.out.println("Accountant Details");
System.out.println("--------------------");
getEmpDetails():
}
}
class InheritanceEx
{
public static void main(String[] args)
{
Manager m=new Manager("E-111","AAA","Hyd");
m.get ManagerDetails();
System.out.println();
Accountant acc=new Accountant("E-222","BBB","Hyd");
acc.getAccountantDetails();
}
}

On Command Prompt:
==================
D:\java7>javac Inheritance Ex.java
D:\java7>java Inheritance Ex

Manager Details:
==============
Employee Id :E-111
Employee Name :AAA
Employee Address :Hyd

Accountant Details:
===============
Employee Id :E-222
Employee Name :BBB
Employee Address :Hyd
Static Context in Inheritance:

 In the case of inheritance,if we create an object for sub class then JVM has to
execute sub class constructor,before executing sub class constructor,JVM has to
check whether sub class bytecode is loaded already in the memory or not,if not,JVM
has to load subclass bytecode to the memory.
 In this context,before loading sub class bytecode to the memory,first,JVM has to load
the respective super class bytecode to the memory.
 Therefore,in the case of inheritance,JVM will load all the classes bytecode right from
super class to sub class.
 If we provide static context in both super class and subclass then JVM will recognize
and execute static context of the respective classes at the time of loading the
respective classes.

Example programme on static Context Inheritance:

class A{

static{

System.out.println("SB-A");

}}

class B extends A{

static{

System.out.println("B-con");

}}

class C extends B{

static{

System.out.println("SB-C");

}}

class Test{

public static void main(String[] args){

C c=new C();

}}
Ouput:

SB-A

B-con

SB-C

==========================

class A{

static{

System.out.println("SB-A");

static int m1(){

System.out.println("m1-A");

return 10;

static int i=m1();

class B extends A{

static int j=m2();

static{

System.out.println("SB-B");

static int m2(){

System.out.println("m2-B");

return 20;

}}

class C extends B{

static int m3(){


System.out.println("m3-C");

return 30;

static int k=m3();

static{

System.out.println("SB-C");

}}

class Test{

public static void main(String[] args){

C c1=new C();

C c2=new C();

}}

O/P:SB-A

m1-A

m2-B

SB-B

m3-C

SB-C

Instance Context in Inheritance:

 In the case of Inheritance,if we create object for sub class then JVM has to execute
sub class constructor,but before executing sub class constructor JVM has to execute
0-argument constructor in the respective super class.

Example programmes on Instance Context in Inheritance:

class A{

A(){

System.out.println("A-con");
}}

class B extends A{

B(){

System.out.println("B-con");

}}

class C extends B{

C(){

System.out.println("C-con");

}}

class Test{

public static void main(String[] args){

C c=new C();

}}

O/P:A-Con

B-Con

C-Con

===============================

class A{

A(){

System.out.println("A-con");

}}

class B extends A{

class C extends B{

C(){

System.out.println("C-con");

}}
class Test{

public static void main(String[] args){

C c=new C();

}}

O/P:A-Con

C-Con

=============================

class A{

A(int i){

System.out.println("A-int-param-con");

}}

class B extends A{

B(int i){

System.out.println("B-int-param-con");

}}

class C extends B{

C(int i){

System.out.println("C-int-param-con");

}}

class Test{

public static void main(String[] args){

C c=new C(10);

}}

Status:Compilation Error

Reason:In case of Inheritance,super classes must have 0-argument constructors


irrespective of the sub class constructors.
 In the case of Inheritance,if we provide instance context at all the classes then JVM
will recognize and execute them just before executing the respective class
constructors.

class A{

A(){

System.out.println("A-con");

int i=m1();

int m1(){

System.out.println("m1-A");

return 10;

System.out.println("IB-A");

}}

class B extends A{

int j=m2();

int m2(){

System.out.println("m2-B");

return 20;

System.out.println("IB-B");

}
B(){

System.out.println("B-Con");

}}

class C extends B{

C(){

System.out.println("C-con");

System.out.println("IB-C");

int k=m3();

int m3(){

System.out.println("m3-C");

return 30;

}}

class Test{

public static void main(String args[]){

C c=new C();

}}

Ouput:

m1-A

IB-A

A-con

m2-B

IB-B

B-Con

IB-C
m3-C

c-con

class A{

A(){

System.out.println("A-con");

static{

System.out.println("SB-A");

int m1(){

System.out.println("m1-A");

return 10;

static int m2(){

System.out.println("m2-A");

return 20;

System.out.println("IB-A");

static int i=m2();

int j=m1();

class B extends A{

System.out.println("IB-B");
}

int m3(){

System.out.println("m3-B");

return 30;

static{

System.out.println("SB-B");

int k=m3();

B(){

System.out.println("B-Con");

static int l=m4();

static int m4(){

System.out.println("m4-B");

return 40;

}}

class C extends B{

static int m5(){

System.out.println("m5-C");

return 50;

int m6(){

System.out.println("m6-C");

return 60;

}
C(){

System.out.println("C-con");

int m6();

static int n=m5();{

System.out.println("IB-C");

static{

System.out.println("SB-C");

class Test{

public static void main(String args[]){

C c1=new C();

C c2=new C();

}}

O/P: SB-A A-con m1-A

m2-A IB-B A-con

SB-B m3-B IB-B

m4-B B-con m3-B

m5-C m6-C B-con

SB-C IB-C m6-C

IB-A C-con IB-C

m1-A IB-A C-con


Super Keyword:

 Super is a Java keyword,it can be used to represent super class object from sub
classes.

There are three ways to utilize "super" keyword.

1.To refer super class variables

2.To refer super class constructors

3.To refer super class methods.

1.To refer super class variables:

 If we want to refer super class variables,by using 'super' keyword then we have to
use the following syntax.

super.var_Name;

NOTE:We will utilize super keyword,to access super class variables when we
have same set of variables at local,at current class and at the super class.

Example programme,To refer super class variables:

class A{

int i=100;

int j=200;

class B extends A{

int i=10;

int j=20;

B(int i,int j){

System.out.println(i+" "+j);

System.out.println(this.i+" "+this.j);

System.out.println(super.i+" "+super.i);

}}
class Test{

public static void main(String args[]){

B b=new B(50,60);

}}

Output:

50 60

10 20

100 100

2.To refer super class constructors:

 If we want to refer super class constructor from sub class by using 'super' keyword
then we have to use the following syntax.

super([Param_List]);

NOTE:In general,in inheritance,JVM will execute 0-argument constructor


before executing sub class constructor.In this context,instead of executing
0-argument constructor we want to execute a parametrized constructor at
super class,for this,we have to use 'super' keyword.

Example programme,To refer super class constructors:

class A{

A(){

System.out.println("A-Con");

A(int i){

System.out.println("A-int-param-Con");

}}

class B extends A{
B(){

super(10);

System.out.println("B-Con");

}}

class Test{

public static void main(String args[]){

B b=new B();

}}

Output:

A-int-param-Con

B-Con

 If we want to access super class constructor from subclass by using "super" keyword
then the respective "super" statement must be provided as first statement.
 If we want to access super class constructor from sub class by using "super"
keyword then the respective "super" statement must be provided in the subclass
constructors only,not in subclass normal Java methods.
 If we violate any of the above conditions then compiler will rise an error like "call to
super must be first statement in constructor".

NOTE:Due to the above rules and regulations,it is not possible to access more
than one super class constructor from a single sub class constructor by using
"super" keyword.

 In the case of inheritance, when we access sub class constructor then JVM will
execute super class 0-arg constructor then sub class constructor, this flow of
execution is possible in Java because of the following compiler actions over source
code at the time of compilation.

a)Compiler will goto each and every class available in the source file and checks
whether any requirement to provide "default constructors".

b)If any class is identified with out user defined constructor explicitly then compiler
will add a 0-argument constructor as default constructor.

c)After providing default constructors,compiler will goto all the constructors at each
and every class and compiler will check "super" statement is provided or not by the
developer explicitly to access super class constructor.
d)If any class constructor is identified with out "super" statement explicitly then
compiler will append "super()" statement in the respective constructor to access a 0-
argument constructor in the respective super class.

e)With the above compiler actions,JVM will execute super class 0-arg constructor as
part of executing sub class constructor explicitly.

Write the translated code:

class A{

A(){

System.out.println("A-con");

}}

class B extends A{

B(int i){

System.out.println("B-int-param-con");

}}
class C extends B{

C(int i){

System.out.println("C-int-param-con");

}}

class Test{

public static void main(String args[]){

C c=new C();

}}

Status:Compilation Error

=========================

class A{

A(){

System.out.println("A-con");

}}

class B extends A{

B(int i){

System.out.println("B-int-param-con");

}}

class C extends B{

C(int i){

super(10);

System.out.println("C-int-param-con");

}}

class Test{

public static void main(String args[]){

C c=new C(10);

}}
Output:

A-con

B-int-param-con

C-int-param-con

3.To refer super class method:

 If we want to refer super class methods from sub class by using "super" keyword
then we have to use the following syntax.

super.method_Name([Param_List]);

NOTE:In Java applications,when we have same method at both subclass and


at super class,if we access that method at sub class then JVM will execute
sub class method only,not super class method because JVM will give more
priority for the local class methods.In this context,if we want to refer super
class method over sub class method then we have to "super" keyword.

Example Programme to refer super class method:

class A{

void m1(){

System.out.println("m1-A");

}}

class B extends A{

void m2(){

System.out.println("m2-B");

m1();

this.m1();

super.m1();

}}

void m1(){

System.out.println("m1-B");

}}

class Test{
public static void main(String args[]){

B b=new B();

b.m2();

}}

Class Level Type Casting:

 The process of converting the data from one user defined data type to another user
defined data type is called as User Defined Data type casting or Class level type
Casting.
 If we want to perform Class Level Type Casting or User Defined data types casting
then we must require either "extends" or "implements" relationship between two
user defined data types.

There are two types of User defined data type casting:

1.UpCasting.

2.DownCasting.

1.UpCasting:

 The process of converting the data from sub type to super type is called as
UpCasting.
 To perform Upcasting,we have to assign sub class reference variable to super class
reference variable.
Ex:

class A{

class B extends A{

B b=new B();

A a=b;

 If we compile the above code then compiler will check whether 'b' variable data type
is compatible with 'a' variable data type or not,if not,compiler will rise an error like
"InCompatible Types".If "b" variable data type id compatible to "a" variable data
type then compiler will not rise any error.

NOTE:In Java applications,always sub class types are compatible with super
class types,so that we can assign sub class reference variable to super class
reference variables directly.

NOTE:In Java,super class types are not compatible with sub class types,so
that,we cannot assign super class reference variables to sub class reference
variables directly,where if we want to assign super class reference variables to
sub class reference variables then we must require "cast operator"
explicitly,that is called as "Explicit Type Casting".

If we execute the above code then JVM will perform the following two actions.

1.JVM will convert "b" variable data type[sub class type] to "a" variable data type[Super
class type] implicitly.

2.JVM will copy the reference value of "b" variable to "a" variable.

With the upcasting,we are able to access only super class members among the
availability of both super class and sub class members in sub class object.

class A{

void m1(){

System.out.println("m1-A");
}}

class B extends A{

void m2(){

System.out.println("m2-B");

}}

class Test{

public static void main(String[] args){

B b=new B();

b.m1();

b.m2();

A a=b;

a.m1();

//a.m2();---->error

}}

Output:

m1-A

m2-B

m1-A

2.DownCasting:

 The process of converting the data from super type to sub type is called as
"DownCasting".

If we want to perform DownCasting then we have to use the following format.


class A{

void m1(){

System.out.println("m1-A");

}}

class B extends A{

void m2(){
System.out.println("m2-B");

}}

class Test{

public static void main(String args[]){

case 1:

A a=new A();

B b=a;

Status:Compilation error,incompatible types

Reason:In Java,always,subclass types are compatible with super class types but
super class types are not compatible with sub class types.It is possible to assign sub
class reference variables directly but it is not possible to assign super class reference
variable to sub class reference variables directly,if we assign then compiler will rise
an error like "InCompatible Types error".

Case 2:

A a=new A();

B b=(B)a;

Status:No Compilation error,but classCastException

Reason:In Java,always,it is possible to keep subclass object reference value


in super class reference variable but it is not possible to keep superclass object
reference value in subclass reference variable.If we are trying to keep super class
object reference value in sub class reference variable then JVM will rise an exception
like "java.lang.classCastException".

Case 3:

A a=new B();

B b=(B)a;

Status:No compilation error,no exception

b.m1();

b.m2();
Ex1:

A a=new A();

B b=a;

Status:Compilation error,incompatible types

Ex2:

A a=new A();

B b=(B)a;

Status:No Compilation error,ClassCastException

Ex3:

A a=new A();

B b=(B)a;

Status:No Compilation error,No Exception


Ex4:

A a=new C();

B b=(C)a;

Status:No Compilation error,No Exception

Ex5:

A a=new B();

B b=(C)a;

Status:No Compilation Error;ClassCastException

Ex6:

A a=new C();

C c=(D)a;

Status:No Compilation Error,ClassCastException

Ex7:

B b=new D();

C c=(D)b;

Status:NO Compilation Error,No Exception

Ex8:

A a=new D();

D d=(D)(C)(B)a;

Status:No Compilation error,No Exception

Ex9:

A a=new C();

D d=(D)(C)(B)a;

Status:No Compilation Error,ClassCastException


Ex10:

A a=new C();

C c=(D)(C)(B)a;

Status:No Compilation Error,ClassCastException

Polymorphism:

Polymorphism is a Greek word,where poly means many and morphism means Structures.

If one thing is existed in more than one form then it is called as Polymorphism.

There are two types of Polymorphisms

1.Static Polymorphism or Early binding

2.Dynamic Polymorphism or Late Binding

1.Static Polymorphism:

If the Polymorphism is existed at compilation time then that Polymorphism is called as


Static Polymorphism.

Ex:Method Overloading

2. Dynamic Polymorphism:

If the Polymorphism is existed at runtime then that Polymorphism is called as Dynamic


Polymorphism

Ex:Method Overriding.

Method Overloading:

The process of extending the existed method functionality upto some new Functionality is
called as Method Overloading.

If we declare more than one method with the same name and with the different parameter
list is called as Method Overloading.

To perform method overloading, we have to declare more than one method with different
method signatures that is same method name and different parameter list.
Example Program me on Method Overloading:

class A{

void add(int i,int j){

System.out.println(i+j);

void add(float f1,float f2){

System.out.println(f1+f2);

void add(String str1,String str2){

System.out.println(str1+str2);

}}

class Test{

public static void main(String[] args){

A a=new A();

a.add(10,20);

a.add(22.22f,33.33f);

a.add(“abc”,”def”);

}}

Output:

30

55.550003

abcdef

class Employee{

void gen_Salary(int basic,float hk,float pf,int ta){

float salary=basic+((basic*hk)/100)-((basic*pf)/100)+ta);

System.out.println("Salary :"+salary);
}

void gen_Salary(int basic,float hk,float pf,int ta,int bonus){

float salary=basic+((basic*hk)/100)-((basic*pf)/100)+ta)+bonus;

System.out.println("Salary :"+salary);

}}

class Test{

public static void main(String[] args){

Employee e=new Employee();

e.gen_Salary(20000,25.of,12.0f,2000);

e.gen_Salary(20000,25.of,12.0f,2000,5000);

}}

Method Overriding:

The process of replacing existed method functionality with some new functionality is called
as Method Overriding.

To perform Method Overriding, we must have inheritance relationship classes.

In Java applications, we will override super class method with sub class method.

In Java applications,we will override super class method with subclass method.

If we want to override super class method with sub class method then both super class
method and sub class method must have same method prototype.

Steps to perform Method Overriding:

1.Declare a super class with a method.

2.Declare a sub class and provide the same super class method with different
implementation.

3.In main class,in main() method,prepare object for sub class and prepare reference
variable for super class[UpCasting].

4.Access super class method then we will get output from sub class method.
Example Programme on Mehhod Overriding:

class Loan{

public float getIR(){

return 7.0f;

class GoldLoan extends Loan{

public float getIR(){

return 10.5f;

class StudyLoan extends Loan{

public float getIR(){

return 12.0f;

}}

class CraftLoan extends Loan{

class Test{

public static void main(String[] args){

Loan gold_Loan=new GoldLoan();

System.out.println("Gold Loan IR :"+gold_Loan.getIR()+"%");

Loan study_Loan=new StudyLoan();

System.out.println("Study Loan IR :"+study_Loan.getIR()+"%");

Loan craft_Loan=new CraftLoan();

System.out.println("Craft Loan IR :"+craft_Loan.getIR()+"%");

}}
NOTE: To prove method overriding in Java, we have to access super class method
but JVM will execute the respective sub class method and JVM has to provide
output from the respective sub class method, not form super class method. To
achieve the above requirement we must create reference variable for only super
class and we must create object for sub class.

class A{

void m1(){

System.out.println("m1-A");

}}

class B extends A{

void m1(){

System.out.println("m1-B");

}}

class Test{

public static void main(String args[]){

/* A a=new A();

a.m1();

Status:Here Method Overriding is not happend,because Mehtod overriding must require


sub class

object,not super class object.

*/

/*

B b=new B();

b.m1();

Status:Here method Overriding is happened,but,to prove method overriding we must


require super class reference variable,not sub class reference variable,because,subclass
reference variable is able to access only sub class method when we have the same method
in both sub class and super class.

*/
A a=new B();

a.m1();

}}

Rules to perform Method Overriding:

1.To override super class method with sub class then super class method must not be
declared as private.

Ex:

class A{

private void m1(){

System.out.println("m1-A");

}}

class B extends A{

void m1(){

System.ou.println("m1-B");

}}

class Test{

public static void main(String args[]){

A a=new A();

a.m1();

}}

2.To override super class method with sub class method then sub class method should have
the same return type of the super class method.

Ex:

class A{

int m1(){

System.ou.println("m1-A");

return 10;
}}

class B extends A{

void m1(){

System.out.println("m1-B");

}}

class Test{

public static void main(String args[]){

A a=new B();

a.m1();

}}

3.To override super class method with sub class method then super class method must not
be declared as final sub class method may or may not be final.

Ex:

class A{

void m1(){

System.out.println("m1-A");

}}

class B extends A{

final void m1(){

System.out.println("m1-B");

}}

class Test{

public static void main(String[] args){

A a=new B();

a.m1();

}}
4.To override superclass method with sub class method either super class method or
subclass method as static then compiler will rise an error.If we declare both super and sub
class method as static in method overriding compiler will not rise any error,JVM will provide
output from the super class method.

NOTE:If we are trying to override superclass static method with sub class static method
then super class static method will override subclass static method,where JVM will generate
output from super class static method.

Example:

class A{

static void m1(){

System.out.println("m1-A");

}}

class B extends A{

static void m1(){

System.out.println("m1-B");

}}

class Test{

public static void main(String args[]){

A a=new B();

a.m1();

}}

5.To override super class method with subclass method,sub class method must have either
same scope of the super class method or more scope when compared with super class
method scope otherwise compiler will rise an error.

Ex:

class A{

protected void m1(){

System.out.println("m1-A");

}}
class B extends A{

public void m1(){

System.out.println("m1-B");

}}

class Test{

public static void main(String args[]){

A a=new A();

a.m1();

}}

6.To override super class method with subclass method subclass method should have either
same access privileges or weaker access privileges when compared with super class method
access privileges.

Q)What are the differences between method overloading and method overriding?

Ans:

Method Overloading Method Overriding

1. The process of extending the existed The process of replacing existed method
method functionality with new functionality functionality with new functionality is called
is called as Method Overloading. as Method Overriding
2.In the case of method overloading, In the case of method overriding same
different method signatures must be method prototypes must be provided to the
provided to the methods methods.
3.With or without inheritance we can With inheritance only we can perform
perform method overloading Method overriding

Consider the following programme:

class DB_Driver{

public void getDriver(){

System.out.println("Type-1 Driver");

}}

class New_DB_Driver extends DB_Driver{


public void getDriver(){

System.out.println("Type-4-Driver");

}}

class Test{

public static void main(String args[]){

DB_Driver driver=new New_DB_Driver();

driver.getDriver();

}}

In the above example, method overriding is implemented, in method overriding, for super
class method call JVM has to execute subclass method, not super class method. In method
overriding, always JVM is executing only subclass method, not super class method. In
method overriding, it is not suggestible to manage super class method body without
execution, so that, we have to remove super class method body as part of code
optimization. In Java applications, if we want to declare a method without body then we
must declare that method as "Abstract Method".

If we want to declare abstract methods then the respective class must be abstract class.

abstract class DB_Driver{

public abstract void getDriver();

class New_DB_Driver extends DB_Driver{

public void getDriver(){

System.out.println("Type-4 Driver");

}}

class Test{

public static void main(String args[]){

DB_Driver driver=new New_DB_Driver();

driver.getDriver();

}}
In Java applications, if we declare any abstract class with abstract methods, then it is
convention to implement all the abstract methods by taking sub class.

To access the abstract class members, we have to create object for subclass and we have to
create reference variable either for abstract class or for subclass.

If we create reference variable for abstract class then we are able to access only abstract
class members, we are unable to access subclass own members

If we declare reference variable for subclass then we are able to access both abstract class
members and subclass members.

abstract class A{

void m1(){

System.out.println("m1-A");

abstract void m2();

abstract void m3();

class B extends A{

void m2(){

System.out.println("m2-B");

void m3(){

System.out.println("m3-B");

void m4(){

System.out.println("m4-B");

}}

class Test{

public static void main(String args[]){

A a=new B();

a.m1();
a.m2();

a.m3();

//a.m4();---error

B b=new B();

b.m1();

b.m2();

b.m3();

b.m4();

}}

In Java applications,it is not possible to create Object fro abstract classes but it possible to
provide constructors in abstract classes,because,to recognize abstract class instance
variables in order to store in the sub class objects.

abstract class A{

A(){

System.out.println("A-Con");

}}

class B extends A{

B(){

System.out.println("B-Con");

}}

class Test{

public static void main(String[] args){

B b=new B();

}}

In Java applications, if we declare any abstract class with abstract methods then it is
mandatory to implement all the abstract methods in the respective subclass. If we
implement only some of the abstract methods in the respective subclass then compiler will
rise an error, where to come out from compilation error we have to declare the respective
subclass as an abstract class and we have to provide implementation for the remaining
abstract methods by taking another subclass in multilevel inheritance.
abstract class A{

abstract void m1();

abstract void m2();

abstract void m3();

abstract class B extends A{

void m1(){

System.out.println("m1-A");

}}

class C extends B{

void m2(){

System.out.println("m2-C");

void m3(){

System.out.println("m3-C");

}}

class Test{

public static void main(String[] args){

A a=new C();

a.m1();

a.m2();

a.m3();

}}
In Java applications, if we want to declare an abstract class then it is not at all mandatory
condition to have atleast one abstract method, it is possible to declare abstract class
without having abstract methods but if we want to declare a method as an abstract method
then the respective class must be abstract class.

abstract class A{

void m1(){

System.out.println("m1-A");

}}

class B extends A{

void m2(){

System.out.println("m2-B");

}}

class Test{

public static void main(String args[]){

A a=new B();

a.m1();

//a.m2();---------->Error

B b=new B();

b.m1();

b.m2();

}}

In Java applications, it is possible to extends an abstract class to concrete class and from
concrete class to abstract class.

class A{

void m1(){

System.out.println("m1-A");

}}
abstract class B extends A{

abstract void m2();

class C extends B{

void m2(){

System.out.println("m2-C");

void m3(){

System.out.println("m3-C");

}}

class Test{

public static void main(String args[]){

A a=new C();

a.m1();

//a.m2();---error

//a.m3();---error

B b=new C();

b.m1();

b.m2();

//b.m3();---error

C c=new C();

c.m1();

c.m2();

c.m3();

}}
Note: In Java applications, it is not possible to extend a class to the same class, if we do the
same then compiler will rise an error like "cyclic inheritance involving".

class A extends A{

Status: Compilation Error: “cyclic inheritance involving".

class A extends B{

class B extends A{

Status: Compilation Error: “cyclic inheritance involving".

Interfaces:

Interface is a Java Feature, it will allow only abstract methods.

In Java applications, for interfaces, we are able to create only reference variables, we are
unable to create objects.

In the case of interfaces, by default, all the variables are "public static final".

In the case of interfaces, by default, all the methods are "public and abstract".

In Java applications, constructors are possible in classes and abstract classes but
constructors are not possible in interfaces.

Interfaces will provide more sharability in Java applications when compared with classes and
abstract classes.

In Java applications, if we declare any interface with abstract methods then it is convention
to declare an implementation class for the interface and it is convention to provide
implementation for all the abstract methods in implementation class.

Interface I{

void m1();

void m2();

void m3();

}
class A implements I{

public void m1(){

System.out.println("m1-A");

public void m2(){

System.out.println("m2-A");

public void m3(){

System.out.println("m3-A");

}}

public void m4(){

System.out.println("m4-A");

}}

class Test{

public static void main(String args[]){

I i=new A();

i.m1();

i.m2();

i.m3();

//i.m4();------>error

A a=new A();

a.m1();

a.m2();

a.m3();

a.m4();

}}
In Java applications, if we declare an interface with abstract methods then it is mandatory
to provide implementation for all the abstract methods in the respective implementation
class. In this context if we provide implementation for some of the abstract methods at the
respective implementation class then compiler will rise an error, where to come out from
the compilation error we have to declare the respective implementation class as an abstract
class and we have to provide implementation for the remaining abstract methods by taking
a sub class for the abstract class.

interface I{

void m1();

void m2();

void m3();

abstract class A implements I{

public void m1(){

System.out.println("m1-A");

}}

class B extends A{

public void m2(){

System.out.println("m2-B");

public void m3(){

System.out.println("m3-B");

}}

class Test{

public static void main(String args[]){

I i=new I();

i.m1();

i.m2();

i.m3();
A a=new B();

a.m1();

a.m2();

a.m3();

B b=new B();

b.m1();

b.m2();

b.m3();

}}

In Java applications, it is not possible to extend more than one class to a single class but it
is possible to extend more than one interface to a single interface.

interface I1{

void m1();

interface I2{

void m2();

interface I3 extends I1,I2{

void m3();

class A implements I3{

public void m1(){

System.out.println("m1-A");

}
public void m2(){

System.out.println("m2-A");

public void m3(){

System.out.println("m3-A");

}}

class Test{

public static void main(String args[]){

I1 i1=new A();

i1.m1();

I2 i2=new A();

i2.m2();

I3 i3=new A();

i3.m1();

i3.m2();

i3.m3();

A a=new A();

a.m1();

a.m2();

a.m3();

}}

In Java applications, it is possible to implement more than one interface into a single
implementation class.

interface I1{

void m1();

}
interface I2{

void m2();

interface I3{

void m3();

class A implements I1,I2,I3{

public void m1(){

System.out.println("m1-A");

public void m2(){

System.out.println("m2-A");

public void m3(){

System.out.println("m3-A");

}}

class Test{

public static void main(String args[]){

I1 i1=new A();

i1.m1();

I2 i2=new A();

i2.m2();

I3 i3=new A();

i3.m3();

A a=new A();

a.m1();

a.m2();
a.m3();

}}

Marker Interface is an Interface, it will not include any abstract method and it will provide
some abilities to the objects at runtime of our Java application.

Ex: java.io.Serializable

The process of separating the data from an object is called as Serialization.

The process of reconstructing an Object on the basis of data is called as Deserialization.

Serialization & Deserialization

Where java.io.Serializable interface is a marker interface, it was not declared any method
but it will make eligible any object for Serialization and Deserialization.

Valid Syntaxes between classes,abstract classes and Interfaces:

class extends class --->Valid

class extends class,class--->InValid

class extends abstract class--->Valid

class extends abstract class,class--->InValid

class extends abstract class,abstract class--->InValid

class extends interface--->InValid

class implements interface--->Valid

class implements interface,interface--->Valid

class implements interface extends class--->InValid


class implements interface extends abstract class--->InValid

class extends class implements interface--->Valid

class extends abstract class implements interface--->Valid

abstract class extends class--->Valid

abstract class extends abstract class--->Valid

abstract class extends class,class--->InValid

abstract class extends abstract class,abstract class--->InValid

abstract class extends class,abstract class--->InValid

abstract class extends interface--->InValid

abstract class implements interface--->Valid

abstract class implements interface,interface--->Valid

abstract class extends class implements interface--->Valid

abstract class extends abstract class implements interface--->Valid

abstract class implements interface extends class-->InValid

abstract class implements interface extends abstract class-->InValid

interface extends interface -->Valid

interface extends interface,interface -->Valid

interface extends class -->InValid

interface extends abstract class -->InValid

interface implements interface -->InValid


JAVA8 Features over Interfaces:

1.Default Methods in Interfaces

2.Static Methods in Interfaces

3.Functional Interfaces

1.Default Methods in Interfaces:

In general, if we declare abstract methods in an interface then we have to implement all


that interface methods in more no.of classes with variable implementation part.

In the above context, if we require any method implementation common to every


implementation class with fixed implementation then we have to implement that method in
the interface as default method.

To declare default methods in interfaces we have to use "default" keyword in method syntax
like access modifier.

Ex:

interface I{

default void m1(){

System.out.println("m1-A");

}}

class A implements I{}

class Test{

public static void main(String args[]){

I i=new A();

i.m1();

}}

NOTE:It is possible to provide more than one default methods with in a single
interface.
Ex:

interface I{

default void m1(){

---------

default void m2(){

--------

}}

1.In JAVA8,it is possible to override default methods in the implementation classes.

interface I{

default void m1(){

System.out.println("m1-A");

}}

class A implements I{

public void m1(){

System.out.println("m1-A");

}}

class Test{

public static void main(String args[]){

I i=new A();

i.m1();

}}
2.Static Methods in Interfaces:

Upto JAVA7 version, static methods are not possible in interfaces but from JAVA8 version
static methods are possible in interfaces in order to improve sharability.

If we declare static methods in the interfaces then it is not required to declare any
implementation class to access that static method,we can use directly interface name to
access static method.

NOTE:If we declare static methods in an interface then they will not be available to the
respective implementation classes,we have to access static methods by using only interface
names not even by using interface reference variable

interface I{

static void m1(){

System.out.println("m1-1");

}}

class Test{

public static void main(String args[]){

I.m1();

}}

Note:In JAVA8 version, interfaces will allow concrete methods along with either "static"
keyword or "default" keyword.

3.Functional Interface:

If any Java interface allows only one abstract method then it is called as "Functional
Interface".

To make any interface as Functional Interface then we have to use the following annotation
just above of the interface.

@FunctionalInterface

Ex: java.lang.Runnable

java.lang.Comparable

NOTE:In Functional Interfaces we have to provide only one abstract method but
we can provide any no.of default methods and any no.of static methods.
@Functional Interface

interface I{

void m1();

//void m2();---->error

default void m3(){

System.out.println("m3-I");

static void m4(){

System.out.println("m4-I");

class A implements I{

public void m1(){

System.out.println("m1-A");

}}

class Test{

public static void main(String args[]){

I i=new A();

i.m1();

i.m3();

//i.m4();--->error

I.m4();

//A.m4();--->error

}}
instanceof operator:

It is a boolean operator,it can be used to check whether the specified reference variable is
representing the specified class object or not that is compatible or not.

ref_Var instanceof Class_Name

where ref_Var and Class_Name must be related otherwise compiler will rise an error like
"incompatible types error".

If ref_Var class is same as the specified Class_Name then instanceof operator will return
"true".

If ref_Var class is subclass to the specified Class_Name then instanceof operator will return
"true".

If ref_Var class is super class to the specified Class_Name then instanceof operator will
return "false".

class A{

class B extends A{

class C{

class Test{

public static void main(String args[]){

A a new A();

B b=new B();

System.out.println(a instanceof A);

System.out.println(a instanceof B);

System.out.println(b instanceof A);

//System.out.println(a instanceof C);

}}
Object Cloning:

The process of creating duplicate object for an existed object is called as Object Cloning.

If we want to perform Object Cloning in Java application then we have to use the following
steps.

1.Declare an User defined Class.

2.Implement java.lang.Cloneable interface inorder to make eligible any object for cloning.

3.Override Object class clone() method in user defined class.

public Object clone() throws CloneNotSupportedException

4.In Main class,in main() method,access clone() method over the respective object.

class Student implements Cloneable{

String sid;

String sname;

String saddr;

Student(String sid,String sname,String saddr){

this.sid=sid;

this.sname=sname;

this.saddr=saddr;

public Object clone()throws CloneNotSupportedException{

return super.clone();

public String toString(){

System.out.println("Student details");

System.out.println("----------------");

System.out.println("Student Id :"+sid);
System.out.println("Student name:"+sname);

System.out.println("Student Address:"+saddr);

return "";

}}

class Test{

public static void main(String args[]){

Student std1=new Student("S-111","Durga","Hyd");

System.out.println("Student Details Before Cloning");

System.out.println(std1);

Student std2=(Student)std1.clone();

System.out.println();

System.out.println("Student Details After cloning");

System.out.println(std2);

}}

There are two types clonings in Java:

1.Shallow Cloning/Shallow Copy

2.Deep Cloning/Deep Copy

1.Shallow Cloning/Shallow Copy:

In this cloning mechanism,while cloning an object if any associated object is encountered


then JVM will not duplicate associated object along with data duplication,where duplicated
object is also refer the same associated object which was refereed by original object.

NOTE:Shallow Cloning is default cloning mechanism in Java.


Deep Cloning/Deep Copy:

In this cloning mechanism,while cloning an object if JVM encounter any associated object
then JVM will duplicate associated object also along with data duplication.In this cloning
mechanism,both original object and cloned object are having their own duplicated
associated objects copy,both are not referring a single associated object
class Account{

String accNo;

String accName;

String accType;

Account(String accNo,String accName,String accType){

this.accNo=accNo;

this.accName=accName;

this.accType=accType;

}}

class Employee implements Cloneable{

String eid;

String ename;

String eddr;

Account acc;

Employee(String eid,String ename,String eaddr,Account acc){

this.eid=eid;

this.ename=ename;

this.eaddr=eaddr;

this.acc=acc;

public Object clone() throws CloneNotSuppoertException{

return super.clone();

public String toString(){

System.out.println("Employee Details");

System.out.println("-----------------");

System.out.println("Employee Id :"+eid);
System.out.println("Employee Address :"+eaddr);

System.out.println("Employee Name :"+ename);

System.out.println("Account Deatails");

System.out.println("----------------");

System.out.println("Account Number:"+acc.accNo);

System.out.println("Account Name :"+acc.accName);

System.out.println("Account Type :"+acc.accType);

System.out.println("Account Reference: "+acc);

return "";

}}

class Test{

public static void main(String args[]) throws Exception{

Account acc=new Account("abc123","Durga","Savings");

Employee emp1=new Employee("E-111","Durga","Hyd",acc);

System.out.println("Employee Details Before Cloning");

System.out.println(emp1);

Employee emp2=(Employee)emp1.clone();

System.out.println("Employee Details After Cloning");

System.out.println(emp2);

}}

To prepare example for deep cloning provide the following clone() method in employee class
in the above example of(shallow Cloning)

public Object clone()throws CloneNotSupportedException{

Account acc1=new Account(acc.accNo,acc.accName,acc.accType);

Employee emp=new Employee(eid,ename,eaddr,acc1);

return emp;

}
Exception Handling:

What is the difference between Error and Exception?

Error Exception

1. Error is a problem at runtime, for Exception is a problem, for which, we


which we are unable to provide are able to provide solution
solutions programmatically. programmatically.

Ex: JVM internal Problem Ex: ArithmeticException


StackOverFlowError NullPointerException
InSufficientMainMemory ArrayIndexOutOfBoundsException

Definition of Exception:

Exception is an Unexpected event occurred at runtime provided by the users


while entering dynamic input to the Java program, provided by the database
while executing sql queries in JDBC applications or provided by the remote
machine while establish connection between local machine and remote
machine in distributed applications causes abnormal termination to the Java
programs.

In Java applications, exceptions may provide abnormal terminations to the


Java programs, these abnormal terminations may effect operating system,
network applications.....

To overcome the above problems, we have to provide smooth terminations


to the Java applications, for this, we have to handle the exceptions properly,
for this, we have to use "Exception Handling Mechanisms".

Note: Terminating Java program in the middle is called as Abnormal


Termination, terminating Java program at the end is called as
Smooth Termination.
Java is Robust programming language, because,

1.Java is having very good memory management system in the form of


Heap memory Management System, a dynamic memory management
system, which allocated and deallocated memory for the objects at runtime
as per the JVM requirement.

2.Java is having very good Exception handling mechanisms due to the


availability of very good predefined library to represent each and every
exceptional situation.

There are two types of exceptions in Java:

1.Predefined Exceptions

2.UserDefined Exceptions

1.Predefined Exceptions:

These Exceptions are defined by Java programming language along with


Java predefined library.

There are two types of predefined exceptions:

1. Checked Exceptions

2. Unchecked Exceptions
Q)What is the difference between checked Exception and Unchecked
Exception?

1.Checked Exception is an exception identified by the compiler at


compilation time[occurred at runtime, not at compilation time].

NOTE:while Java program compilations, compiler will recognize


same situations to get exceptions at runtime then that exceptions
are called as Checked Exceptions.

Unchecked exceptions are the exceptions recognized by the JVM at runtime,


not a compiler at compilation time.

2.Runtime Exceptions and its subclasses, error and its subclasses are treated
as Unchecked exceptions and the remaining exception classes are treated as
checked exception.

There are two types of checked exceptions:

a)pure checked exceptions

b)partially checked exceptions.

Q)What is the difference between pure checked and partially checked


exceptions?

If any checked exception is having only checked exceptions are child classes
then that checked exceptions are called as "pure checked exceptions".

Ex:IOException

If any checked exception is having atleast one unchecked exception as a


child class then that checked exception is called as "partially Unchecked
exception"

Ex:Exception,Throwable
Review of Predefined Exceptions:

1.Arithmetic Exception:

In Java applications,when we have a situation like number divided by zero,


("num/0") then JVM will rise an exception like "Arithmetic Exception".

class Test{

public static void main(String args[]){

int i=100;

int j=0;

float f=i/j;

System.out.println(f);

}}

If we execute the above code then JVM will provide the following Exception
message. Exception in thread "main" java.lang.ArithmeticException:/by zero
at Test.main(Test.java7)

The above exception message is divided into the following three parts:

1.Exception Name :java.lang.ArithmeticException

2.Exception Description: / by zero

3.Exception location : Test.java:7

2.NullPointerException:

In Java applications,when we access any variable or method on a reference


variable having 'null' value then JVM will rise an exception like
"NullPointerException".
import java.util.*;

class Test{

public static void main(String args[]){

Date d=null;

System.out.println(d.toString());

}}

If we execute the above code then JVM will provide the following exception
details.

Exception Name : java.lang.NullPointerException

Exception Description:No Description

Exception Location:Test.java:7

3.ArrayIndexOutofBoundsException:

In Java applications,when we access a value from an array whose index


value is greater then or same as array size then JVM will rise
"ArrayIndexOutOfBoundsException".

Ex:

class Test{

public static void main(String args[]){

int[] a={1,2,3,4};

System.out.println(a[4]);

}}

If we execute the above code then JVM will provide the following exception
message:
Exception Name:java.lang.ArrayIndexOutOfBoundsException

Exception Description:4

Exception Location:Test.java:10

4.FileNotFoundException:

In Java applications,when we are preparing FileInputStream or FileReader


with a particular source file,where if the specified source file is not existed
then JVM will rise "FileNotFoundException"

Ex:

import java.io.*;

class Test{

public static void main(String args[]) throws Exception{

//FileInputStream fis=new FileInputStream("abc.txt");

FileReader fr=new FileReader("abc.txt");

}}

If we execute the above code then JVM will provide the following exception
message:

Exception Name:java.io.FileNotFoundException

Exception Description:abc.txt(The System Cannot Find the file specified)

Exception Location:Test.java:7

5.ClassNotFoundException:

In Java applications,when we trying to load a particular class bytecode to the


memory by using Class.forName(-) method,where if the specified class .class
file is not available at current location,at java predefined library and at the
locations refered by "classpath" environment variable then JVM will rise
"ClassNotFoundException".
class Test{

public static void main(String args[]){

Class.forName("A");

}}

If we execute the above code JVM will provide the following exception
details:

Exception Name:java.lang.ClassNotFoundException

Exception Description:A

Exception Location:Test.java:5

6.InstantiationException:

In Java applications,when we are creating an object for the particular class


by using newInstance() method from "java.lang.Class",where JVM will
search and execute 0-argument constructor,if the respective class is not
having 0-argument constructor then JVM will rise "InstantiationException".

class A{

static{

System.out.println(“Class Loading”);

A(int i){

System.out.println("Object Creating");

}}

class Test{

public static void main(String args[]) throws Exception{

Class c=Class.forName("A");

Object obj=c.newInstance();

}}
If we execute the above code then JVM will provide the following
ExceptionDetails.

Exception Name :java.lang.InstantiationException

Exception Description:A

Exception Location:Test.java:7

7.IllegealAccessException:

In Java applications, when we are trying to create object for a particular


class by using "newInstance()" method where JVM will search and execute
"non-private" constructor, where if the respective class is having only
"private" constructor then JVM will rise "IllegalAccessException".

Ex:

class A{

private A(){

System.out.println("Object Creating");

}}

class Test{

public static void main(String args[])throws Exception{

Class c=Class.forName("A");

Object obj=c.newInstance();

}}

If we execute the above code then JVM will provide the following exception
details.

Exception Name:java.lang.IllegalAccessException

Exception Description:Class Test can not access a member of class A with


modifiers "private".

Exception Location:Test.java:10
8.IllegalArgumentException:

In general,in Java applications,we may provide methods with


parameters,where method parameters will allow the values on the basis of
the parameter dataTypes ranges.In some situations, methods may have
restrictions about the parameter values irrespective of dataTypes provided
ranges.In this context,if we provide any value which is not in the range
defined by the methods then JVM will rise an exception like
"IllegalArgumentException".

In Java,Threads are having priority values range that is from 1 to 10.If we


pass any priority value which is not in between 1 and 10 as a parameter to
setPriority() method then JVM will rise an exception like
"IllegalArgumentException".

class Test{

public static void main(String args[]){

Thread t=new Thread();

t.setPriority(15);

}}

If we execute the above code then JVM will provide the following exception
details.

Exception Name:java.lang.IllegalArgumentException

Exception Description:No Description

Exception Location:Test.java:10

9.IllegalThreadStateException:

In MultiThreading,when Main Thread[JVM created Thread to execute main()


method]access start() method over any thread reference then JVM will
create an Thread and JVM will start that thread to access run() method of
the respective thread class.
In MultiThreading,if any Thread terminated along with Main Thread
automatically then that thread is called as "Daemon Thread".

To make Daemon threads,we have to access setDaemon(true) method


before starting that thread.

If we access setDaemon(true) method after starting the thread then JVM will
rise an exception like "IllegalThreadStateException".

class MyThread extends Thread{

public void run(){

while(true){

System.out.println("User Thread");

}}}

class Test{

public static void main(String args[]){

MyThread mt=new MyThread();

mt.setDaemon(true);

mt.start();

for(int i=0;i<10;i++){

System.out.println("Main Thread");

}}

If we run the above programme then JVM will provide the following
exception details.

Exception Name:java.lang.IllegalThreadStateException

Exception Description:No Description

Exception Location:Test.java:17
10.ClassCastException:

In Java applications,it is possible to keep sub class object reference value in


super class reference variable but it is not possible to keep super class
object reference value in sub class reference variable.

In Java applications,when we are trying to keep super class object reference


value in sub class reference variable in downcasting then JVM will rise an
exception like "java.lang.ClassCastException".

class A{

class B extends A{

class Test{

public static void main(String args[]){

A a=new A();

B b=(B)a;

}}

If we run the above code then JVM will provide the following exceptional
details:

Exception Name:java.lang.ClassCastException

Exception Description:A cannot be cast to B

Exception Location:Test.java:10

“throw” keyword:

throw is a JAVA keyword,it can be used to raise an exception intentionally as


per the application requirement.
Syntax:

throw new Exception_Name([Param_List]);

NOTE:In general,we will utilize "throw" keyword in custom


exceptions inorder to rise an exception.

Ex:

import java.io*;

class Test{

public static void main(String[] args)throws Exception{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Account Number :");

String accNo=br.readLine();

System.out.println("Account Name :");

String accName=br.readLine();

int p_num=Integer.parseInt(pin_number);

if(p_num > 1000 && p_num < 9999){

System.out.println("Account Details");

System.out.println("----------------");

System.out.println("Account Number :"+accNo);

System.out.println("Account Name :"+accName);

System.out.println("Pin Number :"+XXXXXX);

System.out.println("Valid Pin Number");

}
else{

throw new RuntimeException("Invalid PIN Number");

}}}

If any statement we have provided immediately after "throw" statement


then compiler will rise an error like "unreachable statement".

class Test{

public static void main(String args[]){

System.out.println("Before Exception");

throw new ArithmeticException("My Arithmetic Exception");

System.out.println("After Exception");

}}

In Java,there are two ways to handle the exceptions:

1.By using "throws" keyword

2.By using try-catch-finally

1.”throws” keyword:

It is a Java keyword,it can be used to bypass the generated exception from


the present method or constructor to the caller method (or) constructor.

In Java applications,”throws” keyword will be used in method


declarations,not in method body.

In Java applications,”throws” keyword will allows an exception class name,it


should be either same as the generated exception or super class to the
generated exception.It should not be subclass to the generated Exception.

“throws” keyword will allow more than one exception in method prototypes.
In Java applications,”throws” keyword will be utilized mainly for checked
exceptions.

Ex:void m1() throws RuntimeException{

Throw new ArithmeticException();

Status:Valid

Ex:void m1() throws FileNotFoundException{

Throw new IOException();

Status:InValid

Ex:

Void m1() throws NullPointerException,ClassNotFoundException{

Status:Valid

Ex:

Void m1() throws IOException,FileNotFoundException

Status:Valid

If we specify any super exception class along with throws keyword,then it is


not necessary to specify any of its child exception classes along with
“throws” keyword.

NOTE:In any Java method,if we call some other method which is bypassing
an exception by using “throws” keyword,then we must handle that exception
either by using “throws” keyword in the present method prototype or by
using “try-catch-finally” in the body of the present method.
Ex:

Void m1() throws Exception{

-----

------

Void m2(){

try{

m1();

catch(Exception e){

e.printStackTrace();

}}

void m1() throws Exception{

----

void m3() throws Exception{

m1();

Example program for “throws” keyword:

Import java.io.*;

class A{

void add() throws Exception{

concat();
}

Void concat() throws IOException{

throw new IOException();

class Test{

public static void main(String args[]) throws Throwable{

A a=new A();

a.add();

}}

Internal Flow:

If we compile the above program,then compiler will recognize throw keyword


in concat() method at Lline:10

With this compiler will generate exception notification with 6 line as


exception location,due to “throws” keyword in concat() method prototype
the specified exception will be bypasses to concat() method call in add()
method body at line:6,due to “throws” keyword in add(-) method
prototype,the specified exception is bypass to add() method call in main()
method that is at line:18,due to “throws” keyword in main() method
prototype,the specified exception will be bypassed to main() method call
that is to JVM.In this context,compiler will not provide any exception
notification,but when we execute the above program,Default Exception as
part of JVM will take that exception and it will provide the exception details
by including all the locations like 10th line,6th line and 18th line.
Q)What are the differences between “throw” and “throws” keywords?

Ans:

1.”throw” keyword can be used to “throws” keyword will by pass the


rise the exceptions intentionally as exceptions from the present method
Per the application reqirement. to the caller method.
2.”throw” keyword will be utilized in “throws” keyword will be used in
method body. method declarations or in method
prototype (or) in method header
part.
3.”throw” keyword will allow only one “throws” keyword will allow more
exception class name. than one exception class name.

try-catch-finally:

In Java application “throws” keyword is not really an exception


handler,because “throws” keyword will bypass the exception handling
responsibility from present method to the caller method.

If we want to handle the exceptions,the location where exceptions are


generated then we have to use “try-catch-finally”.

Syntax:

try{

catch(Exception_Name e){

finally{

}
where the purpose of try block is to include some java code where the
chances of getting exceptions.

If JVM identify any exception inside "try" block then JVM will bypass flow of
execution to "catch" block by skipping all the remaining instructions in try
block and by passing the generated Exception object reference as
parameter.

If no exception is identified in "try" block then JVM will execute completely


"try" block,at the end of try block JVM will bypass flow of execution to
"finally" block directly.

The main purpose of catch block is to catch the exception from try block and
to display exception details on command prompt.

To display exception details on command prompt,we have to use the


following three approaches.

1.e.printStackTrace()

2.System.out.println(e):

3.System.out.println(e.getMessage());

1.e.printStackTrace():

It will display the exception details like Exception Name,Exception


Description and Exception Location.

2.System.out.println(e):

If we pass Exception object reference variable as parameter to


System.out.println(-) method then JVM will access Exception class toString()
method internally,it will display the exception details like Exception
name,Exception description.

3.System.out.println(e.getMessage()):

Where getMessage() method will return a String contains the exception


details like only Description of the exception.
class Test{

public static void main(String args[]){

try{

throw new ArithmeticException("My Arithmetic Exception");

catch(ArithmeticException e){

e.printStackTrace();

System.out.println();

System.out.println(e);

System.out.println();

System.out.println(e.getMessage());

finally{

}}

Output:

java.lang.ArithmeticException:My Arithmetic Exception

at Test.main(Test.java:7)

java.lang.ArithmeticException:My Arithmetic Exception

My Arithmetic Exception

The main purpose of finally block is to include some Java code inorder to
execute irrespective of getting exception in "try" block and irrespective of
executing "catch" block.
Q)What is the difference between "final","finally" and "finalize" in JAVA?

1."final" is a keyword it can be used to declare constant expressions.

a)final variable:It will not allow modifications over its value.

b)final methods:It will not allow method overriding.

c)final class:It will not be extended.

2.finally block:It is a part in try-catch-finally syntax,it will include some


instructions,which must be executed by JVM irrespective of getting exception
from try block and irrespective of executing catch block.

3.finalize():It is a method in java.lang.Object class,it will be executed before


destroying objects inorder to give final notification to the user about to
destroy objects.

Q)Find the output from the following programs.

class Test{

public static void main(String args[]){

System.out.println("Before Try");

try{

System.out.println("Inside Try");

catch(Exception e){

System.out.println("Inside Catch");

finally{

System.out.println("Inside Finally");

System.out.println("After Finally");
}}

Output:

Before try

Inside try

Inside finally

After finally

class Test{

public static void main(String args[]){

System.out.println("Before Try");

try{

System.out.println("Before Exception in try");

float f=100/0;

System.out.println("After Exception in try");

catch(Exception e){

System.out.println("Inside Catch");

finally{

System.out.println("Inside Finally");

System.out.println("After Finally");

}}
Output:

Before try

Before exception in try

Inside catch

Inside finally

After finally

class A{

int m1(){

try{

return 10;

catch(Exception e){

return 20;

finally{

return 30;

}}}

class Test{

public static void main(String args[]){

A a=new A();

int val=a.m1();

System.out.println(val);

}}
Output:

30

NOTE:finally block provided return statement is the finally return statement


for the method

Q)Is it possible to provide "try" block without "catch" block?

Ans:Yes,it is possible to provide try block with out catch block but by using
"finally" Block.

try{

finally{

class Test{

public static void main(String args[]){

System.out.println("Before try");

try{

System.out.println("Before Exception inside try");

int i=100;

int j-0;

float f=i/j;

System.out.println("After Exception inside try");

finally{

System.out.println("Inside finally");

}
System.out.println("After Finally");

}}

Status:No Compilation Error.

Output:

Before try

Before exception inside try

Inside finally

Exception in thread “main” java.lang.ArithmeticException:/by zero

at Test.main(Test.java:11)

Reason:When JVM encounter exception in try block,JVM will search for catch
block,if no catch block is identified,then JVM will terminate the program
abnormally after executing finally block.

Q)Is it possible to provide "try" block with out "finally" block?

Ans:Yes,it is possible "try" block with out using "finally" block but by
providing "catch" block.

Ex:

try{

-------

--------

catch(Exception e){

-------------

-------------

}
Q)Is it possible to provide try-catch-finally

a)inside try block,

b)inside catch block and

c)inside finally block

Ans:Yes,it is possible to provide try-catch-finally inside try block,inside catch


block and inside finally block.

Syntax-1:

try{

try{

catch(Exception e){

finally{

catch(Exception e){

finally{

Syntax-2:

try{

}
catch(Exception e){

try{

catch(Exception e)

finally{

finally{

Syntax-3:

try{

catch(Exception e){

finally{

try{

catch(Exception e){

finally{

}}
Q)Is it possible to provide more than one catch block for a single try block?

Ans:Yes,it is possible to provide more than one catch block for a single try
block but with the following conditions.

1.If no inheritance relation existed between exception class names which are
specified along with catch blocks then it is possible to provide all the catch
blocks in any order.If inheritance relation is existed between exception class
names then we have to arrange all the catch blocks as per Exception classes
inheritance increasing order.

2.In general,specifying an exception class along with a catch block is not


giving any guarantee to rise the same exception in the corresponding try
block,but if we specify any pure checked exception along with any catch
block then the corresponding "try" block must rise the same pure checked
exception.

Ex1:

try{

catch(ArithmeticException e){

catch(ClassCastException e){

catch(NullPointerException e){

Status:Valid Combination

Reason:No Inheritance Relation is existed between exception classes.


Ex2:

try{

catch(NullPointerException e){

catch(ArithmeticException e){

catch(ClassCastException e){

status:Valid Combination

Ex3:

try{

catch(ArithmeticException e){

catch(RuntimeException e){

catch(Exception e){

Status:Valid

Reason:Inheritance Relationship
Ex4:

try{

catch(Exception e){

catch(RuntimeException e){

catch(ArithmeticException e){

status:Invalid

Ex5:

try{

throws new ArithmeticException("My Exception");

catch(ArithmeticException e){

catch(IOException e){

catch(NullPointerException e){

Status:Invalid
Ex6:

try{

throw new IOException("My Exception");

catch(ArithmeticException e){

catch(IOException e){

catch(NullPointerException e){

status:Valid

JAVA7 Features in Exception Handling:

1.Multi Catch block

2.Try-with-Resources/Automatic Resources Management/Auto close able


Resources

1.Multi Catch block:

Consider the below syntax:

try{

catch(Exception e){

}
If we specify "Exception" class along with catch block then it able to catch
and handle all the exceptions which are either same as Exception or child
classes to Exception, this approach will not provide specific handling for the
specific exceptions,it will handle all the exceptions in the common way like
Exception object.

If we want to handle to the Exceptions separately then we have to use


multiple catch blocks for a single try block.

try{

}catch(ArithmeticException e){

}catch(NullPointerException e){

}catch(ClassCastException e){

If we use this approach then no.of catch blocks are increased.

In Java applications,if we want to handle all the exceptions separately and


by using a single catch block then we have to use "JAVA7" provided multi-
catch block

Syntax:

try{

catch(Exception1 | Exception2 |....|Exception-n e){

where Exception1,Exception2....must not have inheritance relation otherwise


Compilation error will be raised.
Example Programme on Multi catch block example program:

class Test{

public static void main(String args[]){

try{

/* int a=10;

int b=0;

float c=a/b;

*/

/*java.util.Date d=null;

System.out.println(d.toString());

*/

int[] a={1,2,3,4,5};

System.out.println(a[10]);

catch(ArithmeticException | NullPointerException |
ArrayIndexOutOfBoundsException e){

e.printStackTrace();

}}

Try-With-Resources/Auto Closeable Resources:

In general,in Java applications,we may use the resources like


Files,Streams,Database Connections....as per the application requirements.

If we want to manage the resources along with try-catch-finally in Java


applications then we have to use the following conventions.
1.Declare all the resources before "try" block.

2.Create the resources inside "try" block.

3.Close the resources inside finally block.

The main intention to declare the resources before "try" block is to make
available resources variables to "catch" block and to "finally" block to use.

If we want to close the resources in "finally" block then we have to use


close() methods, which are throwing some exceptions like
IOException,SQLException depending on the resource by using "throws"
keyword,to handle these exceptions we have to use "try-catch-finally" inside
"finally" block.

//Declare the resources

File f=null;

BufferedReader br=null;

Connection con=null;

try{

//create the resources

f=new File("abc.txt");

br=new BufferedReader(new InputStreamReader(System.in));

con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");

-----

-----

catch(Exception e){

}
finally{

//close the resources

try{

f.close();

br.close();

con.close();

}catch(Exception e){

e.printStackTrace();

}}

To manage the resources in Java applications,if we use the above convention


then developers have to use close() methods explicitly,Developers have to
provide try-catch-finally inside "finally" block,this convention will increase
no.of instructions in Java applications.

To overcome all the above problems,JAVA7 version has provided a new


Feature in the form of "Try-With-Resources" or "Auto Closeable Resources".

In the case of "Try-With-Resources",just we, have to declare and create the


resources along with "try"[not inside try block,not before try block] and no
need to close these resources inside the finally block,why because,JVM will
close all the resources automatically when flow of execution is coming out
from "try" block.

In the case of "Try-With-Resources",it is not required to close the resources


explicitly,it is not required to use close() methods in finally block explicitly,so
that it is not required to use "finally" block in try-catch-finally syntax.
Synatx:

try(Resource1;Resource2;........Resource-n){

-------

------

catch(Exception e){

-----

-----

Where all the specified Resources classes or interfaces must implement or


extend "java.io.AutoCloseable" interface.

Where if we declare resources as AutoCloseable resources along with "try"


then the resources reference variables are converted as "final" variables.

Ex:

try(File f=new File("abc.txt");

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

Connection
con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");)

-------

-------

catch(Exception e){

e.printStackTrace();}
NOTE:In Java,all the predefined Stream classes,File class,Connection
interface are extends/implemented "java.io.AutoCloseable"
interface predefinedly.

import java.io.*;

class Test{

public static void main(String args[]){

try(FileInputStream fis=new FileInputStream("ScannerEx.java")

FileOutputStream fos=new FileOutputStream("DynamicEx2.java");)

int size=fis.available();

byte[] b=new byte[size];

fis.read(b);

fos.write(b);

System.out.println("File Transfered From ScannerEx.java to


DynamicEx2.java");

catch(Exception e){

e.printStackTarce();

}}}

Custom Exceptions/User Defined Exceptions:

Custom Exceptions are the exceptions,which would be defined by the


developers as per their application requirements.

If we want to define user defined exceptions then we have to use the


following steps:
1.Define User defined Exception class:

To declare user-defined Exception class,we have to take an user-defined


class,which must be extended from java.lang.Exception class.

Class MyException extends Exception

2.Declare a String parametrized constructor in User-Defined Exception class


and access String parametrized super class constructor by using "super"
keyword:

class MyException extends Exception{

MyException(String err_Msg){

super(err_Msg);

}}

3.Create and Rise exception in Java application as per the application


requirement:

try{

throw new MyException("My Custom Exception");

catch(MyException me){

me.printStackTrace();

}
class InsufficientFundsException extends Exception{

InsufficientFundsException(String err_Msg){

super(err_Msg);

}}

class Transaction{

String accNo;

String accName;

String accType;

int initial_Amt=10000;

Transaction(String accNo,String accName,String accType){

this.accNo=accNo;

this.accName=accName;

this.accType=accType;

public void withdraw(int wd_Amt){

try{

System.out.println("Transaction Details");

System.out.println("-------------------");

System.out.println("Transaction Id :T123");

System.out.println("Account Number :"+accNo);

System.out.println("Account Name :"+accName);

System.out.println("Account Type :"+accType);

System.out.println("Transaction Type : WITHDRAW");

System.out.println("Initial Amount :"+initial_Amt);


System.out.println("Withdrawl Amount :"+wd_Amt);

int total_Amt=0;

if(wd_Amt<initial_Amt)

total_Amt=initial_Amt-wd_Amt;

initial_Amt=total_Amt;

System.out.println("Total Amount :"+total_Amt);

System.out.println("Transaction Status : SUCCESS");

else{

total_Amt=initial_Amt;

System.out.println("Total Amount :"+total_Amt);

System.out.println("Transaction Status:FAILURE");

throw new InsufficientFundsException("Amount is not sufficient in your


Account");

catch(InsufficientFundsException e){

System.out.println(e.getMessage());

System.out.println("********ThankQ,Visit Again***********");

class Test{

public static void main(String args[]){

Transaction tx1=new Transaction("abc123","Durga","Savings");

tx1.withdraw(5000);
System.out.println();

Transaction tx2=new Transaction("xyz123","Anil","Savings");

tx2.withdraw(15000);

}}

IOStreams:

In any programming language,in any application,providing input to the


programme and getting output from the programme is essential.

In case of C and C++ applications,we are able to perform input and output
operations by using some predefined library in the form of
printf(),scanf(),cin>>,cout<<,......

Similarly in Java Applications,to perform input and output operations we


have to use streams.

Java has represented all the streams in the form of predefined classes in
"java.io" package.

Stream:Stream is medium or channel,it will allow the data in continuous flow


from input devices to java program and from Java program to output
devices.

In Java IOStreams are divided into following ways:

1.Byte oriented Streams.


2.Character-Oriented Streams

1.Byte-Oriented Streams

These are Streams,which will allow the data in the form of bytes from input
devices to Java program and from java program to output devices.

The length of the data in byte-oriented streams is 1 byte.

There are two types of Byte-Oriented Streams

1.InputStream

2.OutputStream

1.InputStream:

It is a byte-oriented Stream,it will allow the data in the form of bytes from
input devices to Java program.

Ex:

ByteArrayInputStream

FilterInputStream

DataInputStream

ObjectInputStream

FileInputStream

StringBufferInputStream

BufferedInputStream….

2.OutputStream:

It is a byte-oriented Stream,it will allow the data in the form of bytes from
Java programmes to output devices.

Ex:ByteArrayOutputStream

FilterOutputStream

DataOutputStream

FileOutputStream

PrintStream

BufferedOutputStream..

NOTE:All the ByteOrientedStream classes are terminated with


"Stream" word.

2.Character-Oriented Streams:

These are the Streams,which will allow the data in the form of characters
from input devices to java program and form java program to output
devices.

The length of the data in characters-oriented stream is 2 bytes.

There are two bytes of character-oriented streams

1.Reader

2.Writer

1.Reader:

It is a character-oriented stream,it will allow the data in the form of


characters from input devices to java program.

Ex:

CharArrayReader

FilterReader

BufferedReader

FileReader
InputStreamReader….

2.Writer:

It is a character-oriented stream,it will allow the data in the form of


characters from java program to output devices.

Ex:

CharArrayWriter

FilterWriter

FileWriter

PrintWriter

BufferedWriter….

NOTE:All the predefined Classes of character-oriented streams are


terminated with either Reader or Writer.

FileOutPutStream:

It is byte-oriented Stream,it can be used to transfer the data from Java


program to a particular target file.

To transfer the data from Java program to a particular target file by using
FileOutPutstream we have to use the following Steps.

1.Create FileOutPutStream between Java programme and target file:

If we want to create FileOutPutStream class object then we have to use the


following constructors

public FileOutPutStream(String target_File)

public FileOutPutStream(String target_File,boolean b)


Ex:

FileOutPutStream fos=new FileOutPutStream("abc.txt");

-->It will override the existed data in the target file at each and every write
operation.

FileOutPutStream fos=new FileOutPutStream("abc.txt",true);

-->It will not override the existed data in the target file,it will append the
specified new data to the existed data in the target file.

When JVM encounter the above instruction,JVM will perform the following
tasks.

a)JVM will take the specified target file.

b)JVM will search for the specified target file at the respective location.

c)If the specified target file is available then JVM will establish
FileOutPutStream from java program to target file.

d)If the specified target file is not available then JVM will create a file with
the target file name and establish FileOutPutStream from Java program to
target file.

2)Declare the data and convert into byte[]:

String data="Hello";

byte[] b=data.getBytes();

3)Write Byte Array data into FileOutPutStream:

To write byte[] data into FileOutPutStream,we have to use the following


method.
public void write(byte[] b) throws IOException

Ex:

fos.write(b);

4)Close FileOutPutStream:

fos.close();

2.FileInputStream:

It is a byte-oriented Stream,it can be used to transfer the data from a


particular source file to Java Program.

If we want to transfer the data from source file to java programme by using
FileInputStream,we have to use the following Steps:

1.Create FileInputStream class Object:

To create FileInputStream class object,we have to use the following


constructor from java.io.FileInputStream class.

public FileInputStream(String file_name) throws FileNotFoundException

Ex:

FileInputStream fis=new FileInputStream("abc.txt");

When JVM encounter the above instruction then JVM will perform the
following actions.

1.JVM will take the specified source file name.

2.JVM will search for the specified source file at the respective location.

3.If the source file is not available at the respective location then JVM will
raise an excpetion like "java.io.FileNotFoundException".

4.If the required source file is available then JVM will establish
FileInputStream from source file to JAVA program.
5.After creating FileInputStream,JVM will transfer the data from source file
to FileInputStream in the form bytes.

2.Get the size of the data from FileInputStream and prepare byte[] with the data
size:

To get the size of the data from FileInputStream,we have to use the
following method

public int available()

Ex:

int size=fis.available();

byte[] b=new byte[size];

3.Read the data from FileInputStream into byte[]:

To read the data from FileInputStream into byte[],we have to use the
following method.

public void read(byte[] b)throws IOException

Ex:

fis.read(b);

4.Convert data from byte[] to String:

String data=new String(b);

System.out.println(data);

5.close FileInputStream:

fis.close();
Write a Java program to display a particular file content on command prompt
by taking filename as command line input?

import java.io.*;

class DisplayEx{

public static void main(String args[]) throws Exception{

String file_Name=args[0];

FileInputStream fis=new FileInputStream(file_Name);

int size=fis.available();

byte b[]=new byte[size];

fis.read();

String data=new String(b);

System.out.println(data);

fis.close();

}}

Write a Java program to count no of words available in a particular text file


and how many times the word "is" is repeated?

import java.io.*;

import java.util.*;

class Word_Count_Ex{

public static void main(String args[]) throws Exception{


FileInputStream fis=new FileInputStream("abc.txt");

int size=fis.available();

byte b[]=new byte[size];

fis.read();

String data=new String(b);

StringTokenizer st=new StringTokenizer(data);

int tokens=st.countTokens();

System.out.println("No of words :"+tokens);

int count=0;

while(st.hasMoreTokens()){

String token=st.nextToken();

if(token.equals("is")){

count=count+1;

}}

System.out.println("'is' is repeated :"+count);

fis.close();

}}

Write a Java program to copy an image from a source file to a particular


target file?

import java.io.*;

public class Image_Copy_Ex{

public static void main(String args[]){

FileInputStream fis=new FileInputStream();

int size=fis.available();
byte[] b=new byte[size];

fis.read(b);

FileOutPutStream fos=new FileOutPutStream("abc.jpg");

fos.write(b);

fis.close();

fos.close();

}}

FileWriter:

This character-oriented Stream can be used to transfer the data from Java
Application to a particular target File.

If we want to transfer the data from java application to a particular target


file by using FileWriter then we have to use the following steps:

1.Create FileWriter object:

To create FileWriter class object,we have to use the following constructor.

public FileWriter(String target_File)

Ex:FileWriter fw=new FileWriter("abc.txt");

-->It will override the existed content with the new content at each and
every write operation.

public FileWriter(String target_File,boolean b)

Ex:FileWriter fw=new FileWriter("abc.txt",true);

-->It will append new content to the existed content available in the file at
each and every write operation.

When JVM encounter the above instructions,JVM will take the specified file
and JVM search for the specified file at the respective location,if the required
target file is available then JVM will establish FileWriter from Java application
to the target file.If the required target file is not available at the respective
location then JVM will create a new file with the same specified file name and
establish FileWriter from Java application to the target file.

2.Declare the data which we want to transfer and convert that data into char[]:

String data="Hello";

char[] ch=data.toCharArray();

3.Write char[] data into FileWriter:

To write char[] data into FileWriter,we have to use the following method.

public void write(char[] ch)throws IOException

Ex:fw.write(ch);

4.Close FileWriter:

fw.close();

Example programme on FileWriter:

import java.util.*;

public class FWEx{

public static void main(String args[])throws Exception{

FileWriter fw=new FileWriter("abc.txt",true);

String data="DurgaSoftwareSolutions";

char[] ch=data.toCharArray();

fw.write(ch);

fw.close();
}}

FileReader:

This character-oriented stream can be used to transfer the data from a


particular source file to Java program.

If we want to transfer the data from a particular source file to Java program
by using FileReader then we have to use the following steps:

1.Create FileReader class Object:

To create FileReader class object,we have to use the following constructor.

public FileReader(String file_Name)throws FileNotFoundException

Ex:FileReader fr=new FileReader("abc.txt");

when JVM encounter the above instruction,JVM will perform the following
steps.

a)JVM will take source file name from FileReader constructor.

b)JVM will check whether the specified file is available or not at the
respective location.
c)If the specified source file is not available at the respective location then
JVM will rise an exception like "java.io.FileNotFoundException".

d)If the specified file is existed at the respective location then JVM will
establish FileReader from source file to Java program.

e)After creating FileReader,JVM will transfer the content of source file to


FileReader object in the form of characters.

2.Read data from FileReader:

To read data from FileReader,we have to use the following steps.

a)Read character by character from FileReader in the form of ASCII values.

b)Convert that ASCII values into the respective characters.

c)Append the converted characters to a String variable.

Repeat the above steps upto all the characters which are available in the
respective source file or upto the end-of-file character i.e "-1".

To read an ASCII value from FileReader,we have to use the following


method.

public int read() throws IOException

3.Close FileReader:

fr.close();

Example programme on FileReader:

import java.util.*;

public class FREx{

public static void main(String args[])throws Exception{

FileWriter fr=new FileWriter("abc.txt");

String data="";
int val=fr.read();

while(val!=-1){

data=data+(char)val;

val=fr.read();

System.out.println(data);

fr.close();

}}

Write a JAVA programme to copy a document from one file to another file by
using character oriented Streams?

import java.io.*;

public class FileCopyEx{

public static void main(String args[])throws Exception{

FileReader fr=new FileReader("hibernatecgf.xml");

String data="";
int val=fr.read();

while(val!=-1){

data=data+(char)val;

val=fr.read();

char[] ch=data.toCharArray();

FileWriter fw=new FileWriter("abc.xml");

fw.write(ch);

fr.close();

fw.close();

}}

Approaches to provide dynamic input:

There are three approaches to provide dynamic input in java applications.

1.BufferedReader

2.Scanner

3.Console

1.BufferedReader:

If we want to take dynamic input by using BufferedReader in java


applications then we have to use the following statement.

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

where "in" is static variable,it will refer a predefined "InputStream" object


which is connected with command prompt.

If we provide data on command prompt then that data will be transfered to


InputStream object in the form of binary data.
where "InputStreamReader can be used to convert the data from binary
representation to character representation.

where BufferedReader can be used to improve the performance of Java


application while performing input operation.

To read the data from BufferedReader,we will use the following method

1.readLine()

2.read()

Q)What is the difference between readLine() method and read() method?

Ans:readLine() method will read a line of text from command


prompt[BufferedReader] and it will return that data in the form of String.

public String readLine() throws IOException

read() method will read a single character from command


prompt[BufferedReader] and it will return that character in the form of its
ASCII value.
public int read()throws IOException

Example programme on BufferedReader:

import java.io.*;

public class BufferedReaderEx{

public static void main(String args[])throws Exception{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("Enter Text :");

String data1=br.readLine();

System.out.println("Enter the same text again :");

int data2=br.read();

System.out.println("First Entered :"+data1);

System.out.println("Second Entered :"+data2+"--->"+(char)data2);

}}

Consider the following programme:

import java.io.*;

public class BufferedReaderEx{

public static void main(String args[])throws Exception{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("First value :");


String val1=br.readLine();

System.out.println("Second value :");

String val2=br.readLine();

System.out.println("Addition :"+val1+val2);

}}

If we provide 10 and 20 as dynamic input to the above programme then the


above programme will display "1020" value instead of 30 that is the above
programme has performed String concatenation instead of performing
Arithmetic Addition because br.readLine() method has return 10 and 20
values in the form String data.

In the above programme,if we want to perform Arithmetic operations over


dynamic input then we have to convert String data into the respective
primitive data,for this we have to use Wrapper Classes.
ThereFore,BufferedReader dynamic input approach is depending on wrapper
classes while reading primitive data as dynamic input.

Example programme on BufferedReader:

import java.io.*;

public class BufferedReaderEx{

public static void main(String args[])throws Exception{

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));

System.out.println("First value :");

String val1=br.readLine();

System.out.println("Second value :");


String val2=br.readLine();

int f_Val=Integer.parseInt(val1);

int s_Val=Integer.parseInt(val2);

System.out.println("Addition :"+(f_Val+s_Val));

}}

Scanner:

This class is provided by Java in java.util package along with JDK5.0 Version.

In java applications, if we use BufferedReader to dynamic input then we


must use wrapper classes while reading primitive data as dynamic Input.

In java applications, if we use "Scanner" to read dynamic input then it is not


required to use wrapper classes while reading primitive data as dynamic
input, scanner is able to provide environment to read primitive data directly
from command prompt.

If we want to use scanner in Java applications then we have to use the


following steps.

1.Create Scanner class Object:

To create Scanner class Object,we have to use the following constructor

public Scanner(InputStream is)

Ex:Scanner s=new Scanner(System.in);

2.Read dynamic Input:

To read String data as Dynamic input,we have to use the following method.

public String next()

To read primitive data as Dynamic input,we have to use the following


method.
public xxx nextXXX()

where xxx may be byte,short,int,float...............

Console:

This class is provided by Java in java.io package along with JAVA6 Version.

In Java applications,to take dynamic input,if we use BufferedReader and


Scanner then we are able to get the following drawbacks:

1.We have to consume 2 instructions for each and every dynamic


input[s.o.pln(..) and readLine() or

nextXXX() methods]

2.These are not providing security for the data like password data,pin
numbers.....

To overcome the above problems,we have to use "Console" dynamic input


approach.

If we want to use Console in Java applications then we have to use the


following Steps:

1.Create Console object:

To get Console object,we have to use the following method from "System"
class.

public static Console console()

Ex:Console c=System.console();

2.Read dynamic Input:

To read String data,we have to use the following method.

public String readLine(String msg)

To read password data,we have to use the following method.


public char[] readPassword(String msg)

Example programmes on Console:

import java.io.*;

public class ConsoleEx{

public static void main(String args[])throws Exception{

Console c=System.console();

String uname=c.readLine("User Name :");

char[] pwd=c.readPassword("PassWord :");

String upwd=new String(pwd);

if(uname.equals("durga")&&upwd.equals("durga")){

System.out.println("Valid User");

else{

System.out.println("InValid User");

}}

Serialization and Deserialization:

If we design Java applications by distributing application logic over multiple


[JVMS] then that Java application is called as Distributed Application.

In general, in Distributed applications, it is frequent requirement to transfer


an object [Distributed Object] from one machine to another machine.
In Java, Object is a block of memory, it is not possible to transfer the object
through network, where we have to transfer object data from one machine
to another machine through network.

To transfer an Object through network from one machine to another


machine, first we have to separate the data from an object at local machine
and convert the data from system representation to network representation
then transfer the data to network.

At remote machine, we have to get the data from network and convert the
data from system representation to System representation and reconstruct
an object on the basis of data.

----Diagram--------------

The process of converting the data from System representation to network


representation is called as "Marshalling".

The process of converting the data from Network representation to System


representation is called as "UnMarshalling".

The Process of separating the data from an Object is called as


"Serialization".

The process of reconstructing an object on the basis of data is called as


"Deserialization".

To perform Serialization and Deserialization in Java applications, JAVA has


given two predefined byte-oriented streams like java.io.ObjectOutputStream
for Serialization java.io.ObjectInputStream for Deserialization

In Standalone applications,if we want to perform Serialization and


Deserialization over an object then we have to take a file[text file] to store
serialized data.

Steps to Perform Serialization:

1.Create Serializable Object:


To create Serializable Object we have to implement java.io.Serializable
marker interface to the respective class.

Serializable interface is marker interface,it will make eligible any object for
Serialization and Deserialization.

Example programme on Serializable:

class Employee implements Serializable{

int eno=111;

String ename="AAA";

float esal=5000;

Employee e1=new Employee();

2.Prepare FileOutPutStream with a particular target File:

FileOutPutStream fos=new FileOutPutStream("abc.txt");

3.Create ObjectOutPutStream:

To create ObjectoutputStream,we have to use the following constructor.

public ObjectOutputStream(FileOutputStream fos)

Ex:

ObjectOutputStream oos=new ObjectOutputStream(fos);

4.Write Serializable object to ObjectOutputStream:

To write Serializable object to ObjectOutputStream,we have to use the


following method.

public void writeObject(Object obj)throws NotSerializableException

Ex:oos.writeObject(e1);
Steps To perform DeSerialization:

1.Create FileInputStream object:

FileInputStream fis=new FileInputStream("emp.txt");

2.Create ObjectInputStream:

To create ObjectInputStream class object,we have to use the Following


constructor.

public ObjectInputStream(FileInputStream fis)

Ex:ObjectInputStream ois=new ObjectInputStream(fis);

3.Read DeSerialized Data from ObjectInputStream:

To read DeSerialized object from ObjectInputStream,we have to use the


following method.

public Object readObject()

Ex:Employee e2=(Employee)ois.readObject();

-->In Object serialization, static members are not allowed.

-->If we serialize any object having static variables then compiler will not
rise any error and JVM will not rise any exception but static variables will not
be listed in the serialized data in the text file.

-->In object serialization,if we do not want to allow any variable in


serialization and deserialization then we have to declare that variable as
"transient" variable.

transient int eno=111;


-->In Java applications, if we serialize an object which is not implementing
java.io.Serializable interface then JVM will rise an exception like
"java.io.NotSerializableException".

import java.io.*;

class A{

int i=10;

int j=20;

class Test{

public static void main(String args[])throws Exception{

FileOutputStream fos=new FileOutputStream("abc.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

A a=new A();

oos.writeObject(a);

}}

Status:"java.io.NotSerializableException".[Exception]

-->In Java applications, if we implement Serializable interface to the super


class then automatically all the sub class objects are eligible for Serialization
and Deserialization.

Ex:

import java.io.*;

class A implements Serializable{

int i=10;

int j=20;
}

class B extends A{

int k=30;

int l=40;

class Test{

public static void main(String args[])throws Exception{

FileOutputStream fos=new FileOutputStream("abc.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

B b=new B();

oos.writeObject(b);

}}

-->In Java applications, if we implement Serializable interface in sub class


then only sub class properties are allowed in Serialization and
deserialization, the respective super class members are not allowed in the
Serialization and deserialization.

Ex:

import java.io.*;

class A {

int i=10;

int j=20;

}
class B extends A implements Serializable{

int k=30;

int l=40;

class Test{

public static void main(String args[])throws Exception{

FileOutputStream fos=new FileOutputStream("abc.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

B b=new B();

oos.writeObject(b);

}}

-->In Java applications,while Serializing an object if any associated object is


available then JVM will serialize the respective associated object also but the
respective associated object must implement Serializable interface otherwise
JVM will rise an exception like "java.io.NotSerializableException".

Ex:

import java.io.*;

class Branch implements Serializable{

String bid;

String bname;

Branch(String bid,String bname){

this.bid=bid;

this.bname=bname;

}}

class Account implements Serializable{


String accNo;

String accName;

Branch branch;

Account(String accNo,String accName,Branch branch){

this.accNo=accNo;

this.accName=accName;

this.branch=branch;

}}

class Employee implements Serializable{

String eid;

String ename;

Account acc;

Employee(String eid,String ename,Account acc){

this.eid=eid;

this.ename=ename;

this.acc=acc;

}}

class Test{

public static void main(String args[])throws Exception{

FileOutputStream fos=new FileOutputStream("abc.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

Branch branch=new Branch("B-111","S R Nagar");

Account acc=new Account("abc123","Durga",branch);

Employee emp=new Employee("E-111","Durga",acc);


oos.writeObject(emp);

}}

Externalization:

As part of object serialization and deserialization we are able to separate the


data from Object and stored in a text file and we are able to retrieve that
object data from text file to Object in Java application.

In Java applications, to perform serialization and deserialization Java has


given "ObjectOutputStream" and "ObjectInputStream" two byte-oriented
Streams.

In Java applications, to perform Serialization just we have to send


Serializable object to ObjectOutputStream,it will perform serialization
internally, where Developers are not having controlling over serialization
process.

In Java applications, to perform deserialization just we have to create


ObjectInputStream and we have to read deserialized object,where
ObjectInputStream will perform deserialization internally,where developers
are not having controlling over deserialization process.

In the above context to have controlling over serialization and deserialization


processes inorder to provide the services like security, data
compression,data decompression, data encoding.....over serialized and
deserialized data we have to go for "Externalization".

If we want to perform Externalization in java applications,we have to use the


following steps.

1)Prepare Externalizable object

2)Perform Serialization and Deserialization over Externalizable object.


1)Prepare Externalizable object:

In Java applications,if we want to create Serializable object then the


respective class must implement java.io.Serializable interface.

Similarly, if we want to prepare Externalizable object then the respective


class must implement java.io.Externalizable interface.

java.io.Externalizable is a sub interface to java.io.Serializable interface.

java.io.Serializable interface is a marker interface, which is not having


abstract methods but java.io.Externalizable interface is not marker
interface,which includes the following methods.

public void writeExternal(ObjectOutput oop)throws IOException

public void readExternal(ObjectInput oip)throws


IOException,ClassNotFoundException

where writeExternal(--) method will be executed just before performing


serialization in ObjectOutputStream,

where we have to perform manipulations on the data which we want to


serialize.

where readExternal(--) method will be executed immediately after


performing Deserializationin ObjectInputStream,where we can perform
manipulations over the deserialized data.

where ObjectOutput is stream,it will carry manipulated data for Serialization.

To put data in ObjectOutput,we have to use the following methods.

public void writeXXX(xxx data)

where xxx may be byte,short,int,UTF[String]..........

where ObjectInput will get serialized data from text file to perform
manipulations.

To read data from ObjectInput we have to use the following method

public void readXXX(xxx data)


where xxx may be byte,short,int,UTF[String]..........

If we want to prepare Externalizable object we have to use the following


steps.

a)Declare an user defined class

b)Implement java.io.Externalizable interface.

c)Implement the methods writeExternal(--) and readExternal(--)

of Externalizable interface at the user defined class.

class Employee implements Externalizable{

public void writeExternal(ObjectOutput oop)throws IOException{

---implementation---

public void readExternal(ObjectInput oip)throws


IOException,ClassNotFoundException{

---implementation----

}}

Employee emp=new Employee();

2.Perform Serialization and Deserialization over Externalizable object by using


ObjectOutputStream and ObjectInputStream:

same as Serialization and DeSerialization

Ex:

import java.util.*;
import java.io.*;

class Employee implements Externalizable{

String eid;

String ename;

String email;

String emobile;

//It will be used to construct object while performing deserialization in


Externalization process

public Employee(){

Employee(String eid,String ename,String email,String emobile){

this.eid=eid;

this.ename=ename;

this.email=email;

this.emobile=emobile;

public void writeExternal(ObjectOutput oop)throws IOException{

try{

StringTokenizer st1=new StringTokenizer(eid,"-");

st1.nextToken();

int no=Integer.parseInt(st1.nextToken());

StringTokenizer st2=new StringTokenizer(email,"@");

String mail=st2.nextToken();

StringTokenizer st3=new StringTokenizer(emobile,"-");

st3.nextToken();
String mobile=st3.nextToken();

oop.writeInt(no);

oop.writeUTF(ename);

oop.writeUTF(mail);

oop.writeUTF(mobile);

catch(Exception e){

e.printStackTrace();

}}

public void readExternal(ObjectInput oip)throws


IOException,ClassNotFoundException{

eid="E-"+oip.readInt();

ename=oip.readUTF();

email=oip.readUTF()+"@durgasoft.com";

emobile="91-"+oip.readUTF();

public void getEmpDetails(){

System.out.println("Employee Details");

System.out.println("-----------------");

System.out.println("Employee Id : "+eid);

System.out.println("Employee Name : "+ename);

System.out.println("Employee Mail : "+email);

System.out.println("Employee Mobile: "+emobile);

}}

class ExternalizableEx{
public static void main(String args[])throws Exception{

FileOutputStream fos=new FileOutputStream("emp.txt");

ObjectOutputStream oos=new ObjectOutputStream(fos);

Employee emp1=new Employee("E-


111","Durga","durga@durgasoft.com","91-9988776655");

System.out.println("Employee Data before Serialization");

emp1.getEmpDetails();

oos.writeObject(emp1);

System.out.println();

FileInputStream fis=new FileInputStream("emp.txt");

ObjectInputStream ois=new ObjectInputStream(fis);

Employee emp2=(Employee)ois.readObject();

System.out.println("Employee Data After Deserialization"):

emp2.getEmpDetails();

Files in Java:

File is a storage area to store data.

There are two types of files in Java.

1.Sequential Files

2.RandomAccessFiles

1.Sequential Files:

It will allow the user to retrive data in Sequential manner.

To represent Sequential files,Java has given a predefined class in the form of


java.io.File.
To create File class object we have to use the following constructor.

public File(String file_Name)throws FileNotFoundException

Ex:File f=new File("c:/abc/xyz/emp.txt");

Creating File class object is not sufficient to create a file at directory


structure we have to use the following method.

public File createNewFile()

To create a Directory, we have to use the following method.

public File mkdir()

To get file / directory name we have to use the following method.

public String getName()

To get file / directory parent location,we have to use the following method.

public String getParent()

To get file / directory absolute path,we have to use the following method.

public String getAbsolutePath()

To check whether the created thing File or not,we have to use the following
method.

public boolean isFile()

To check whether the created thing is directory or not we have to use the
following method.

public boolean isDirectory()

Ex:

import java.io.*;

class Test{

public static void main(String args[])throws Exception{


File f=new File("c:/abc/xyz/emp.txt");

f.createNewFile();

System.out.println(f.isFile());

System.out.println(f.isDirectory());

File f1=new File("c:/abc/xyz/student");

f1.mkdir();

System.out.println(f.isFile());

System.out.println(f.isDirectory());

System.out.println("File Name :"+f.getName());

System.out.println("Parent Name :"+f.getParent());

System.out.println("Absolute Path :"f.getAbsolutePath());

int size=fis.available();

byte[] b=new byte[size];

fis.read();

String data=new String(b);

System.out.println(data);

}}

RandomAccessFile:

It is a Storage area,it will allow the user to read data from random positions.

To represent this file,java has given a predefined class in the form of

"java.io.RandomAccessFile".

To create RandomAccessFile class object,we have to use the following


constructor.

public RandomAccessFile(String file_name,String access_Previliges)


where access_Previliges may be "r" [Read] or "rw" [Read and Write]

To write data into randomAccessFile,we have to use the following method.

public void writeXXX(xxx value)

where xxx may be byte,short,int,UTF[String],.....

To read data from RandomAccessFile,we have to use the following method

public XXX readXXX()

where xxx may be byte,short,int,UTF[String],.....

To move file pointer to a particular position in RandomAccessFile,we have to


use the following method.

public void seek(int position)

Ex:

import java.io.*;

class Test{

public static void main(String args[])throws Exception{

RandomAccessFile raf=new RandomAccessFile("abc.txt","rw");

raf.writeInt(111);

raf.writeUTF("Durga");

raf.writeFloat(5000.0f);

raf.writeUTF("HYD");

raf.seek(0);

System.out.println("Employee Number :"+raf.readInt());

System.out.println("Employee Name :"+raf.readUTF());

System.out.println("Employee Salary :"+raf.readFloat());


System.out.println("Employee Address :"+raf. readUTF ());

}}

Annotations:
1.Introduction

2.Comment Vs Annotations

3.XML Vs Annotations

4.Types of Annotations

5.Standard Annotations

6.Custom Annotations

Annotation:

Annotation is a Java Feature provided by JDK 5.0 version,it can


be used to represent metadata in Java applications.

Q)In java applications,to describe metadata we have already


Comments then what is the requirement to go for Annotations?

 Ans:In Java applications,if we provide metadata by using


comments then "Lexical Analyzer" will remove comments
metadata from Java program as part of Compilation.
 As per the application requirement,if we want to bring
metadata upto .java file,upto .class file and upto RUNTIME
of our application then we have to use "Annotations".
Q)In Java applications,to provide metadata at runtime of Java
applications we are able to use XML documents then what is the
requirement to go for "Annotations"?

Ans:In Java applications,if we provide metadata by using XML


documents then we are able to get the following problems.

1.Every time we have to check whether XML documents are


located properly or not.

2.Every time we have to check whether XML documents are


formatted properly or not.

3.Every time we have to check whether we are using right


parsing mechanism or not to access the data from XML
document.

4.First Developers must aware XML tech.

To Overcome all the above problems,we have to use Java


alternative that is "Annotation".

Ex:

Servlet Configuration with XML document:

web.xml

<web-app>

<servlet>

<servlet-name>ls</servlet-name>

<servlet-class>LoginServlet</servlet-name>

</servlet>

<servlet-mapping>
<servlet-name>ls</servlet-name>

<url-pattern>/login</url-pattern>

</servlet-mapping>

</web-app>

Servlet Configuration with Annotation

@WebServlet("/login")

public class LoginServlet extends HttpServlet{

XML-Based Tech Annotation Based Tech

JDK1.4 JDK5.0

JDBC3.0 JDBC4.0

Servlets2.5 Servlets3.0
Struts1.x Struts2.x

JSF1.x JSF2.x

Hiberante3.2.4 Hibernate3.5

EJBs2.x EJBs3.x

Spring2.x Spring3.x

NOTE:Annotations are not the complete alternative for XML


tech,with in a Java application we can use annotations as
an alternative for XML documents but when we go for
distributed applications where applications are designed
on different tech.standards there annotations are not
possible,only we have to use XML tech.

 To process the annotations,Java has provided a predefined


tool in the form of "Annotation Processing tool"[APT},it was
managed by Java upto JAVA7 version,it was removed from
Java in JAVA8 version.

Syntax to declare annotation:

@interface Annotation_Name{

data_Type member_Name() [default] value;

Syntax to use Annotation:

@Annotation_Name(member_name1=value1,member_Name2=v
alue2.........)

 In Java,all the annotations are interfaces by default.


 In Java,the common and default super type for all the
annotations is "java.lang.annotation.Annotation".
 As per the no.of members inside annotations,there are three
types of annotations.

1.Marker Annotations:

It is an annotation with out members.

Ex:
@interface Override{

2.Single-Valued Annotation:

It is an Annotation with exactly one single member

Ex:

@interface SuppressWarnings{

String value();

3.Multi-Valued Annotation:

It is an annotation with more than one member.

Ex:

@interface WebServlet{

int loadOnStartup();

String[] urlPatterns();

-----

In Java Annotations are divided into the following two types as


per their nature.

1.Standard Annotations

2.Custom Annotations
1.Standard Annotations:

These are predefined Annotations provided by Java along with


Java software.

There are two types of Standard Annotations

1.General Purpose Annotations

2.Meta Annotations

1)General Purpose Annotations:

These Annotations are commonly used Annotations in Java


applications

These Annotations are provided by Java as part of java.lang


package.

Ex:

@Override

@Deprecated

@SuppressWarnings

@FunctionalInterface [JAVA 8]

2)Meta Annotations:

These Annotations can be used to define another Annotations.

These Annotations are provided by Java as part of


java.lang.annotation package.
Ex:

@Inherited

@Documented

@Target

@Retention

1.@Override:

 In Java applications if we want to perform method overriding


then we have to provide a method in subclass with the same
prototype of super class method.
 While performing method Overriding,if we are not providing
the same super class method at sub class method then
compiler will not rise any error and JVM will not rise any
exception,JVM will provide super class method output.

 In the above context,if we want to get an error about to


describe failure case of method overriding from compiler
then we have to use @Override

Ex:

class JdbcApp

public void getDriver(){

System.out.println("Type-1 Driver");

}
class New_JdbcApp extends JdbcApp

@Override

public void getdriver(){

System.out.println("Type-4 Driver");

class Test

public static void main(String args[]){

JdbcApp app=new New_JdbcApp();

app.getDriver();

 If we compile the above programme then compiler will rise


an error like "method does not override or implement a
method from a SuperType".

NOTE:If we compile the above programme,compiler will


recognize @Override annotation,compiler will take sub
class method name which is marked with @Override
annotation,compiler will comparesub class method name
with all the super class method names.If any method name
is matched then compiler will not rise any error.If no super
class method name is matched with sub class method
name then compiler will rise an error.
@Deprecated:

 The main intention of this annotation is to make a method


as deprecated method and to provide deprecation message
when we access that deprecated method.
 In general,Java has provided Deprecation support for only
predefined methods,if we want to get deprecation support
for the user defined methods we have to use @Deprecated
annotation.

NOTE:Deprecated method is an outdated method


introduced in the initial versions of Java and having
alternative methods in the later versions of Java.

class Employee{

@Deprecated

public void gen_Salary(int basic,float hq){

System.out.println("Salary is calculated on the basis of basic


amount,hq");

public void gen_Salary(int basic,float hq,int ta,float pf){

System.out.println("Salary is calculated on the basis of basic


amount,hq,ta,pf");
}

class Test{

public static void main(String args[]){

Empoloyee emp=new Employee();

emp.gen_Salary(25000,20.0f);

Note:If we compile the above code then compiler will


provide the following deprecation message "Note:java
uses or overrides a deprecated API"

@SuppressWarnings(--):

In Java applications,when we perform unchecked or unsafe


operations then compiler will rise some warning messages.In this
context,to remove the compiler generated warning messages we
have to use @SuppressWarnings("unchecked") annotation.

Ex:

import java.util.*;

class Bank{

@SuppressWarnings("unchecked")

public ArrayList listCustomers(){


ArrayList al=new ArrayList();

al.add("chaitu");

al.add("Mahesh");

al.add("Jr NTR");

al.add("Pavan");

return al;

class Test{

public static void main(String args[]){

Bank b=new Bank();

List l=b.listCustomers();

System.out.println(l);

@FunctionalInterface:

 In Java,if we provide any interface with out abstract


methods then that interface is called as "Marker Interface".
 In Java,if we provide any interface with exactly one abstract
method then that interface is called as "Functional
Interface".
 To make any interface as Functional Interface and to allow
exactly one abstract method in any interface then we have
to use "@FunctionalInterface" annotation.
NOTE:This annotation is a new annotation provided by
JAVA8 version.

@FunctionalInterface

interface Loan{

void getLoan();

class GoldLoan implements Loan{

public void getLoan(){

System.out.println("GoldLoan");

class Test{

public static void main(String args[]){

Loan l=new GoldLoan();

l.getLoan();

@Inherited:

In general all the annotations are not inheritable by default.


If we want to make/prepare any annotation as Inheritable
annotation then we have to declare that annotation as Inheritable
annotation then we have to declare that annotation with

@Inherited annotation.

Ex:

@interface Persistable

@Persistable

class Employee

class Manager extends Employee{

In the above example,only Employee class objects are Persistable


i.e eligible to store in database.

@Inherited

@interface Persistable

@Persistable

class Employee{

}
class Manager extends Employee{

NOTE:In the above example,both Employee class objects


and manager class objects are Persistable i.e eligible to
store in database.

@Documented:

In Java,by default all the annotations are not documentable.

In Java applications,if we want to make any annotation as


documentable annotation then we have to prepare the respective
annotation with @Documented annotation.

Ex:

@interface Persistable

@Persistable

class Employee

javadoc Employee.java
If we prepare html documentation for Employee class by using
"javadoc" tool then @Persistable annotation is not listed in the
html documentation.

@Documented

@interface Persistable

@Persistable

class Employee

If we prepare html documentation for Employee class by using


"javadoc" tool then @Persistable annotation will be listed in the
html documentation.

@Target:

The main intention of this annotation is to define a list of target


elements to which we are applying the respective annotation.

Synatx:

@Target(--list of constants from ElementType enum---)

Where ElementType enum contains


FIELD,CONSTRUCTOR,METHOD,TYPE[Classes,abstract
classes,interfaces]
Ex:

@Target(ElementType.TYPE,ElementType.FIELD,ElementType.ME
THOD)

@interface persistable

@Persistable

class Employee

@Persistable

Account acc;

@Persistable

public Address getAddress(){}

@Retention:

The main intention of the annotation is to define life time of the


respective annotation in Java application.

Syntax:

@Retention(---a constant from RestentionPolicy enum---)


Where RestentionPolicy enum contains the constants like
SOURCE,CLASS,RUNTIME

@Retention(RetentionPolicy.RUNTIME)

@interface Persistable

@Persistable

class Employee

Custom Annotations:

 These are the annotations defined by the developers as per


their application requirements.
 To use custom annotations in java applications,we have to
use the following steps.

1)Declare user defined Annotation:

Bank.java

import java.lang.annotation.*;

@Inherited

@Documented
@Target(ElementType.TYPE)

@Retention(RetentionPolicy.RUNTIME)

@interface Bank

String name() default "ICICI Bank";

String branch() default "S R Nagar";

String phone() default "040-123456";

2)Utilize User defined Annotations in Java applications:

Account.java

@Bank(name="Axis Bank",phone="040-987654")

public class Account{

String accNo;

String accName;

String accType;

public Account(String accNo,String accName,String accType){

this.accNo=accNo;

this.accName=accName;

this.accType=accType;

public void getAccountDetails(){


System.out.println("Account Details");

System.out.println("----------------");

System.out.println("Account Number:"+accNo);

System.out.println("Account Name :"+accName);

System.out.println("Account Type :"+accType);

3)Access the data from User-Defined Annotation in main Application:

1)If the annotation is class level annotation then use the following
steps:

a)Get java.lang.Class object of the respective class

b)Get Annotation object by using getAnnoataion(Class c)


method

2)If the annotation is Field level annotation then use the following
steps:

a)Get java.lang.Class object of the respective class

b)Get java.lang.reflect.Field class object of the respective


variable from java.lang.Class by using getField(String field_name)
method

c)Get Annotation object by using getAnnotation(Class c)


method from java.lang.reflect.Field class.

3)If the annotation is Method level annotation then use the


following steps:
a)Get java.lang.Class object of the respective class

b)Get java.lang.reflect.Method class object of the respective


Method from java.lang.Class by using getMethod(String
method_name) method

c)Get Annotation object by using getAnnotation(Class c)


method from java.lang.reflect.Method class.

MainApp.java

import java.lang.annotation.*;

import java.lang.reflect.*;

public class MainApp{

public static void main(String args[])throws Exception{

Account acc=new Account("abc123","Durga","Hyd");

acc.getAccountDetails();

System.out.println();

Class c=acc.getClass();

Annotation ann=c.getAnnotation(Bank.class);

Bank b=(Bank)ann;

System.out.println("Bank Details");

System.out.println("------------");

System.out.println("Bank Name :"+b.name());

System.out.println("Branch Name :"+b.branch());

System.out.println("Phone "+b.phone());
}

NOTE:class Level Annotation

Method Level Annotation

Course.java:

import java.lang.annotation.*;

@Inherited

@Documented

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)

@interface Course{

String cid() default "C-111";

String cname() default "Java";

int ccost() default 5000;

Student.java:

public class Student{

String sid;

String sname;

String saddr;
public Student(String sid,String sname,String saddr){

this.sid=sid;

this.sname=sname;

this.saddr=saddr;

@Course(cid="C-222",cname=".NET")

public void getStudentDetails(){

System.out.println("Student Details");

System.out.println("---------------");

System.out.println("Student Id :"+sid);

System.out.println("Sudent Name :"+sname);

System.out.println("Student Address:"+saddr);

ClientApp.java

import java.lang.annotation.*;

import java.lang.reflect.*;

public class ClientApp{

public static void main(String args[])throws Exception{

Student std=new Student("S-111","Durga","Hyd");

std.getStudentDetails();
System.out.println();

Class cl=std.getClass();

Method m=cl.getMethod("getStudentDetails");

Annotation ann=m.getAnnotation(Course.clas);

Course c=(Course)ann;

System.out.println("Course Details");

System.out.println("---------------");

System.out.println("Course Id :"+c.cid());

System.out.println("Course Name :"+c.cname());

System.out.println("Course Cost :"+c.ccost());

Inner Classes:
 Declaring a class inside a class is called as an Inner Class.
 In Java applications,Inner classes are able to provide the
following Advantages.

1.Modularity

2.Abstraction

3.Share-ability

4.Security
5.ReUseAbility

1.Modularity:

 If we declare an Inner class inside a class then that inner


class is treated as a module of that entity class.

Ex:

class Account{

class StudentAccount{

class EmployeeAccount{

class LoanAccount{

2.Abstraction:

 If we declare any variable or method inside an inner class


then that variable and method will have scope upto the
respective inner class only,which are not available to outside
of that inner class.

3.Security:

 In Java applications,private keyword is able to improve


security.In Java applications,it is not possible to declare a
class as private but it is possible to declare an inner class as
private.Therefore Inner classes are able to improve security.

4.Share-ability:

 In Java applications,static keyword is able to improve share-


ability.
 In Java applications,it is not possible to declare a class as
static but it is possible to declare an inner class as
static.Therefore inner classes are able to improve share-
ability.

5.ReUseAbility:

 In Java applications,inheritance is able to improve


ReuseAbility.In Java applications,it is possible to extend one
inner class to another inner class,so that,inner classes are
able to improve ReuseAbility.

Types of Inner classes:

There are four types of Inner classes in Java.

1.Member Inner class

2.Static Inner class

3.Method Local Inner class

4.Anonymous Inner class.

1.Member Inner class:

 Declaring a non-static class inside a class is called as


Member Inner class.
class Outer{

class Inner{

----

----

 If we want to access members of member Inner class then


we have to create an Object for the respective member
inner class.To create object for member inner class,we have
to use the following syntax.

Outer.Inner ref_Var=new Outer.new Inner();

 In the case of member Inner classes,by using outer class


reference variable we are able to access only outer class
members,it is not possible to access inner class members.
 In the case of member Inner classes by using Inner class
reference variables we are able to access only inner class
members,it is not possible to access outer class members.
 In the case of member inner classes,all the outer class
members are available to inner classes automatically but all
the inner class members are not available to outer classes.
 In general,inner classes are not allowing static
declarations,but inner classes are able to allow 'static'
keyword along with 'final' keyword.

Example programme on Member Inner class:

class A{

int i=10;
void m3(){

System.out.println("m3-A");

//System.out.println(j);---->error

class B{

int j=20;

//static int k=30;--->error

static final int k=30;

void m1(){

System.out.println("m1-B");

System.out.println(i);

void m2(){

System.out.println("m2-B");

class Test{

public static void main(String args[]){

A.B ab=new A().new B();

ab.m1();

ab.m2();
//ab.m3();--->error

A a=new A();

a.m3();

//a.m1();--->error

//a.m2();--->error

In the case of member inner classes,we are able to define


inheritance relation in the following cases:

Diagram(OOPS--INNERCLASSES1.png)

Q)Is it possible to provide an interface inside a class?

 Ans:Yes,it is possible to provide an interface inside a class


but the respective implementation class must be provided in
the same outer class.

Example programme on,to provide an interface inside a class :

class A{

interface I{

void m1();

void m2();

class B implements I{

public void m1(){

System.out.println("m1-B");
}

public void m2(){

System.out.println("m2-B");

class Test{

public static void main(String args[]){

A.I ai=new A().new B();

ai.m1();

ai.m2();

2.Static Inner class:

 Declaring Static class inside a class is called as Static Inner


class.

class Outer{

static class Inner{

 If we want to access the members of static inner classes


then we have to create object for the static inner class.
Outer.Inner ref_Var=new Outer.Inner();

 In general inner classes will allow all the members of outer


classes directly but static inner classes are able to allow only
static members of the outer class,it will not allow non-static
members of the outer class.
 In general,inner classes will not allow static declarations but
static inner classes are able to allow the static declarations.

Example programme on Static Inner classes:

class A{

int i=10;

static int j=10;

static class B{

void m1(){

System.out.println("m1-B");

//System.out.println(i);---->error

System.out.println(j);

void m2(){

System.out.println("m2-B");

static void m3(){

System.out.println("m3-B");

}
}

class Test{

public static void main(String args[]){

A.B ab=new A.B();

ab.m1();

ab.m2();

A.B.m3();

Q)Is it possible to provide a class inside an Interface?

 Ans:Yes,it is possible to declare a class inside an interface.If


we declare a class inside an interface then that class is
becoming as static inner class,where we can access the
members like static inner class members.

interface I{

class A{

void m1(){

System.out.println("m1-A");

void m2(){

System.out.println("m2-A");

}
}

class Test{

public static void main(String args[]){

I.A ia=new I.A();

ia.m1();

ia.m2();

3.Method local Inner Class:

 Declaring a class Inside a method is called as Method Local


Inner class.
 If we declare a class inside a method then that class is
having scope upto the respective method.
 In the case of method local Inner classes,we have to create
object for the Inner class and we have to access members of
the inner class inside the respective method only.

Example Programme on Method local Inner Class:

class A{

void m1(){

class B{

void m2(){

System.out.println("m2-B");

void m3(){
System.out.println("m3-B");

B b=new B();

b.m2();

b.m3();

class Test{

public static void main(String args[]){

A a=new A();

a.m1();

4.Anonymous Inner class:

 In general,in Java applications,if we declare any abstract


class with abstract methods then we have to take a sub
class for the abstract class,where we have to provide
implementation for all the abstract methods.
 In the case of interfaces,we have to take an implementation
class and we have to provide implementation for all the
abstract methods declared in the interface.
 In the above two cases,subclasses or implementation
classes may allow their own methods and if we create object
for sub class or implementation class then that object may
have the respective sub class identity or implementation
class identity.
 In Java applications,if we want to provide implementations
for abstract classes and interfaces with out allowing extra
methods and if we want to create object with abstract class
identity and with interface identity then we have to use
"Anonymous Inner Class".

Syntax:

abstract className / Interface Name

---abstract methods---------

class Outer{

Name ref_Var=new Name(){

-----impl for abstract methods-------

};

Example programme on Anonymous Inner class for Interface:

interface I{

void m1();

void m2();
}

class A{

I i=new I(){

public void m1(){

System.out.println("m1-A");

public void m2(){

System.out.println("m2-A");

};

class Test{

public static void main(String args[]){

A a=new A();

a.i.m1();

a.i.m2();

Example programme on Anonymous Inner class for Abstract Class:

abstract class A{

void m1(){
System.out.println("m1-A");

abstract void m2();

abstract void m3();

class B{

A a=new A(){

void m2(){

System.out.println("m2-AIC");

void m3(){

System.out.println("m3-AIC");

};

class Test{

public static void main(String args[]){

B b=new B();

b.a.m1();

b.a.m2();

b.a.m3();
}

Utilization of Anonymous Inner class:

 In Java applications,when we have any requirement to pass


interface or abstract class references as parameters to the
methods then we have to pass anonymous Inner class as
parameter to the methods instead of taking implementation
classes and their references values.

Ex:

class MyFrame extends Frame{

MyFrame(){

this.addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we){

System.exit(0);

});

}}

Example programme on Utilization of Anonymous Inner class:

interface I{

void m1();

class B{
void m2(I i){

System.out.println("m2-B");

i.m1();

class Test{

public static void main(String args[]){

B b=new B();

b.m2(new I()

public void m1(){

System.out.println("m1-AIC");

});

NOTE:Passing Anonymous Inner class as parameter to the


methods is suggestable only in the case of less no.of
abstract methods in side the interface.If the interface
contains more no.of methods then it is suggestable to use
implementation class approach.
Packages:

 Package is a collection of related classes and interfaces as a single


unit.

--diagram--(Packages.png)[package1]

 Package is a folder contains .class files representing related classes


and interfaces.

--diagram--(Packages.png)[package2]

In Java applications,packages will provide the following advantages.

1.Modularity:

 In enterprise application development,we will prepare modules by


declaring packages only,so that,packages will improve modularity.

2.Abstraction:

 If we declare classes and interfaces in a package then that classes and


interfaces are not visible in out side,so that,packages will provide
abstraction.

3.Security:

 In Java applications,packages will provide abstraction and


encapsulation so that packages will provide security.

Security=Encapsulation+Abstraction
4.Sharability:

 In Java applications,if we declare one package then we can share that


package to any no.of modules at a time.

5.Reusability:

 In Java applications,if we declare a package one time then that we can


reuse any no. of times at any module.

--diagram--(Pacakages1.png)

There are two types of packages in Java.

1.Predefined packages

2.User defined packages

1.Predefined Packages:

 These are the packages defined by Java programming language along


with Java software.

Ex:

1.java.lang:

 It is a default package in every java file,no need to import this


package.
 java.lang package contains the basic classes and interfaces which are
required for basic Java applications.
 java.lang.package contains the classes and interfaces like

String,StringBuffer,StringBuilder

Thread,Runnable

Exception,ArithmeticException,NullPointerException.....
Byte,Short,Integer,Long....

Object,Cloneable,Comparable...........

2.java.io:

 This package contains all the predefined classes and interfaces which
are required to perform,IO Operations in Java.

This package contains the predefined classes and interfaces like

InputStream,ByteArrayInputStream,FileInputStream....

OutputStream,ByteArrayOutputStream,FileOutputStream...

Reader,FileReader,InputStreamReader,BufferedReader.....

Writer,FileWriter,BufferedWriter......

Serializable,Externalizable...........

3.java.util:

 This package will provide all the predefined classes and interfaces to
represent data structures in java applications.

This package will provide the predefined classes and interfaces like
List,ArrayList,Vector,Stack,LinkedList

Set,HashSet,LinkedHashSet,TreeSet,NavigableSet,SortedSet,

Map,HashMap,

LinkedHashMap,TreeMap,NavigableMap....

4.java.awt:
 This package will provide all the predefined classes and interfaces to
design GUI applications.

This package contains the classes and interfaces like

Component,Label,TextFiled,TextArea,Button,Check box,List..

FlowLayout,BorderLayout,GridLayout,GridBagLayout,CardLayout....

5.javax.swing:

 This package will provide predefined classes and interfaces to design


GUI applications.

javax.swing package is able to provide no.of GUI components which


are light weight GUI components, platform independent GUI
components,able to consume less memory and less execution time...

when compared with AWT provided GUI components.

This package contains the predefined classes and interfaces like

JComponent,JTextField,JLabel,JButton,JPasswordField,JList,JCheckBox,
JRadioButton,JColorChooser, JFileChooser.....

6.java.net:

 This package will provide all the predefined classes and interfaces to
prepare Distributed applications.

This package will provide the predefined classes and interfaces like
Socket, ServerSocket, URL, URLConnection, INetAddress

7.java.sql:

 This package will provide predefined classes and interfaces to prepare


JDBC applications.

This package will provide the predefined classes and interfaces like

Driver
DriverManager

Connection

Statement

PreparedStatement

CallableStatement

ResultSet

2.User Defined packages:

 These are the packages defined by the developers as per their


application requirements.

To declare user defined packages in Java applications,we have to use


the following syntax.

package package_Name;

where package declaration statement should be first statement in Java


file after comment section.

NOTE:It is not possible to provide more than one package


declaration statement with in a single java file.

Where package name should be unique,it should not be duplicated and


it should not be shareable.

To provide package names,Java has given a convention like to include


our company domain name in reverse.

EX:

package com.durgasoft.axis.loan;

com.durgasoft-->Company Domain name in reverse

axis-->Client name/project name

loan-->module name
 If we want to use a particular package content in present java file then
we have to import the respective package in present java file.
 To import a package in java file,we have to use the following syntax.

import package_Name.*;

 It will import all the classes and interfaces from the specified package.

Ex:import java.util.*;

import package_Name.Member_Name;

 It will import only the specified member from the specified package.

Ex:import java.util.ArrayList;

Example:

D:\abc

Employee.java

C:\abc

com

|----durgasoft

|------core

|----Employee.class

D:\java7

MainApp.java

D:\abc\Employee.java:

package com.durgasoft.core;(D:\abc\Employee.java)

public class Employee{

String eid;
String ename;

String eaddr;

public Employee(String eid,String ename,String eaddr){

this.eid=eid;

this.ename=ename;

this.eaddr=eaddr;

public void displayEmployee(){

System.out.println("Employee Details");

System.out.println("-----------------");

System.out.println("Employee Id :"+eid);

System.out.println("Employee Name :"+ename);

System.out.println("Employee Address :"+eaddr);

compilation:D:\abc>javac -d c:\abc Employee.java

D:\java7\MainApp.java:

import com.durgasoft.core.*;

public class MainApp{

public static void main(String args[]){

Employee emp=new Employee("E-111","Durga","Hyd");

emp.displayEmployee();
}

compilation:D:\java7>set classpath=C:\abc;.;

D:\java7>javac MainApp.java

D:\java7>java MainApp

jar files in Java:

As part of Java applications development,after implementing the java


application it is not suggestable to send the application in the form of .class
files individually to the clients.

Always,it is suggestable to manage the generated .class files in the form of


jar[Java Archive] files and it is suggestable to send that jar files to the
clients or to the customers.

To prepare jar file in java applications,we have to use the following


command on command prompt.

jar -cvf file_name.jar *.*

CVF --->Create Verboz file

*.* --->all files and folders

To extract jar file,we have to use the following command.

jar -xvf file_Name.jar

If we want to use the content of jar file in our java application then we have
to set "classpath" environment variable to jar file.

D:\abc

Employee.java

Student.java
C:\abc

com

|-----durgasoft

|-------emp

| |----Employee.class

|-------std

| |----Student.class

C:\xyx

durga.jar

D:\java7

MainApp.java

MainApp.class

D:\abc\Employee.java:

package com.durgasoft.emp;

public class Employee{


String eid;

String ename;

String eaddr;

public Employee(String eid,String ename,String eaddr){

this.eid=eid;

this.ename=ename;

this.eaddr=eaddr;

public void displayEmployee(){

System.out.println("Employee Details");

System.out.println("-----------------");

System.out.println("Employee Id :"+eid);

System.out.println("Employee Name :"+ename);

System.out.println("Employee Address :"+eaddr);

D:\abc\Student.java:

package com.durgasoft.std;

public class Student{

String sid;

String sname;

String saddr;

public Student(String sid,String sname,String saddr){


this.sid=sid;

this.sname=sname;

this.saddr=saddr;

public void displayStudent(){

System.out.println("Student Details");

System.out.println("----------------");

System.out.println("Student Id :"+sid);

System.out.println("Student Name :"+sname);

System.out.println("Student Address :"+saddr);

Compilation Process:

D:\abc>javac -d C:\abc *.java

C:\abc>jar -cvf durga.jar *.*

Copy the generated durga.jar from C:\abc and past at C:\xyz location for
testing purpose.

D:\java7\MainApp.java

import com.durgasoft.emp.*;

import com.durgasoft.std.*;

public class MainApp{

public static void main(String args[]){

Employee emp=new Employee("E-111","Durga","Hyd");


emp.displayEmployee();

System.out.println();

Student std=new Student("S-111","Anil","Sec");

std.displayStudent();

Compilation Process:

D:\java7>set classpath=C:\xyz\durga.jar;.;

D:\java7>javac MainApp.java

D:\java7>java MainApp

In Java applications,when we create a Jar file,jar command will provide


MANIFEST.MF file under META-INF folder inside jar file along with our
current location content.Here MANIFEST.MF file is able to store the data
about jar file in the form of key-value pairs.

Ex:

D:\abc> jar -cvf durga.jar *.*

Diagram(Packages2.png)

Steps to prepare Executable jar file and batch file:

Executable Jar file is a jar file which contains main class directly.

1)Prepare java application as per the requirement.

D:\abc\MainApp.java

import java.awt.*;

class LogoFrame extends Frame{


LogoFrame(){

this.setVisible(true);

this.setSize(700,500);

this.setTitle("Logo Frame");

this.setBackground(Color.green);

public void paint(Graphics g){

Font f=new Font("airal",Font.BOLD+Font.ITALIC,35);

g.setFont(f);

this.setForeground(Color.red);

g.drawString("DURGA SOFTWARE SOULTIONS",50,100);

class MainApp{

public static void main(String args[]){

LogoFrame lf=new LogoFrame();

2)Prepare a text file with "Main-Class" attribute:

D:\abc\abc.txt

Main-Class:MainApp

The main intention to prepare this text file is to keep Main-Class attribute
data in the generated MANIFEST.MF file.

3)Compile Java file and prepare jar file with user provided data in
MANIFEST.MF file:
Syntax:

jar -cvfm file_Name.jar file_name.txt *.*

Ex:

D:\abc>javac MainApp.java

D:\abc>jar -cvfm durga.jar abc.txt *.*

When we execute the above command on command prompt then "jar"


command will prepare jar file with MainApp.class and MANIFEST.MF file with
"Main-Class:MainApp" attribute data.

4.Execute jar file:

To execute jar file directly we have to use the following command.

java -jar file_name.jar

EX:

D:\abc>java -jar durga.jar

If we use the above command on command prompt then JVM will perform
the following actions

a)JVM will search for durga.jar file at current location

b)If durga.jar file is available then JVM will goto META-INF folder and
recognize MANIFEST.MF file.

c)JVM will get "Main-Class" attribute value from MANIFEST.MF file that is
main class name that is "MainApp".

d)JVM will search for main class .class file inside durga.jar file

e)If MainApp.class file is available in durga.jar file then JVM will execute
main class.

Diagram(Packages3.png)

If we want to execute the above application with batch file then we have to
prepare batch file with the required "java" command,keep both batch file
and jar file at the same location and double click on batch file.
Reflection API:
1.Introduction

2.Class

3.Method

4.Field

5.Constructor

Reflection:

 The process of analyzing all the capabilities of a particular


class at runtime is called as "Reflection".
 Reflection API is a set of predefined classes provided by Java
to perform reflection over a particular class.
 Reflection API is not useful in projects
development,reflection API is useful in products
development like
Compilers,JVM's,Server's,IDE's,FrameWork's.....
 Java has provided the complete predefined library for
Reflection API in the form of "java.lang" package and
"java.lang.reflect" package.

java.lang

Class

java.lang.reflect

Field

Method
Constructor

Package

Modifier

---

---

java.lang.Class:

 This class can be used to represent a particular class


metadata which includes class name,super class
details,implemented interfaces details,access modifiers......
 To get the above class metadata,first we have to create
Class Object for the respective class.
 There are three ways to create object for java.lang.Class

1.Using forName(--) method:

 forName() method is defined in java.lang.Class to load a


particular class bytecode to the memory and to get
metadata of the respective loaded class in the form of Class
object.
 public static Class forName(String class_Name) throws
ClassNotFoundException

class c=Class.forName("Employee");

when JVM encounter the above instruction,JVM will perform the


following actions.

a)JVM will take provided class from forName() method.

b)JVM will search for its .class file at current location,at java
predefined library and at the locations refefered by "classpath"
environment variable.
c)If the required .class file is not available at all the above
locations then JVM will rise an exception like
"java.lang.ClassNotFoundException".

d)If the required .class file is available at either of the above


locations then JVM will load its bytecode to the memory.

e)After loading its bytecode to the memory,JVM will collect the


respective class metadata and stored in the form of
java.lang.Class object.

2.Using getClass() method:

 In Java applications,if we create object for any class then


JVM will load the respective class bytecode to the
memory,JVM will get metadata of the respective class and
stored in the form of java.lang.Class object.
 In the above context,to get the generated Class object,we
have to use the following method from java.lang.Object
class.
 public Class getClass()

Ex:

Employee e=new Employee();

Class c=e.getClass();

3.Using .class file name:

 In Java,every .class file is representing a java.lang.Class


Object,it will manage the metadata of the respective class.
Ex:

Class c=Employee.class

 To get name of the class,we have to use the following


method.

public String getName()

 To get super class metadata in the form of Class object,we


have to use the following method.

public Class getSuperclass()

 To get implemented interfaces metadata in the form of


Class[] we have to use the following method.

public Class[] getInterfaces()

 To get the sepcified access modifiers list,we have to use the


following method.

public int getModifiers()

Ex:

int val=c.getModifiers()

String modifiers=Modifier.toString(val);

import java.lang.reflect.*;

public abstract class Employee implements


java.io.Serializable,java.lang.Cloneable{

class Test{

public static void main(String args[]) throws Exception{

Class c1=Clas.forName("Employee");
System.out.println(c1.getName());

Employee e=new Employee();

Class c2=e.getClass();

System.out.println(c2.getName());

Class c3=Employee.class;

System.out.println(c3.getName());

Class c=Class.forName("Employee");

System.out.println("Class Name :"+c.getName());

System.out.println("Super Class
:"+c.getSuperclass().getName());

Class[] cls=c.getInterfaces();

System.out.println("Interfaces :");

for(int i=0;i<cls.length;i++){

Class cl=cls[i];

System.out.println(cl.getName()+" ");

System.out.println();

int val=c.getModifiers();

System.out.println("Modifers :"+Modifier.toString(val));

}
java.lang.reflect.Field:

 This class can be used to get the metadata of a particular


variable which contains the name of the variable,data type
of the variable,access modifiers of the variable and value of
the variable.
 If we want to get all the variables metadata of a particular
class first we have to get java.lang.Class object.After getting
Class object,we have to get all the variables metadata in the
form Field[].
 To get all the variables metadata in the form of Field[],we
have to use the following two methods.

public Field[] getFields()

 This method will return all the variables metadata which are
declared as public in the respective class and in the super
class.

public Field[] getDeclaredFields()

 This method will return all the variables metadata which are
available in the respective class only irrespective of public
declaration.
 To get name of the variable,we have to use the following
method.

public String getName()

 To get datatype of the variables,we have to use the


following method.

public Class getType()

 To get value of the variable,we have to use the following


method.
public Object get(Field f)

 To get access modifiers of a variable,we have to use the


following method.

public int getModifiers()

public static String toString(int val)

import java.lang.reflect.*;

class Employee{

public static String eid="E-111";

public static String ename="Durga";

public static String eaddr="Hyd";

class Test{

public static void main(String args[])throws Exception{

Class c=Employee.class;

Field[] flds=c.getDeclaredFields();

for(int i=0;i<flds.length;i++){

Field f=flds[i];

System.out.println("Field Name :"+f.getName());

System.out.println("data Type :"+f.getType().getName());

System.out.println("value :"+f.get(f));

int val=f.getModifiers();
System.out.println("Modifiers :"+Modifier.toString(val));

System.out.println("----------------------------------------");

java.lang.Method:

 This class can be used to represent the metadata of a


particular method,which includes method name,return
type,parameter types,access modifiers and exception types
 If we want to get all the methods metadata in the form of
method[],first we have to get java.lang.Class object then we
have to use either of the following methods.

public Method[] getMethods()

 It can be used to get all the methods metadata which are


declared as public in the respective class and in the super
class.

public Method[] getDecalredMethods()

 It can be used to get all the methods metadata which are


available in the respective class irrespective of public
declaration.
 To get method name,we have to use the following method.

public String getName()

 To get method return type,we have to use the following


method.

public Class getReturnType()


 To get parameter data types,we have to use the following
method.

public Class[] getParameterTypes()

 To get Exception types which are specified along with


"throws" keyword then we have to use the following method.

public Class[] getExceptionTypes()

 To get Access modifier of a particular class,we have to use


the following method.

public int getModifers()

public static String toString(int value)

import java.lang.reflect.*;

class Employee{

public void create(String eid,String ename,String eaddr)throws


ClassNotFoundException,NullPointerException{

public void search(String eid)throws ClassCastException

{}

public void delete(String eid)throws


ClassCastException,ClassNotFoundException

{}

class Test{

public static void main(String args[])throws Exception{

Class c=Employee.class;
Method[] mthds=c.getDeclaredMethods();

for(int i=0;i<mthds.length;i++){

Method m=mthds[i];

System.out.println("Method Name :"+m.getName());

System.out.println("Return Tyep :"+m.getreturnType());

int val=m.getModifiers();

System.out.println("Modifiers :"+modifier.toString(val));

Class[] cls=m.getParameterTypes();

System.out.println("Parametes :");

for(int j=0;j<cls.length;j++){

Class cl=cls[j];

System.out.println(cl.getName()+" ");

System.out.println();

Class[] cls1=m.getExceptionTypes();

System.out.println("Exception Types :");

for(int j=0;j<cls1.length;j++){

Class cl1=cls1[j];

System.out.println(cl1.getName()+" ");

System.out.println();

System.out.println("-----------------------------");
}

java.lang.reflect.Constructor:

 This class can be used to get metadata of a particular


constructor.
 To get all the constructors metadata of a particular class first
we have to get Class object then we have to use the
following methods.

public Constructor[] getConstructors()

 It will return only public constructors details from the


respective class.

public Constructor[] getDeclaredConstrctors()

 It will return all the constructors metadata of the respective


class irrespective of their public declaration.
 Constructor class has provided the following methods to get
constructor data.

public String getName()

public Class[] getParameterTypes()

public Class[] getExceptionTypes()

public int getModifiers()

public static String toString(int val)

program is same as java.lang.reflect.Method program with the


above methods
import java.lang.reflect.*;

class Employee{

public Employee(String eid,String ename,String eaddr)throws


ClassNotFoundException,NullPointerException{

public Employee(String eid,String ename)throws


ClassCastException{

public Employee(String eid)throws


ClassCastException,ClassNotFoundException{

class Test{

public static void main(String args[])throws Exception{

Class c=Employee.class;

Constructor[] con=c.getDeclaredConstructors();

for(int i=0;i<con.length;i++){

Constructor constructor =con[i];

System.out.println("Constructor Name
:"constructor.getName());

int val=constructor.getModifiers();

System.out.println("Modifiers :"+Modifier.toString(val));

Class[] cls=constructor.getParameterTypes();
System.out.println("Parametes :");

for(int j=0;j<cls.length;j++){

Class cl=cls[j];

System.out.println(cl.getName()+" ");

System.out.println();

Class[] cls1=constructor.getExceptionTypes();

System.out.println("Exception Types :");

for(int j=0;j<cls1.length;j++){

Class cl1=cls1[j];

System.out.println(cl1.getName()+" ");

System.out.println();

System.out.println("-----------------------------");

}
Wrapper Classes:
 Collection is an object,it able to store a group of some other
Objects.
 In Java all the Collection Objects are represented in the form
of some predefined library in "java.util" package.
 In java applications,Collection objects never be stored data
directly,Collection objects are able to store data in the form
of objects only.
 If we want to store data in Collection objects,first we have to
convert primitive data into object type then we have to store
object type in Collection object.
 If we want to retrieve data from Collection object,first we
have to retrieve the respective object type from Collection
then we have to convert data from Object type to the
respective primitive data type.
 In the above context,to convert the primitive data into its
Object form and to convert the data from Object form to the
respective Primitive data type we have to use a set of
predefined classes called as "Wrapper Classes".

-----Diagram----(CollectionObject.png)

 Java has provided all the wrapper classes w.r.t the primitive
data types as part of "java.lang" package.

-------Diagram----(WrapperClassesDiagram.png)

 Java has provided all the wrapper classes as immutable


classes,whose objects will not allow modifications on their
content.
1.If we want to convert the data from primitive type to its
object type or wrapper type then we have to use the
following approaches.

a)Using Wrapper classes constructors:

To convert the data from primitive type to its respective


wrapper type we have to use the following constructors from
each and every wrapper class.

public XXX(xxx var)

Where XXX may be Byte,Short,Integer.................

Where xxx may be byte,short,int.........

public Byte(byte b)

public Short(short s)

public Integer(int i)

Ex:

int i=10;

Integer in=new Integer(i);

System.out.println(i+" "+in);

O/P: 10 10

b)Using valueOf(--) method:

To convert the data from primitive data type to its object type
then each and every wrapper class has provided the following
method.
public static XXX valueOf(xxx var)

Ex:

public static Byte valueOf(byte b)

public static Short valueOf(short s)

public static Integer valueOf(int i)

----

----

Ex:

int i=10;

Integer in=Integer.valueOf(i);

System.out.println(i+" "+in);

O/P: 10 10

c)Using Auto-Boxing mechanism:

To convert the data from primitive type to its corresponding


Object type,JDK5.0 version has given a direct mechanism like to
assign primitive variable to the respective wrapper type variable
called as "Auto-Boxing".

Ex:

int i=10;

Integer in=i;

System.out.println(i+" "+in);

O/P: 10 10
2)If we want to convert the data from Wrapper type to primitive
type then we have to use the following approaches:

a)Using xxxValue() method:

To convert the data from wrapper type to its respective primitive


data type,Each and every wrapper class has provided the
following method.

public xxx xxxValue()

Where xxx may be byte,short,int,...........

public byte byteValue()

public short shortValue()

public int intValue()

-------------

-------------

Ex:

Integer in=new Integer(10);

int i=in.intValue();

System.out.println(in+" "+i);

O/P: 10 10

b)Using Auto-Unboxing Mechanism:

To convert the data from Wrapper type to primitive type,JDK5.0


version has provided a direct mechanism like to assign wrapper
type variable to the respective primitive type variable called as
"Auto-Unboxing".

Ex:

Integer in=new Integer(10);

int i=in;

System.out.println(in+" "+i);

O/P:10 10

3)If we want to convert the data from String data type to


wrapper type then we have to use the following approaches

a)Using Constructor from Wrapper Classes:

To convert the data from String type to the respective wrapper


type,all the wrapper classes have provided the following
constructors.

public XXX(String data)

public Byte(String data)

public Short(String data)

public Integer(String data)

Ex:

String data="10";

Integer in=new Integer(data);

System.out.println(data+" "+in);

O/P: 10 10
b)Using valueOf(---) method:

To convert the data from String data type to the respective


wrapper type,all most all the wrapper classes have provided the
following method.

public static XXX valueOf(String data)

public static Byte valueOf(String data)

public static Short valueOf(String data)

public static Integer valueOf(String data)

Ex:

String data="10";

Integer in=Integer.valueOf(data);

System.out.println(data+" "+in);

O/P: 10 10

4)If we want to convert the data from Wrapper type to String


type then we have to use the following approaches:

a)Using toString() method:


To convert the data from wrapper type to String data
type,allmost all the wrapper classes have provided the following
method.

public String toString()

Ex:

Integer in=new Integer(10);

String data=in.toString();

System.out.println(in+" "+data);

O/P: 10 10

b)Using '+' operator:

In Java,if we concatinate any reference variable with "" then


internally JVM will access toString() method then the over all
resultant value is becoming as String.

Ex:

Integer in=new Integer(10);

String data=""+in;

System.out.println(in+" "+data);

O/P: 10 10

5)If we want to convert the data from String data type to the
respective primitive data type then we have to use the following
approaches:

a)Using parseXXX() method:


To convert the data from String data type to the respective
primitive type all most all the wrapper classes have provided the
following method.

public static xxx parseXXX(String data)

Where xxx may be byte,short,int.....

public static byte parseByte(String data)

public static short parseShort(String data)

public static int parseInt(String data)

------------

------------

Ex:

String data="10";

int i=Integer.parseInt(data);

System.out.println(data+" "+i);

6)If we want to convert the data from primitive data type to


String data type then we have to use the following approaches:

a)Using toString(--) method:

To convert the data from primitive data type to String data


type,allmost all the wrapper classes have provided the following
method.

public static String toString(xxx value)

Where xxx may be byte,short,int,......


Ex:

int i=10;

String data=Integer.toString(i);

System.out.println(i+" "+data);

O/P: 10 10

b)Using '+' operator:

If we concatenate any primitive variable with "" then that


primitive variable value is becoming as String value.

Ex:

int i=10;

String data=""+i;

System.out.println(i+" "+data);

O/P: 10 10

You might also like