Core J
Core J
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.
Java Details:
J2SE:[Core Java]
1)Introduction:
1)Java History
3)Java Features
2)Editor
3)language Fundamentals:
1)Tokens
2)Identifiers
3)Literals
4)KeyWords/Reserved WordS
5)Operators
3)Java Statements
4)Arrays
4)OOPS:
1)Types of Programming Languages
7)Class,Object,encapsulation,abstraction,inheritance,Pol,MP
9)class syntax
10)Method Syntax
11)Var-arg method.
15)Object Vs Instance
16)Constructors
1)Default 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
2)why public?
3)why static?
4)why void?
5)why main
9)is it posible to provide more than one main(--) method with in a single
java appl?
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
2)Assiciations
3)one-one
4)one-many
5)many-one
6)many-many
26)Types of inheritance
3)constructors in inheritance
5)super keyword
27)Poly Morphism
1)static PM
2)method oveloading
3)Dynamic PM
4)method overriding
31)"instanceof" operator
34)Object Cloning
1)Shallow Cloning
2)Deep Cloning
5)Inner classes:
1)Member 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
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
6)throw Vs throws
7)try-catch-finally
8)Custom Exceptions
10)Multi Thredding:
1)process Vs Proccessor Vs Procedure
4)Thread Design
5)Thread lifecycle
1)New/Born
2)Runnable
3)Running
4)Blocked
5)Dead
1)sleep()
2)join()
3)yield()
4)stop()
7)Daemon Thread
8)Synchronization
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
5)Socket Programming.
13)Collection Framework:
1)Collection Arch.
1)ArrayList
2)Vector
3)Stack
4)LinkedList
1)HashSet
2)LinkedHashSet
3)TreeSet
1)HashMap
2)Hashtable
3)Properties
4)TreeSet
1)Priority Queue
2)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,...
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.RMI Architecture
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.
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.
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.
Stack Output:
--------------------------------------------------
Ex:
s.push("A");
s.pop();
s.peep();
-----------------------------
To write less no.of instructions in a programming language,then that is called as tight coded
programming language.It achieving more complex requirements.
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.
Dec 1992:
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.
Java Evolutions:
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.
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
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>
Ex: java.util
java.io
java.net
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".
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".
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].
Compilation of JAVA
The process of getting variables and methods from one class to another class is called as
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:
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.
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 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.
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.
int b=20;
String str1="abc";
String str2="def";
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 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 has eliminated all the confusion oriented features like multiple inheritance,operator
overloading,pointers...
Java applications will take less memory and less execution time.
2.Object-Oriented:
Java is Object-Oriented Programming language,because it able to store the data in the form
of objects.
3.platform Independent:
4.Arch.Neutral:
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 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 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
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,
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:
1)To check use provided syntax voilations we must require compilation for Java program.
12.HighPerformance:
Java is a high performance programming language due to its rich set of features like
Robust,Dynamic,Secure,object oriented,platform Independent...
Syntax:
//------description-------
/*
----
---Description----
----
*/
3.Documentation Comment:
Syntax:
/*
*---------------
--------
*-------
*/
In general we will utilize documentation comment to prepare API documentation but it is not
suggestable or recommended.
To simply API documentation,JAVA has provided a predefined tool in the form "javadoc".
C:\abc\Employee.java
c:\abc>javadoc Employee.java
In java applications,to describe metadata JDK5.0 version has provided a new feature called
as "Annotation".
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:
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
--------
If we design any servlet by using annotations then it is sufficient to provide only one line of
java code[Annotation]
@webServlet("/login")
--------------------
NOTE:In JAVA/J2EE applications,we can utilize annotations as an alternative for XML tech or
XML documents.
1.Modularity
2.Abstraction
3.Security
4.Sharability
5.Re usability
1.Predefined packages
Ex: java.io
java.util
java.awt
2.User-defined Package
If we want to declare user defined packages in java programme then we have to use
the following Syntax.
package Package_Name;
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;
transaction---->module name
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
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.
Ex:java.io.BufferedReader,java.util.ArrayList
import java.io.*;
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.
2.To define starting point and ending point for 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.
After installation of JDK and JRE software's as part of Java installation process we
have to set
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.
variable name:path
variable value:c:\java\jdk1.7.0
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
Editor is a software or tool,it will provide very good environment to type and save
programs.
Ex:NotePad,EditPlus,NotePad++........
Ex:Eclipse,MyEclipse,NetBeans,JDeveloper.....
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{
}}
abc.java
}}
Status:invalid
A.java
public class A{
}
class Test{
Status:Valid
A.java:
public class A{
public class B{
}}
Status:Invalid
A.java:
public class A{
}}
public class B{
Status:InValid
1.The main purpose of compiling JAVA file is to convert JAVA programme from
HighLevelRepresentation to LowLevelRepresentation.
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.
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.
4.When Java Complier Software is activated then Java Complier will perform the
following tasks.
c)If the required java file is not available at current location then compiler will
provide the following message on command prompt.
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
Ex:
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:\java7\Employee.java
package com.durgasoft.core;
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
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 *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
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.
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
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:
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
1.Identifiers
2.Literals
3.Keywords/Reserved words
4.Operators
1.Identifiers:
Ex:
2.Identifiers will not allow all the operators,the special symbols like #,@,.,:,.......except
$ and_ symbols
Ex:
Ex:
forName(); -->Valid
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;
}}
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{
int Exception=10;
System.out.println(Exception);
}}
class Test{
float Thread=22.22f;
System.out.println(Thread);
}}
class Test{
String String="String";
System.out.println(String);
}}
class Test{
int System=10;
System.out.println(System);
}}
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{
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.
Ex:
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:
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:
2.Literals:
int a=10;
int--->data type
a----->variable
= ---->operatot
10 --->constant[literal]
; --->special symbol/terminator
byte,short,int,long ---->10,20......
char ---->'a','b'.....
float --->11.11f,12.234f,...............
double --->12.23,23.345..................
3.Boolean literals:
boolean --->true,false
4.String Literals:
String --->"abc","xyz"...
To represent number in Java,we are able to use the following number system.
Ex:
int b=0b10;-->Valid
int c=0B10;-->Valid
int d=0b102;-->Invalid
Ex:
int b=010;--->Valid
int c=0345;-->Valid
int d=0678;-->Invalid
Ex:
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:
Keywords:
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:
To design Java applications java has provided the following list of operators.
1.Arithmetic Operators:
+,-,*,/,%,++,--
2.Assignment Operator:
=,+=,-+,/+,%=
3.Comparsion Operators:
==,!=,<,><=,>=
&,|,^,............
5.logical Bitwise Operators:
&,|,^,<<,>>,.............
6.Ternary Operator:
exp1?exp2:exp3;
7.Shortcircuit Operator:
&&,||
Ex:1
class Test{
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{
int a=5;
System.out.println(a++-++a);
}}
class Test{
int a=7;
System.out.println(++a+--a*++a);
}}
class Test{
int a=4;
System.out.println(a++-++a*++a+--a);
}}
class Test{
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
T T T T F
T F F T T
F T F T T
F F F F F
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{
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{
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:
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
byte 1 byte 0
short 2 bytes 0
int 4 bytes 0
long 8 bytes 0
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
Ex:
8-1 8-1
-2 to 2 -1
7 7
-2 to 2 -1
-128 to 128 -1
-128 to 127
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.
Byte Byte
Short Short
Int Integer
long Long
Float Float
Double Double
char Character
Boolean Boolean
class Test{
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.
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.
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;
o/p:10 10
byte b=65;
char c= b;
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;
long l=10;
float f=l;
o/p 10 10.0
float f=22.2f;
long l=f;
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;
Note:For byte and short the next higher data type is "int".
byte b1=10;
byte b2=20;
byte b=b1+b2;
X+Y=Z
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.
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);
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);
O/P:65 A
char c='B';
System.out.println(c+" "+s);
O/P:B 66
Ex:
float f=22.22f;
System.out.println(f+" "+l);
O/P:22.22 22
Ex:
byte b1=10;
byte b2=10;
System.out.println(b);
O/P:20
Ex:
float f1=10.0f;
long L1=10;
O/P:20
Ex:
double d=22.22;
byte b=(byte)(short)(int)(long)(float)d;
System.out.println(b);
O/P:22
Ex:
int i=135;
byte b=(byte)i;
System.out.println(i+"----------------"+b);
O/P:135 -121
Reason:
int i=X;
byte b=(byte)X;
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:
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
throw,try-catch-finally
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);
O/P:20
int i=20;
int j;
if(i==10){
j=20;
}
else{
j=30
System.out.println(j);
O/P:20
int j;
if(i==10){
j=20;
System.out.println(j);
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.
4.In java,compiler is unable to recognize and execute variable expressions which are
having atleast one variable.
Switch:
Syntax:
switch(var){
case 1:
-------statements-----------
break;
------
------
case n:
-------statements--------
break;
default:
---------statements------
break;
}
Ex:
class Test{
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;
}}}
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;
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;
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;
Ex:
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.
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);
O/P:0 to 9
Ex:
int i=0;
for(System.out.println("Hello");i<10;i++){
System.out.println(i);
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:
System.out.println(i+" "+f);
Status:Compilation Error
Ex:
System.out.println(i+" "+j);
Status:Compilation Error
Ex:
System.out.println(i+" "+j);
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);
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");
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");
System.out.println("Before loop");
for(int i=0;;i++){
System.out.println("Inside loop");
System.out.println("After loop");
Reason:In Java,if we provide any statement immediately after infinite loop then that
statement is called as "UnReachableStatement".
Ex:
for(int i=0;i<10;){
System.out.println(i);
i=i+1;
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:
System.out.println(i);
Status:Compilation Error.
Ex:
for(;;)
Status:Compilation Error
Ex:
for(;;);
Ex:
for(;;)
Ex:
for(;;){
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.
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.
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.
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{
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{
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
Ex:
int i=0;
System.out.println("Before Loop");
while(i<10){
System.out.println("Inside loop");
System.out.println("After loop");
O/P:Infinite loop
Ex:
int i=0;
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
Transfer Statements:
These are Java Statements,which can be used to bypass the flow of execution from one
instruction to another instruction.
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);
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;
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
4)Structured Programming languages are able to provide tightly coupled design for the
applications.
Object Oriented Programming Languages are very good when compared with
Structured Programming Languages,because
Object Oriented Programming Languages are not good when compared with Aspect
Oriented Programming Languages,because,
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.
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.
Ans:
Ans:
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:
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:
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.
4)In main class,In main() method,create an object and reference variable for the class.
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 Salary:"+esal);
System.out.println("Employee Address:"+eaddr);
}}
class Test{
emp.display_Employee();
}}
Output:
Employee Details:
---------------------
Employee Id :E-111
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 Address:”+saddr);
}}
class Test{
s.display_Student();
}}
Output:
Student Details
------------------
Student ID:S-111
Student name:Durga
Student Marks:100
Student Address:Hyderabad
class Syntax:
----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:
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.
class Test{
System.out.println(“class Test”);
}}
System.out.println(“class Test”);
}}
==================
System.out.println(“class Test”);
}}
Status:Compilation Error
========================
protected class Test{
System.out.println(“class Test”);
}}
=========================
class A{
public class B{
System.out.println(“Hai”);
}}
=================
class A{
private class B{
System.out.println(“Hai”);
}}
==================
class A{
protected class B{
System.out.println(“Hai”);
}}
=================
class A{
class B{
System.out.println(“Hai”);
}}
==================
class A{
Ex:
Class A{
int i=10;
void m1(){
int k=30;
}}
All the class variables are called as Instance Variables.
1.Heap Memory
2.Stack Memory
3.Method Area
Heap Memory:All the class level variables are stored in Heap Memory.
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{
System.out.println(“Hai”);
}}
Output:
====================
Ex:
abstract class A{
class Test{
System.out.println(“Hai”);
}}
Output:
No Compilation Error.
=============
Ex:
native class A{
class Test{
System.out.println(“Hai”);
}}
Ouput:modifier native not allowed here.
=========================
Ex:
final class A{
class Test{
System.out.println(“Hai”);
}}
==================
Ex:
transient class A{
class Test{
System.out.println(“Hai”);
}}
===========================
Ex:
class A{
int j=20;
class Test{
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.
static
final
abstract
native
volatile
transient
synchronized
strictfp
--------
---------
---------
----------
From the above list of access modifiers,classes are able to allow abstract,final and
strictfp.
Where "class" is a keyword,it can be used to represent "class" object oriented feature
in Java.
class_Name:
“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:
NOTE:In class syntax,extends keyword will allow only one super class but
implements keyword will allow more than one interface.
Ex1:
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
b)Declare concrete methods and abstract methods as per the application requirement.
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.
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");
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{
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();
}}
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".
b)Declare all the service names in the form of abstract methods[Here no need to use
"abstract" keyword]
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.
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.
interface AccountService{
System.out.println("Account details");
System.out.println("------------------");
System.out.println("Account details");
System.out.println("----------------");
}}
class MainProject{
account.create("abc123","Durga","Savings");
System.out.println();
account.search("abc123");
System.out.println();
account.delete("abc123");
}}
Output:
Account details
-----------------
Account details
------------------
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:
Syntax:
---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.
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 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.
NOTE:Java Bean class is a normal Java class having variables and the respective
setXXX(-) methods and getXXX() methods.
eno=eno1;
ename=ename1;
esal=esal1;
}
public int getEno()//Accessor Method
return eno;
return ename;
return esal;
}}
class Test{
e.setEno(111);
e.setEname("Durga");
e.setEsal(5000.0f);
System.out.println("Employee Details");
System.out.println("-------------------");
}}
Output:
Employee Details
-------------------------
Syntax:
----impl-----
}
class A{
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{
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
Addition :10
-------------------------------------
No of Arguments :2
Addition :30
-------------------------------------
No of Arguments :3
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:
To create an object for a particular class,we have to use the following syntax.
| |
==============
|
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.
float f=22.22f;
class Test{
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.
hashCode()
toString()
equals()
clone()
finalize()
wait()
wait(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.
Ans:
class A{
}
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 B extends A{
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
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
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";
System.out.println("Employee Details");
System.out.println("------------------");
System.out.println("Employee Id :"+eid);
return "";
}}
class Test{
System.out.println(emp);
}}
Output:
Employee Details
-------------------------
Employee Id :E-111
class Test{
System.out.println(str);
System.out.println(e);
System.out.println(t);
System.out.println(i);
}}
Output:
abc
java.lang.Exception: My Exception
Thread[Thread-0,5,main]
10
1.Immutable Objects
2.Mutable Objects
Q)What is the difference between Immutable Object and Mutable Object?
(or)
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.
Mutable Object is a Java object,it will allow modifications over the data directly.
class Test{
String str2=str1.concat("Software");
String str3=str2.concat("Solutions");
System.out.println(str1);
System.out.println(str2);
System.out.println(str3);
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
Every object is able to manage no. of instances but we are able to access only
the latest instance.
Constructors:
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.
9)Constructors will allow "throws" keyword as part of its syntax to bypass the generated
exception from present Constructor to caller.
Syntax of Constructors:
-----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
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.
class A{
void A(){
System.out.println("A-con");
}}
class Test{
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".
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".
class Account{
String accNo;
String accName;
String accType;
accNo=accNo1;
accName=accName1;
accType=accType1;
System.out.println("Account details");
System.out.println("--------------------");
return "";
}}
class Test{
System.out.println(acc);
}}
Output:
Account details
------------------------
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:
D:\JAVA7\Test.java
class Test{
On Command prompt.
D:\JAVA7\javac Test.java
D:\JAVA7\javap Test
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".
class Person{
Person(){
System.out.println("0-argument Con");
}
Person(String name){
System.out.println("String-Parameterized Constructor");
System.out.println("String,String-parameterized con");
}}
class Test{
}}
Output:
0-argument Con
String,String-parameterized con
class EmployeeService{
---establish connection-------
---create Statement----
---establish connection-------
---create Statement----
---establish connection-------
---create Statement----
}}
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{
---establish connection-------
---create Statement----
}
}}
1.Instance Variables
2.Instance Methods
3.Instance Blocks
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:
class Account{
}}
class A{
int i=m1();
A(){
System.out.println("A-Con");
int m1(){
System.out.println("M1-A");
return 10;
}}
class Test{
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{
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----
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
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{
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{
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:
In Java applications,we are able to utilize 'this' keyword in the following four ways.
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.
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{
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.
class User{
this.uname=uname;
this.upwd=upwd;
public getUname() {
return uname;
public getUpwd(){
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{
A a=new A();
a.m2();
}}
Output:
m2-A
m1-A
m1-A
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{
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.
class A{
A(){
this(10);
this(22.22f);---->InValid
A(int i){
A(float f){
}}
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{
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.
class A{
A getRef1(){
A a=new A();
return a;
}
A getRef2(){
return this;
}}
class Test{
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:
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.
class A{
int j=10;
void m1(){
System.out.println("m1-A");
System.out.println(this.i);
}}
class Test{
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{
int j=10;
class Test{
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.
class A{
int i=10;
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{
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.
class Test{
return 10;
}}
Output:
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:
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.
class A{
int i=10;
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
Q)Is it Possible to print a line of text on command prompt with out using
main() method,static variable and static method?
Example Programme on with out using main() method,static variable and static
method:
class Test{
static{
}}
Output:
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.
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".
class Test{
}};}
Output:
JAVA7:Error:main method not found in class Test,please define the main method
as:public static void main(String[] args)
4.static import:
import java.io.*;
Syntax:
It will import all the static members from the specified class.
It will import only the specified member from the specified class.
class Test{
out.println(MIN_PRIORITY);
out.println(MAX_PRIORITY);
out.println(NORM_PRIORITY);
}}
Output:
10
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.
class A{
static {
System.out.println("SB-A");
System.out.println("m1-A");
return 10;
}}
class Test{
A a=new A();
}}
Output:
SB-A
m1-A
class A{
System.out.println("m1-A");
return 10;
static{
System.out.println("SB-A");
System.out.println("m2-A");
return 20;
}
class Test{
A a1=new A();
A a2=new A();
}}
Output:
m2-A
SB-A
m1-A
class A{
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{
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{
A a=new 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".
class A{
private A(){
System.out.println("A-con");
void m1(){
System.out.println("m1-A");
A a=new A();
return a;
}}
class Test{
A a=A.getRef();
a.m1();
}}
Output:
A-con
m1-A
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(--);
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 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".
class A{
static A a=null;
private A(){
static A getRef(){
if(a==null){
a=new A();
return a;
}}
class Test{
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{
private A(){
static A getRef(){
return a;
}}
class Test{
System.out.println(A.getRef());
System.out.println(A.getRef());
System.out.println(A.getRef());
}}
Output:
A@69cd2e5f
A@69cd2e5f
A@69cd2e5f
class A{
static A a=null;
static{
a=new A();
private A(){
static A getRef(){
return a;
}}
class Test{
System.out.println(A.getRef());
System.out.println(A.getRef());
System.out.println(A.getRef());
}}
Output:
A@a6eb38a
A@a6eb38a
A@a6eb38a
final Keyword:
1.final variable
2.final method
3.final class
1.final variable:
Ex:
i=i+10;
Output:
i=i+10;
1 error
Ex:
System.out.println(i);
}
Output:
2.final method:
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".
System:
Thread:
class MailStatus{
class Test{
System.out.println(MailStatus.AVAILABLE);
System.out.println(MailStatus.BUSY);
System.out.println(MailStatus.IDLE);
}}
Output:
Available
Busy
Idle
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.
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.
enum MailStatus{
AVAILABLE,BUSY,IDLE;
class Test{
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.
---------
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;
return price;
}}
class Test{
}}
Output:
If we compile the above programme,then compiler will translate enum into the
following class:
Apple(int price){
this.price=price;
return price;
----
enum Book{
A(500,250),B(300,150),C(200,100);
int no_of_pages;
int cost;
this.no_of_pages=no_of_pages;
this.cost=cost;
System.out.println(no_of_pages+"--------->"+cost);
}}
class Test{
System.out.println("-------------------");
Book.A.getBookDetails();
Book.B.getBookDetails();
Book.C.getBookDetails();
}}
Output:
---------------------------
No of Pages Cost
---------------------------
500------------->250
300------------->150
200------------->100
int cost;
int no_of_pages;
this.no_of_pages=no_of_pages;
this.cost=cost;
----
Class.forName(--):
class A{
static{
System.out.println("Class Loading");
A(){
System.out.println("Object Creating");
}}
class Test{
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.
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.
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.
Ex:Object obj=c.newInstance();
When JVM encounter the above instruction,JVM will perform the following actions.
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.
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".
class A{
static{
System.out.println("Class Loading");
A(){
System.out.println("Object creating");
}}
class Test{
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");
2.To define starting point and ending point for the applications execution.
Syntax:
----application logic---
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:
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.
JAVA7:Error:Main method not found in class Test,please define main method as:public
static void main(String args[])
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.
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)
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:
Ans:In Java applications,there are three ways to provide input to the Java programs.
1.Static Input
2.Dynamic 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:
D:\Java7>javac Add.java
D:\java7>java Add
First value : 10
Addition :30
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?
class Test{
for(int i=0;i<args.length;i++){
System.out.println(args[i]);
}}
O/P:D:\java7>javac Test.java
10
"abc"
22.22f
34.345
'A'
true
class Test{
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?
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{
System.out.println("main()-A");
}}
class B{
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{
System.out.println("main()-A");
String[] str={"AAA","BBB","CCC"};
B.main(str);
B.main(args);
}}
class B{
System.out.println("main()-B");
}}
O/P:D:\java7>javac abc.java
D:\java7>java A
main()-A
main()-B
main()-B
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.
class Test{
System.out.println("String[]-param-A");
System.out.println("int[]-param-A");
}}
Output:
String[]-param-A
Relationships in JAVA:
1.Has-A relationship
2.IS-A relationship
3.USE-A relationship
1.Has-A relationship:
1.One-To-One Association
2.One-To-Many Association
3.Many-To-One Association
3.Many-To-Many Association
Ex:
class Address{
----
class Student{
----
}
1.One-To-One Association:
Ex:
class 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;
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id :"+eid);
System.out.println();
System.out.println("Account Details");
System.out.println("----------------");
}}
class OneToOneEx{
emp.getEmployee();
}}
Output:
Employee Details
------------------------
Employee Id :E-111
Employee Name:Durga
Employee Address:Hyd
Account Details
----------------------
class Employee{
String eid;
String ename;
String eaddr;
this.eid=eid;
this.ename=ename;
this.eaddr=eaddr;
}}
class Department{
String did;
String dname;
Employee[] emps;
this.did=did;
this.dname=dname;
this.emps=emps;
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("----------------");
for(int i=0;i<emps.length;i++){
Employee e=emps[i];
}}}
class OneToManyEx{
emps[0]=e1;
emps[1]=e2;
emps[2]=e3;
dept.getDepartmentDetails();
}}
Output:
Department Details
-----------------------------
Department Id :D-111
Department Name:Admin
----------------------------------
class Branch{
String bid;
String bname;
this.bid=bid;
this.bname=bname;
}}
class Student{
String sid;
String sname;
String saddr;
Branch branch;
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
this.branch=branch;
System.out.println("Student Details");
System.out.println("----------------");
System.out.println("Student Id :"+sid);
System.out.println("Student Address:"+saddr);
System.out.println("Branch Id :"+branch.bid);
System.out.println();
}}
class ManyToOneEx{
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:
class 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;
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
this.crs=crs;
System.out.println("Student Details");
System.out.println("----------------");
System.out.println("Student Id :"+sid);
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();
}}
class ManyToManyEx{
crs[0]=c1;
crs[1]=c2;
crs[2]=c3;
std1.getStudentDetails();
std2.getStudentDetails();
std3.getStudentDetails();
}}
Output:
Student Details
----------------------
Student Id :S-111
Student Address:Hyd
------------------------------------
C-111 C 500
Student Details
------------------------
Student Id :S-222
Student name:BBB
Student Address:Hyd
------------------------------------
C-111 C 500
Student Details
-----------------------
Student Id :S-333
Student name:CCC
Student Address:Hyd
-----------------------------------
C-111 C 500
This is a relationship between entities,where one entity will use another entity upto a
particular action or behaviour or method.
class Account{
String accno;
String accName;
String accType;
int bal=10000;
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
}}
class Transaction{
String tx_tid;
String tx_Type;
this.tx_Id=tx_Id;
this.tx_Type=tx_Type;
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("Transaction Status:SUCCESS");
System.out.println("********THANKQ,VISIT AGAIN***********");
}}
class UsesAEx{
tx.deposit(acc,5000);
}}
Output:
Transaction Details
----------------------------
Transaction Id :T-111
Transaction Status:SUCCESS
********THANKQ,VISIT AGAIN**********
Ans:In Object Orientation,both Aggregation and Composition are two level of associations
or representations of associations.
Ex:
"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:
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.
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.
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
{{{
---------- ----------- -----------
---------- ----------- -----------
}}}
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.
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{
C c=new C();
}}
Ouput:
SB-A
B-con
SB-C
==========================
class A{
static{
System.out.println("SB-A");
System.out.println("m1-A");
return 10;
class B extends A{
static{
System.out.println("SB-B");
System.out.println("m2-B");
return 20;
}}
class C extends B{
return 30;
static{
System.out.println("SB-C");
}}
class Test{
C c1=new C();
C c2=new C();
}}
O/P:SB-A
m1-A
m2-B
SB-B
m3-C
SB-C
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.
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{
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{
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{
C c=new C(10);
}}
Status:Compilation Error
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{
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;
System.out.println("m2-A");
return 20;
System.out.println("IB-A");
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");
System.out.println("m4-B");
return 40;
}}
class C extends B{
System.out.println("m5-C");
return 50;
int m6(){
System.out.println("m6-C");
return 60;
}
C(){
System.out.println("C-con");
int m6();
System.out.println("IB-C");
static{
System.out.println("SB-C");
class Test{
C c1=new C();
C c2=new C();
}}
Super is a Java keyword,it can be used to represent super class object from sub
classes.
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.
class A{
int i=100;
int j=200;
class B extends A{
int i=10;
int j=20;
System.out.println(i+" "+j);
System.out.println(this.i+" "+this.j);
System.out.println(super.i+" "+super.i);
}}
class Test{
B b=new B(50,60);
}}
Output:
50 60
10 20
100 100
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]);
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{
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.
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{
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{
C c=new C(10);
}}
Output:
A-con
B-int-param-con
C-int-param-con
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]);
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();
}}
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.
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{
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".
void m1(){
System.out.println("m1-A");
}}
class B extends A{
void m2(){
System.out.println("m2-B");
}}
class Test{
case 1:
A a=new A();
B b=a;
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;
Case 3:
A a=new B();
B b=(B)a;
b.m1();
b.m2();
Ex1:
A a=new A();
B b=a;
Ex2:
A a=new A();
B b=(B)a;
Ex3:
A a=new A();
B b=(B)a;
A a=new C();
B b=(C)a;
Ex5:
A a=new B();
B b=(C)a;
Ex6:
A a=new C();
C c=(D)a;
Ex7:
B b=new D();
C c=(D)b;
Ex8:
A a=new D();
D d=(D)(C)(B)a;
Ex9:
A a=new C();
D d=(D)(C)(B)a;
A a=new C();
C c=(D)(C)(B)a;
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.
1.Static Polymorphism:
Ex:Method Overloading
2. 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{
System.out.println(i+j);
System.out.println(f1+f2);
System.out.println(str1+str2);
}}
class Test{
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{
float salary=basic+((basic*hk)/100)-((basic*pf)/100)+ta);
System.out.println("Salary :"+salary);
}
float salary=basic+((basic*hk)/100)-((basic*pf)/100)+ta)+bonus;
System.out.println("Salary :"+salary);
}}
class Test{
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.
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.
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{
return 7.0f;
return 10.5f;
return 12.0f;
}}
class Test{
}}
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{
/* A a=new A();
a.m1();
*/
/*
B b=new B();
b.m1();
*/
A a=new B();
a.m1();
}}
1.To override super class method with sub class then super class method must not be
declared as private.
Ex:
class A{
System.out.println("m1-A");
}}
class B extends A{
void m1(){
System.ou.println("m1-B");
}}
class Test{
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{
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{
System.out.println("m1-B");
}}
class Test{
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{
System.out.println("m1-A");
}}
class B extends A{
System.out.println("m1-B");
}}
class Test{
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{
System.out.println("m1-A");
}}
class B extends A{
System.out.println("m1-B");
}}
class Test{
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:
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
class DB_Driver{
System.out.println("Type-1 Driver");
}}
System.out.println("Type-4-Driver");
}}
class Test{
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.
System.out.println("Type-4 Driver");
}}
class Test{
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");
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{
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{
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{
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{
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{
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{
class C extends B{
void m2(){
System.out.println("m2-C");
void m3(){
System.out.println("m3-C");
}}
class Test{
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{
class A extends B{
class B extends A{
Interfaces:
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{
System.out.println("m1-A");
System.out.println("m2-A");
System.out.println("m3-A");
}}
System.out.println("m4-A");
}}
class Test{
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();
System.out.println("m1-A");
}}
class B extends A{
System.out.println("m2-B");
System.out.println("m3-B");
}}
class Test{
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();
void m3();
System.out.println("m1-A");
}
public void m2(){
System.out.println("m2-A");
System.out.println("m3-A");
}}
class Test{
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();
System.out.println("m1-A");
System.out.println("m2-A");
System.out.println("m3-A");
}}
class Test{
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
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.
3.Functional Interfaces
To declare default methods in interfaces we have to use "default" keyword in method syntax
like access modifier.
Ex:
interface I{
System.out.println("m1-A");
}}
class Test{
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{
---------
--------
}}
interface I{
System.out.println("m1-A");
}}
class A implements I{
System.out.println("m1-A");
}}
class Test{
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{
System.out.println("m1-1");
}}
class Test{
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
System.out.println("m3-I");
System.out.println("m4-I");
class A implements I{
System.out.println("m1-A");
}}
class Test{
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.
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{
A a new A();
B b=new B();
}}
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.
2.Implement java.lang.Cloneable interface inorder to make eligible any object for cloning.
4.In Main class,in main() method,access clone() method over the respective object.
String sid;
String sname;
String saddr;
this.sid=sid;
this.sname=sname;
this.saddr=saddr;
return super.clone();
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{
System.out.println(std1);
Student std2=(Student)std1.clone();
System.out.println();
System.out.println(std2);
}}
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;
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
}}
String eid;
String ename;
String eddr;
Account acc;
this.eid=eid;
this.ename=ename;
this.eaddr=eaddr;
this.acc=acc;
return super.clone();
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id :"+eid);
System.out.println("Employee Address :"+eaddr);
System.out.println("Account Deatails");
System.out.println("----------------");
System.out.println("Account Number:"+acc.accNo);
return "";
}}
class Test{
System.out.println(emp1);
Employee emp2=(Employee)emp1.clone();
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)
return emp;
}
Exception Handling:
Error Exception
Definition of Exception:
1.Predefined Exceptions
2.UserDefined Exceptions
1.Predefined Exceptions:
1. Checked Exceptions
2. Unchecked Exceptions
Q)What is the difference between checked Exception and Unchecked
Exception?
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.
If any checked exception is having only checked exceptions are child classes
then that checked exceptions are called as "pure checked exceptions".
Ex:IOException
Ex:Exception,Throwable
Review of Predefined Exceptions:
1.Arithmetic Exception:
class Test{
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:
2.NullPointerException:
class Test{
Date d=null;
System.out.println(d.toString());
}}
If we execute the above code then JVM will provide the following exception
details.
Exception Location:Test.java:7
3.ArrayIndexOutofBoundsException:
Ex:
class Test{
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:
Ex:
import java.io.*;
class Test{
}}
If we execute the above code then JVM will provide the following exception
message:
Exception Name:java.io.FileNotFoundException
Exception Location:Test.java:7
5.ClassNotFoundException:
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:
class A{
static{
System.out.println(“Class Loading”);
A(int i){
System.out.println("Object Creating");
}}
class Test{
Class c=Class.forName("A");
Object obj=c.newInstance();
}}
If we execute the above code then JVM will provide the following
ExceptionDetails.
Exception Description:A
Exception Location:Test.java:7
7.IllegealAccessException:
Ex:
class A{
private A(){
System.out.println("Object Creating");
}}
class Test{
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 Location:Test.java:10
8.IllegalArgumentException:
class Test{
t.setPriority(15);
}}
If we execute the above code then JVM will provide the following exception
details.
Exception Name:java.lang.IllegalArgumentException
Exception Location:Test.java:10
9.IllegalThreadStateException:
If we access setDaemon(true) method after starting the thread then JVM will
rise an exception like "IllegalThreadStateException".
while(true){
System.out.println("User Thread");
}}}
class Test{
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 Location:Test.java:17
10.ClassCastException:
class A{
class B extends A{
class Test{
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 Location:Test.java:10
“throw” keyword:
Ex:
import java.io*;
class Test{
String accNo=br.readLine();
String accName=br.readLine();
int p_num=Integer.parseInt(pin_number);
System.out.println("Account Details");
System.out.println("----------------");
}
else{
}}}
class Test{
System.out.println("Before Exception");
System.out.println("After Exception");
}}
1.”throws” keyword:
“throws” keyword will allow more than one exception in method prototypes.
In Java applications,”throws” keyword will be utilized mainly for checked
exceptions.
Status:Valid
Status:InValid
Ex:
Status:Valid
Ex:
Status:Valid
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 m2(){
try{
m1();
catch(Exception e){
e.printStackTrace();
}}
----
m1();
Import java.io.*;
class A{
concat();
}
class Test{
A a=new A();
a.add();
}}
Internal Flow:
Ans:
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.
The main purpose of catch block is to catch the exception from try block and
to display exception details on command prompt.
1.e.printStackTrace()
2.System.out.println(e):
3.System.out.println(e.getMessage());
1.e.printStackTrace():
2.System.out.println(e):
3.System.out.println(e.getMessage()):
try{
catch(ArithmeticException e){
e.printStackTrace();
System.out.println();
System.out.println(e);
System.out.println();
System.out.println(e.getMessage());
finally{
}}
Output:
at Test.main(Test.java:7)
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?
class Test{
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{
System.out.println("Before Try");
try{
float f=100/0;
catch(Exception e){
System.out.println("Inside Catch");
finally{
System.out.println("Inside Finally");
System.out.println("After Finally");
}}
Output:
Before try
Inside catch
Inside finally
After finally
class A{
int m1(){
try{
return 10;
catch(Exception e){
return 20;
finally{
return 30;
}}}
class Test{
A a=new A();
int val=a.m1();
System.out.println(val);
}}
Output:
30
Ans:Yes,it is possible to provide try block with out catch block but by using
"finally" Block.
try{
finally{
class Test{
System.out.println("Before try");
try{
int i=100;
int j-0;
float f=i/j;
finally{
System.out.println("Inside finally");
}
System.out.println("After Finally");
}}
Output:
Before try
Inside finally
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.
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
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.
Ex1:
try{
catch(ArithmeticException e){
catch(ClassCastException e){
catch(NullPointerException e){
Status:Valid Combination
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{
catch(ArithmeticException e){
catch(IOException e){
catch(NullPointerException e){
Status:Invalid
Ex6:
try{
catch(ArithmeticException e){
catch(IOException e){
catch(NullPointerException e){
status:Valid
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.
try{
}catch(ArithmeticException e){
}catch(NullPointerException e){
}catch(ClassCastException e){
Syntax:
try{
class Test{
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();
}}
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.
File f=null;
BufferedReader br=null;
Connection con=null;
try{
f=new File("abc.txt");
con=DriverManager.getConnection("jdbc:odbc:nag","system","durga");
-----
-----
catch(Exception e){
}
finally{
try{
f.close();
br.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}}
try(Resource1;Resource2;........Resource-n){
-------
------
catch(Exception e){
-----
-----
Ex:
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{
int size=fis.available();
fis.read(b);
fos.write(b);
catch(Exception e){
e.printStackTarce();
}}}
MyException(String err_Msg){
super(err_Msg);
}}
try{
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;
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
try{
System.out.println("Transaction Details");
System.out.println("-------------------");
System.out.println("Transaction Id :T123");
int total_Amt=0;
if(wd_Amt<initial_Amt)
total_Amt=initial_Amt-wd_Amt;
initial_Amt=total_Amt;
else{
total_Amt=initial_Amt;
System.out.println("Transaction Status:FAILURE");
catch(InsufficientFundsException e){
System.out.println(e.getMessage());
System.out.println("********ThankQ,Visit Again***********");
class Test{
tx1.withdraw(5000);
System.out.println();
tx2.withdraw(15000);
}}
IOStreams:
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<<,......
Java has represented all the streams in the form of predefined classes in
"java.io" package.
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.
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..
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.
1.Reader
2.Writer
1.Reader:
Ex:
CharArrayReader
FilterReader
BufferedReader
FileReader
InputStreamReader….
2.Writer:
Ex:
CharArrayWriter
FilterWriter
FileWriter
PrintWriter
BufferedWriter….
FileOutPutStream:
To transfer the data from Java program to a particular target file by using
FileOutPutstream we have to use the following Steps.
-->It will override the existed data in the target file at each and every write
operation.
-->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.
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.
String data="Hello";
byte[] b=data.getBytes();
Ex:
fos.write(b);
4)Close FileOutPutStream:
fos.close();
2.FileInputStream:
If we want to transfer the data from source file to java programme by using
FileInputStream,we have to use the following Steps:
Ex:
When JVM encounter the above instruction then JVM will perform the
following actions.
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
Ex:
int size=fis.available();
To read the data from FileInputStream into byte[],we have to use the
following method.
Ex:
fis.read(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{
String file_Name=args[0];
int size=fis.available();
fis.read();
System.out.println(data);
fis.close();
}}
import java.io.*;
import java.util.*;
class Word_Count_Ex{
int size=fis.available();
fis.read();
int tokens=st.countTokens();
int count=0;
while(st.hasMoreTokens()){
String token=st.nextToken();
if(token.equals("is")){
count=count+1;
}}
fis.close();
}}
import java.io.*;
int size=fis.available();
byte[] b=new byte[size];
fis.read(b);
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.
-->It will override the existed content with the new content at each and
every write operation.
-->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();
To write char[] data into FileWriter,we have to use the following method.
Ex:fw.write(ch);
4.Close FileWriter:
fw.close();
import java.util.*;
String data="DurgaSoftwareSolutions";
char[] ch=data.toCharArray();
fw.write(ch);
fw.close();
}}
FileReader:
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:
when JVM encounter the above instruction,JVM will perform the following
steps.
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.
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".
3.Close FileReader:
fr.close();
import java.util.*;
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.*;
String data="";
int val=fr.read();
while(val!=-1){
data=data+(char)val;
val=fr.read();
char[] ch=data.toCharArray();
fw.write(ch);
fr.close();
fw.close();
}}
1.BufferedReader
2.Scanner
3.Console
1.BufferedReader:
To read the data from BufferedReader,we will use the following method
1.readLine()
2.read()
import java.io.*;
String data1=br.readLine();
int data2=br.read();
}}
import java.io.*;
String val2=br.readLine();
System.out.println("Addition :"+val1+val2);
}}
import java.io.*;
String val1=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.
To read String data as Dynamic input,we have to use the following method.
Console:
This class is provided by Java in java.io package along with JAVA6 Version.
nextXXX() methods]
2.These are not providing security for the data like password data,pin
numbers.....
To get Console object,we have to use the following method from "System"
class.
Ex:Console c=System.console();
import java.io.*;
Console c=System.console();
if(uname.equals("durga")&&upwd.equals("durga")){
System.out.println("Valid User");
else{
System.out.println("InValid User");
}}
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--------------
Serializable interface is marker interface,it will make eligible any object for
Serialization and Deserialization.
int eno=111;
String ename="AAA";
float esal=5000;
3.Create ObjectOutPutStream:
Ex:
Ex:oos.writeObject(e1);
Steps To perform DeSerialization:
2.Create ObjectInputStream:
Ex:Employee e2=(Employee)ois.readObject();
-->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.
import java.io.*;
class A{
int i=10;
int j=20;
class Test{
A a=new A();
oos.writeObject(a);
}}
Status:"java.io.NotSerializableException".[Exception]
Ex:
import java.io.*;
int i=10;
int j=20;
}
class B extends A{
int k=30;
int l=40;
class Test{
B b=new B();
oos.writeObject(b);
}}
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{
B b=new B();
oos.writeObject(b);
}}
Ex:
import java.io.*;
String bid;
String bname;
this.bid=bid;
this.bname=bname;
}}
String accName;
Branch branch;
this.accNo=accNo;
this.accName=accName;
this.branch=branch;
}}
String eid;
String ename;
Account acc;
this.eid=eid;
this.ename=ename;
this.acc=acc;
}}
class Test{
}}
Externalization:
where ObjectInput will get serialized data from text file to perform
manipulations.
---implementation---
---implementation----
}}
Ex:
import java.util.*;
import java.io.*;
String eid;
String ename;
String email;
String emobile;
public Employee(){
this.eid=eid;
this.ename=ename;
this.email=email;
this.emobile=emobile;
try{
st1.nextToken();
int no=Integer.parseInt(st1.nextToken());
String mail=st2.nextToken();
st3.nextToken();
String mobile=st3.nextToken();
oop.writeInt(no);
oop.writeUTF(ename);
oop.writeUTF(mail);
oop.writeUTF(mobile);
catch(Exception e){
e.printStackTrace();
}}
eid="E-"+oip.readInt();
ename=oip.readUTF();
email=oip.readUTF()+"@durgasoft.com";
emobile="91-"+oip.readUTF();
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id : "+eid);
}}
class ExternalizableEx{
public static void main(String args[])throws Exception{
emp1.getEmpDetails();
oos.writeObject(emp1);
System.out.println();
Employee emp2=(Employee)ois.readObject();
emp2.getEmpDetails();
Files in Java:
1.Sequential Files
2.RandomAccessFiles
1.Sequential Files:
To get file / directory parent location,we have to use the following method.
To get file / directory absolute path,we have to use the following method.
To check whether the created thing File or not,we have to use the following
method.
To check whether the created thing is directory or not we have to use the
following method.
Ex:
import java.io.*;
class Test{
f.createNewFile();
System.out.println(f.isFile());
System.out.println(f.isDirectory());
f1.mkdir();
System.out.println(f.isFile());
System.out.println(f.isDirectory());
int size=fis.available();
fis.read();
System.out.println(data);
}}
RandomAccessFile:
It is a Storage area,it will allow the user to read data from random positions.
"java.io.RandomAccessFile".
Ex:
import java.io.*;
class Test{
raf.writeInt(111);
raf.writeUTF("Durga");
raf.writeFloat(5000.0f);
raf.writeUTF("HYD");
raf.seek(0);
}}
Annotations:
1.Introduction
2.Comment Vs Annotations
3.XML Vs Annotations
4.Types of Annotations
5.Standard Annotations
6.Custom Annotations
Annotation:
Ex:
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>
@WebServlet("/login")
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
@interface Annotation_Name{
@Annotation_Name(member_name1=value1,member_Name2=v
alue2.........)
1.Marker Annotations:
Ex:
@interface Override{
2.Single-Valued Annotation:
Ex:
@interface SuppressWarnings{
String value();
3.Multi-Valued Annotation:
Ex:
@interface WebServlet{
int loadOnStartup();
String[] urlPatterns();
-----
1.Standard Annotations
2.Custom Annotations
1.Standard Annotations:
2.Meta Annotations
Ex:
@Override
@Deprecated
@SuppressWarnings
@FunctionalInterface [JAVA 8]
2)Meta Annotations:
@Inherited
@Documented
@Target
@Retention
1.@Override:
Ex:
class JdbcApp
System.out.println("Type-1 Driver");
}
class New_JdbcApp extends JdbcApp
@Override
System.out.println("Type-4 Driver");
class Test
app.getDriver();
class Employee{
@Deprecated
class Test{
emp.gen_Salary(25000,20.0f);
@SuppressWarnings(--):
Ex:
import java.util.*;
class Bank{
@SuppressWarnings("unchecked")
al.add("chaitu");
al.add("Mahesh");
al.add("Jr NTR");
al.add("Pavan");
return al;
class Test{
List l=b.listCustomers();
System.out.println(l);
@FunctionalInterface:
@FunctionalInterface
interface Loan{
void getLoan();
System.out.println("GoldLoan");
class Test{
l.getLoan();
@Inherited:
@Inherited annotation.
Ex:
@interface Persistable
@Persistable
class Employee
@Inherited
@interface Persistable
@Persistable
class Employee{
}
class Manager extends Employee{
@Documented:
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
@Target:
Synatx:
@Target(ElementType.TYPE,ElementType.FIELD,ElementType.ME
THOD)
@interface persistable
@Persistable
class Employee
@Persistable
Account acc;
@Persistable
@Retention:
Syntax:
@Retention(RetentionPolicy.RUNTIME)
@interface Persistable
@Persistable
class Employee
Custom Annotations:
Bank.java
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@interface Bank
Account.java
@Bank(name="Axis Bank",phone="040-987654")
String accNo;
String accName;
String accType;
this.accNo=accNo;
this.accName=accName;
this.accType=accType;
System.out.println("----------------");
System.out.println("Account Number:"+accNo);
1)If the annotation is class level annotation then use the following
steps:
2)If the annotation is Field level annotation then use the following
steps:
MainApp.java
import java.lang.annotation.*;
import java.lang.reflect.*;
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("Phone "+b.phone());
}
Course.java:
import java.lang.annotation.*;
@Inherited
@Documented
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface Course{
Student.java:
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")
System.out.println("Student Details");
System.out.println("---------------");
System.out.println("Student Id :"+sid);
System.out.println("Student Address:"+saddr);
ClientApp.java
import java.lang.annotation.*;
import java.lang.reflect.*;
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());
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:
Ex:
class Account{
class StudentAccount{
class EmployeeAccount{
class LoanAccount{
2.Abstraction:
3.Security:
4.Share-ability:
5.ReUseAbility:
class Inner{
----
----
class A{
int i=10;
void m3(){
System.out.println("m3-A");
//System.out.println(j);---->error
class B{
int j=20;
void m1(){
System.out.println("m1-B");
System.out.println(i);
void m2(){
System.out.println("m2-B");
class Test{
ab.m1();
ab.m2();
//ab.m3();--->error
A a=new A();
a.m3();
//a.m1();--->error
//a.m2();--->error
Diagram(OOPS--INNERCLASSES1.png)
class A{
interface I{
void m1();
void m2();
class B implements I{
System.out.println("m1-B");
}
System.out.println("m2-B");
class Test{
ai.m1();
ai.m2();
class Outer{
class A{
int i=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");
System.out.println("m3-B");
}
}
class Test{
ab.m1();
ab.m2();
A.B.m3();
interface I{
class A{
void m1(){
System.out.println("m1-A");
void m2(){
System.out.println("m2-A");
}
}
class Test{
ia.m1();
ia.m2();
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{
A a=new A();
a.m1();
Syntax:
---abstract methods---------
class Outer{
};
interface I{
void m1();
void m2();
}
class A{
I i=new I(){
System.out.println("m1-A");
System.out.println("m2-A");
};
class Test{
A a=new A();
a.i.m1();
a.i.m2();
abstract class A{
void m1(){
System.out.println("m1-A");
class B{
A a=new A(){
void m2(){
System.out.println("m2-AIC");
void m3(){
System.out.println("m3-AIC");
};
class Test{
B b=new B();
b.a.m1();
b.a.m2();
b.a.m3();
}
Ex:
MyFrame(){
this.addWindowListener(new WindowAdapter(){
System.exit(0);
});
}}
interface I{
void m1();
class B{
void m2(I i){
System.out.println("m2-B");
i.m1();
class Test{
B b=new B();
b.m2(new I()
System.out.println("m1-AIC");
});
--diagram--(Packages.png)[package1]
--diagram--(Packages.png)[package2]
1.Modularity:
2.Abstraction:
3.Security:
Security=Encapsulation+Abstraction
4.Sharability:
5.Reusability:
--diagram--(Pacakages1.png)
1.Predefined packages
1.Predefined Packages:
Ex:
1.java.lang:
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.
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.
Component,Label,TextFiled,TextArea,Button,Check box,List..
FlowLayout,BorderLayout,GridLayout,GridBagLayout,CardLayout....
5.javax.swing:
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 the predefined classes and interfaces like
Driver
DriverManager
Connection
Statement
PreparedStatement
CallableStatement
ResultSet
package package_Name;
EX:
package com.durgasoft.axis.loan;
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)
String eid;
String ename;
String eaddr;
this.eid=eid;
this.ename=ename;
this.eaddr=eaddr;
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id :"+eid);
D:\java7\MainApp.java:
import com.durgasoft.core.*;
emp.displayEmployee();
}
compilation:D:\java7>set classpath=C:\abc;.;
D:\java7>javac MainApp.java
D:\java7>java MainApp
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;
String ename;
String eaddr;
this.eid=eid;
this.ename=ename;
this.eaddr=eaddr;
System.out.println("Employee Details");
System.out.println("-----------------");
System.out.println("Employee Id :"+eid);
D:\abc\Student.java:
package com.durgasoft.std;
String sid;
String sname;
String saddr;
this.sname=sname;
this.saddr=saddr;
System.out.println("Student Details");
System.out.println("----------------");
System.out.println("Student Id :"+sid);
Compilation Process:
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.*;
System.out.println();
std.displayStudent();
Compilation Process:
D:\java7>set classpath=C:\xyz\durga.jar;.;
D:\java7>javac MainApp.java
D:\java7>java MainApp
Ex:
Diagram(Packages2.png)
Executable Jar file is a jar file which contains main class directly.
D:\abc\MainApp.java
import java.awt.*;
this.setVisible(true);
this.setSize(700,500);
this.setTitle("Logo Frame");
this.setBackground(Color.green);
g.setFont(f);
this.setForeground(Color.red);
class MainApp{
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:
Ex:
D:\abc>javac MainApp.java
EX:
If we use the above command on command prompt then JVM will perform
the following actions
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:
java.lang
Class
java.lang.reflect
Field
Method
Constructor
Package
Modifier
---
---
java.lang.Class:
class c=Class.forName("Employee");
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".
Ex:
Class c=e.getClass();
Class c=Employee.class
Ex:
int val=c.getModifiers()
String modifiers=Modifier.toString(val);
import java.lang.reflect.*;
class Test{
Class c1=Clas.forName("Employee");
System.out.println(c1.getName());
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("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 method will return all the variables metadata which are
declared as public in the respective class and in the super
class.
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.
import java.lang.reflect.*;
class Employee{
class Test{
Class c=Employee.class;
Field[] flds=c.getDeclaredFields();
for(int i=0;i<flds.length;i++){
Field f=flds[i];
System.out.println("value :"+f.get(f));
int val=f.getModifiers();
System.out.println("Modifiers :"+Modifier.toString(val));
System.out.println("----------------------------------------");
java.lang.Method:
import java.lang.reflect.*;
class Employee{
{}
{}
class Test{
Class c=Employee.class;
Method[] mthds=c.getDeclaredMethods();
for(int i=0;i<mthds.length;i++){
Method m=mthds[i];
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();
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:
class Employee{
class Test{
Class c=Employee.class;
Constructor[] con=c.getDeclaredConstructors();
for(int i=0;i<con.length;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();
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)
public Byte(byte b)
public Short(short s)
public Integer(int i)
Ex:
int i=10;
System.out.println(i+" "+in);
O/P: 10 10
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:
----
----
Ex:
int i=10;
Integer in=Integer.valueOf(i);
System.out.println(i+" "+in);
O/P: 10 10
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:
-------------
-------------
Ex:
int i=in.intValue();
System.out.println(in+" "+i);
O/P: 10 10
Ex:
int i=in;
System.out.println(in+" "+i);
O/P:10 10
Ex:
String data="10";
System.out.println(data+" "+in);
O/P: 10 10
b)Using valueOf(---) method:
Ex:
String data="10";
Integer in=Integer.valueOf(data);
System.out.println(data+" "+in);
O/P: 10 10
Ex:
String data=in.toString();
System.out.println(in+" "+data);
O/P: 10 10
Ex:
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:
------------
------------
Ex:
String data="10";
int i=Integer.parseInt(data);
System.out.println(data+" "+i);
int i=10;
String data=Integer.toString(i);
System.out.println(i+" "+data);
O/P: 10 10
Ex:
int i=10;
String data=""+i;
System.out.println(i+" "+data);
O/P: 10 10