Java Notes
Java Notes
It was developed by James gosling at microsystem in 1995 and later acquire by corporation . it is a
simple programming language which makes writing, compiling and rebugging easy. It helps to create
reusable code-end modular programs. It is a class based OOP language java application are compile
byte code that can run on any java virtual machine (JVM)
1. Platform independent:- compile converts the source code to byte code and then JVM
execute the byte code generating by the compiler. This byte code can run on any platform be
it window, LINUX and mac, OS. That means if we compile a program on windows. We can run
it on mac OS or vice-versa. Each OS has different JVM but the output produce by all the OS is
the same after the execution of the byte code, that’s why it called platform independent.
2. OOP:- it is an OOP language promoting obj & classes organizing the program in the terms of
collection of obj is a way of OOP each of which request & interfaces of class . The main
concept of OOP one abstraction encapsulation, inheritance & polymorphism.
3. Simplicity :- Java’s syntax is simple easy to learn specially for those who familiar with c &
CPP. IT eliminate complex features like pointer & pointers & multiple inheritance making its
learn to write debug & maintain code.
4. Rebustness:- it is robust which means reliable it is developed in such as way that it parts a lot
of efforts into checking errors as early as possible that’s why the java compile is able to dated
even those errors that are not easily to detect by another language . The main feature of java
that makes collection exception handling & m/y allocation.
Security:- In java we don’t have pointers so we can’t access out of bend array i.e. it shows
array index out of bound exception. It we try to do so that’s why several security flows like
step corruption or bytes overflow are impossible like stack corruption are impossible to
explain in java also program run in an environment that is independent of the environment
that is independent of the OS which makes java more server .
Distributive:- we can create distributed application using the java programing language.
Remote invocation method & enter price java beans are used for creating distributive
application in java. The java programs can be easily distributed on 1 or more system that are
connected to each other through internet connection.
Multi threading:- it support multithreading enabling the content of multiple part of program.
This features is particularly useful for application that requires high performance such as
games and real times simulators.
High performance :- Java architecture is define in such a way that retain overhead during the
runtime & at some kinds java uses (just in time (JIT)) compiler, when compiler code on
demand basis when It only compiles there method that are called making application to
execute faster .
JDK
JVM Exit
Java virtual machine :- The JVM is an integral part of the java platform responsible for executing java
byte code.
It ensures that the output of java program is consistence across different platforms.
Java debuggers define as a command line tool used by developers to debug java code efficiently. It
allows developers to ser break points, ----------------variable &step through the code, it can attach it
self to a running java process & support both local & remate debugging it is a user friendly command
line interface.
Java runtime envoriment :- it about the java program to run however we can’t compile it using only
JRE . JRE include a browser. JVM , applet support & plugins for running the java program.
Garbage collection:- In java programmers can’t delete the obj to delete or recollect that obj/ specific
M/Y (which is allocated previously) JVM has a program called garbage collection. It can be collect the
obj that are not referenced so java makes the life of a program easy by handling M/Y management.
However programmer should be careful about there code weather there are using obj that have
been used for long time b/c garbage can’t recover the M/Y of obj being referenced.
Class path:- it is the file path where java runtime and java compiler look for class file to load by
default JDK provides many library if you want to include external library they should be added to the
class path .
In other words we can say that basically everything in java represent in class as an obj including the
main function.
Performance:- java can be slower compile to the other programing language such as c ++ due to it
use a virtual machine and automatic M/Y management
Primitive Non-primitive
Int string
Float Float
Char class
Byte
Long
Boolean
Java control statement :- java compiler executer the code from top to bottom approach the
statement of java are executed according the order in which they appear.
However java provides statement that can be used to control the flow of java code such statement
are called control flow statements.
A:- if statement
2, Loop statements:-
B:- do while
C:-while
D:-for each
3. jump statement
A:- break
B:- continue
If statements:- in java the if statement is used to evaluate a condition The content of the program is
diverted depending upon the specific condition. The condition of the if statement gives a Boolean
value either true or false in java there are four types of if statement:…
1. Simple if
2. If else
3. If else if
4. Nested if
# Public class Aditya {
Int a = 10;
If (a % 2 == 0)
Else if (a == 0)
Else
Page no 13 start
Switch :- This is similar to if else if statements. It contains multiple blocks of code called cases and a
single case is executed based on the variable which is being switched. It is easier to use then the
other if statements there are some rule we need to take are while using switch statements in java
Loop:-
Output:-
*
**
***
****
*****
#For loop :- it provides and enhanced for loop to traverse. The data structure like array or
collection. In this loop we don’t need to update the loop variable.
Syntax:-
For(datatype variable:array name)
Statement;
String[]name{“1”,”2”,”3”,”4”};
System.out.print(names);
}}}
Page no 18
Operators in java :- Operator constitute the basic building blocks to any programing language java to
provide many type of operator which can be use according to the need to program various
calculation and function be it logical arithmetic and relational.
1. Arithmetic
2. Unary
3. Assignment
4. Relational
5. Logical
6. Ternary
7. Bitwise
8. Shift
String in java :-
4. String class provides a lot of method of to perform operation on string such as compare ( )
equals, split , length , replace compare to , intern , substring , etc.
5. The java lang string class implements comparable relies able and char sequence interface.
How to create string objects:- There are two ways to create string object
By string literal
I. Literals are define as the siynthatic representation of Boolean , char numeric as string data
String s= “ Abhishek “;
1) Each time you create S L the JVM check s the string “constant tool “ first ..
2) If the string is already exist in the tool a reference to the fooled instance is interned .
3) If the string does not exit in the pool a new string is created and placed in the tool .
String s2 = “hello”;
Diagram
1) String obj are stored in memory and known as string constant pool.
2) Java uses the concept of string literal to main to java more memory efficient because already
in the string constant pool .
String s1 = “java”
Sout (s1);
Sout (s2);
Sout (s3);
}
}
Imutable string:-
Class test_string
String = “Abhishek”;
s.concat (“tyagi”);
cout (s);
Note:- java uses the concapt of string literals that’s why object in java are imutable.
Suppose there are 5 reference variable and all refered to one object and if that one reference
variable changed the value of object then it will affected to all the reference variable .
{
public static void main (string [] args)
{
}}
Output:=
Be-yourself
String comparison :-
-→ It is uses in authentic, equal () function sorting (by compare to function ) reference matching
( by equal () operator).
{
string s1 = “hello”;
String s2 = “hello”;
String s4 = “world”;
Sout(s1.equal (s2));
Sout(s2.equal (s3));
Sout(s3.equal (s4));
String concatenation :- In java string concatenation form a new string that is the combination of
multiple string and as we already know that concatenation means a series of interconnected obj/
series. There area two case to concat string in java.
1) By + operator
2) By concat() method
String s1 = “Abhishek”;
String s3 = s1 + s2 ;
Sout ( s3 );
}
}
Java classes and objects:-= An entity that has state and behavior is non as object . it can be physical
or logical. An object has following characterstics :-
1) State:- It requested the data of an object that called reconsider the value of object created
in a system .
2) Behavior :- IT represent the behavior or we can say that it is used to represent the
functionally of an object such that deposit, withdraw etc.
3) Object definition:- An object is a real world entity . An object is an instance of a class .
4) Class :- This is a group of object which has common property. It is a template or btw print
from which object are not be physical . A class in java can contain physical . A class in java can
contain .
→Field
→construction.
→nested class
→methods.
→blocks
→interfaces.
Class (class name)
Field;
Method;
Instance variable :- A var which is create inside the class but outside the method is known as instance
variable. It does not get memory at compile time, It get m/y at runt time when an object an instance
is created that why it is known as an IV.
Note:- IN java a method is like a function which is use to expose the behavior of object the
advantages of method is code responsibility and code optimization.
The new Keyword:- is used to allocate memory at runtime and all objects get memory in heap
memory area .
Class student {
Int id;
String name;
Sout (s1.id );
Sout (s1.name );
1) By reference variable
2) By method
3) By construction
Class student
Int id ;
String name;
{
Student s1 = new student ();
Constructor :- In java a constructor is a block is similar to the method. It is called when an object
of a class is created . At the time of callins constructor many of a object is allocated in the
memory.
It is a special types of method which is use to initialized the object every time an object is
created using “new” at last one constructor is called.
It is called a default constructor if then is no constructor available / declared in the class. In such
cases java compiler provides a default constructor by default . There are two types of constructor
in the java .
1) Default constructor
2) Parameterized
1) Default constructor :- It is called constructor because it construct the value at the time of
object creation.
A java constructor did not be abstract, static final and syncnonise we can use access modifies
while declaring a constructor . it controls object creation.
In other words we can say that we can have private , protected public or default constructor in
java.
Default constructor
Class stud
{
int id;
Class stud {
Int id ;
String name;
Id = I;
Name = n;
Void display ()
Sout(“id “ + “name” );
S1.display ();
S2.display ();
Data abstaraction:- A database system is a collection of interrelated data and a set of program that
allows user to access and modify these data. In major purpose of DBS is to provide the user only that
much information that is required by them. This means that the system does not disclose all the
details of does not disclose all the details of data .
Rather It bides certain details of how the data is stored and maintain.
• Physical label:- It is the lowest level of abstraction and describe how the data actual stored
on storage media. It describe complex low level data structure in details.
• Logical label:- It is next higher level of abstraction and describe what data are stored in the
database and what relationship exist among those data. Thus it describe the entire database
in terms of a small number relatively simple structure.
• Vies level:- IT is the highest level of abstraction and it concerned with the main in which the
data are mute by individual user, most of the user of database. Instead the need of apart of
database relevant to that. To simplify the user interaction this level is defined. Thus, the
system provide many view for the same database.
Constructor overloading:- it is a technique of having more than one constructor with different
parameterized list . They are arrange in a way that each constructor performs different task. They are
different by the compiler, by the number of parameterized in the list of there types;
Class stud
Int id ;
String name ;
Int roll_no;
Id = x;
Name = n;
Roll_no = y;
{
id = n;
Name = n;
Void display ()
S1.display ();
S2.display ();
}
Different between constructor and method :
Constructor :
Method :-
Copy constructor :- there is no separate copy constructor in java however we can copy the values
from one object to another like c , C++.
There are many way to copy the values from one object to another like cc in c++.
There are many way to copy the values of one object into another .
1) By constructor
2) By assigning a value of one obj to another .
3) By clone () method of obj class.
Class student
Int id ;
String name;
Id = I; name=n;
Student (student s)
Id = s.id;
Name = s.name;
Void display ()
{
S1.display();
S2.dispaly();
}}
Output:- 101, A
101, A
Inheritence :- It is mechanism in which are object acquire the properties and behaviour of parent
object.
→Advantage of inheritance is that, when it inherit from an existing class. You can reuse method
and feeds of the parent clan moreover you can add new method, and feeds in your current class.
→Sub class:- It is a class which inherit the other class. It is also called a derived /extended/ child
class.
→superclass:- it is the class from where a subclass inherit the feature. It is also called base [print
class].
→reusability :- it is a mechanism which facilitate you to reuse the fields of an exisiting class when
you create a new class .
{
Fields //(data type)
Method // function
The extends keyword indicates that you are making a new class that derived from an existing class .
C++ Java
1. It is platform dependent. 1. it is platform independent .
2. It is namely used for the system 2. it is mainly need. For application
programing programing and is willy used in enterprices.
3. It supports the ‘goto’ statement. 3. it doesn’t support ‘goto’ statement
4. It support multiple inheritance . 4. it doesn’t support multiple inheritance
through class but it can be achived by using
interfaces in java.
5. it supports operator overloading 5. It doesn’t support operator overloading
6. it supports both ‘call by value’ or ‘call by 6. it supports call by value only
reference’.
7. it is an object oriented language however in 7. it is also an object oriented language
c++ a single hierarchy is not provide however everything in java is an object except
the fundamental types,it is a single heirachy as
everything derived from java. language
#Java language:- A set of syntax symmetric and keywords that can be compiled into an executable
form called bytecode. The bytecode are then interpreted by a virtual java machine (JVM). Some
features of java includes object- oriented programing , automatic memory management .
#Java platform:- A collection of technology that allows for the development of application for
different execution environment.
1) Java platform
2) Standard edition (java se)
3) Java platform enter prices edition (java EE)
4) Java platform micro edition (java HE)
i) Single
ii) Multilevel
iii) Hierarchical
Double pi=3.14;
Return pi*r*r;
}}
Class
Note:- Multiple inheritance is not supported in java to reduce the complexity and simplify the
language .
Consider a scenario when a,b,c are three classes .The class inherit A and B classes. If A and B have
the same method and you called it from child class object, there will be ambiguity to call the method
of a or b class.
Since, compile time error are better than run time error, java compile time error, if you inherit two
classes.
So , whether you have same method or different there will be compile time error .
#Aggregation Java:- if class has an entity reference , it is known as aggregation , we use aggregation
for code reusability .
Syntax:-
Class employe
Int id;
String name;
Address, address;
------------------
i) Inheritance should be used only if the relationship Isa maintain throughout the lifetime
of the object involved , otherwise aggregation is the best choice.
#Method overloading:-
i) If a class has multiple method having same name but different parameters is known as
method overloading .
ii) Suppose you have to perform addition of given numbers but there can be any number of
given numbers but there can be any numbers of given arguments if you write the
method such as A (int, int) for 2 parameters B (int, int, int) for 3 parameters then it may
be difficult for you as well as other parameter to understand the behaviour of the
method because its name different .
iii) The advantage of method overloading is that it increase the read ability of the program .
iv) There are two ways to overloading the method in java.
• By changing number of arguments .
• By changing datatypes.
Note:- Method overloading in java is not possible by changing the returns type of the method .
# Method overloading:-
i) If subclasses has the same method as declared in the parent class , it is known as
method overriding .
ii) It is used to provide the specific implementation of a method which is already provided
by its superclass.
iii) It is used for overtime polymorphism
iv) There are some rules to be followed by using java method overriding .
• The method must have the same name as in the parent class.
• The method must have the same parameter as in the class.
• There must be an ISA relationship .
# Java package:-
Java
#package addition ;
}}
# package addition 2;
System.out.println(a+b);
}}
#Advantage of packages:- IT is used to categorized classes and interfaces so that they can by
easily maintain . it provides access direction , it removes name collection.
• Reusability
• High security
• Memory management
• Easy to locate related classes
• There are ways to access the package form outside the package.
I) Import package .*
II) Import package. Class name
III) Fully qualified name
Package pack;
Public class A
System.out.println (“Hello”);
}}
Package mypack;
Import pack.A ;
Class b{
A obj = new A () ;
Obj.message;}}
# using fully qualified name:-
If you use fully qualified name then only declared class of this package will be access able now In this
way we don’t need to import. But we need to use fully qualified name every time when you are
accessing . The class are interface . it is generally used when two package have same class name i.e.
jave.util , java. Sql .
# Sub package in java:- Package inside the package is called subpackage it is used to categonized the
package further in such the way that we don’t need to create a number of package to define the
code.
# user input in java:- To input from the user in java the scanner class is used.
The scanner class is a built_in class of java.util package java scanner class provide many built in
method to take different types of user inputs form user there are same steps to be follow to we
scanner class for the user input in java
Step1:- import scanner class:- firstly the user need to import the scanner class to use its method
Example :- If the user want to input an int, value, use next int(_) method.
The JRE is one of the B interrelated components for developing and running java programs. The other
components are JDK JVM.
• The JDK is a set of levels for developing java application . Developers choose JDK by java
version and by package edition JAVA enterprises edition (JAVA EE) , java special edition (JAVA
SE ). Every JDK always includes a compatable JRE because the java program is a part of a
process of developing a java program .
• The java runs time java application , every JRE includes a default JRE but developers can
choose another that means the specific resources needs for their application .
The JRE combine java code by using the JDK with the necessary library requires to run it on a
JVM’s then create an instance of the jvm that runs the resulting program . JVM are available
for multiple operating system and program crated with the JRE . in this way the java runtime
environment is what enables a java program to run in any operator system without
modification .
• Working of JRE :- the JDK and JRE interact with one another to create a rustainble the
runtime environment that enables the seamless execution of java based application in
vitually any os. The attribute makeup the JRE runtime architecture are:-
i) Class loader:- IT dynamically loads all clanes which are necessary to run a java
program , since java classes are only loaded into memory when they are required the
JRE uses class loader to automatic this process on diamond .
ii) Byte code verifier :- It ensure the format and accurancy of java code before it passes
to the interpreter. It code system integrity or access rights then the class will be
consider corrupted and wants to be loaded .
iii) Interpreter :- After the byte code successfully loads the java interpreter creates an
instance of JVM that allows the java program to be run natively on the under time
machine.
What does JRE consist of :- Beside the JVM , JRE is composed of various other software tool and
feature to get the most out of java apps .
This plug-in adds java compilation testing and bundling capabilities to a project..
# Integration library:- JRE provides several IL to assist developers in creating seamless data
connection between their application and services.
i) Java IDL:- it uses common object , request architecture to support distributed object
written in java programing language .
ii) Java database connectivity (JDBL):- it provides tools for developers to write application
with access to remote relationship database i.e. flat files and spreadsheets.
iii) A programing interface and directory service that helps client create portable
application that can fetch information from database by using naming conventions .
# language and utility library :- included with JRE are java long and java. Util package that are
fundamental for the design of java application , package versioning, management and monitoring, it
included some of main package are ….
Java Api:-java application programing interface is a software components that connects different
parts of the java programing stack. It is integrated into JDK and is a key part of open and internal
development. Java Api are made up of predefine classes interfaces and method that developers can
used in there java application they act as a bridge between different software components and
allowing them to interact with each other in standardized way. The java Api can be a value able tool
for developers they let you access a wide variety of third party services with just a few lines of code,
which can be helpful in solving problem or building apps that are difficult to do without them.
1. Public java Api are often refer to as open java Api as they are part of JDK and don’t need any
extra payment. Also they are free from the areas and use causes for there implementation.
2. Private or internal java Api is design by a particular developers aur organization and is access
able only to authorized professional
3. Partner java Api are the third party Api often to business for specific operation.
4. Composed java Api is basically microservices developed by using different kind of Api.
5. Web java Api is accessed by VIA http protocol and is used to stablished a communication
bridge for browser based application/ services like web storage and web notification .
Example:- REST API makes code available and useable for every related application or
program .
Advantages of API:-
The direct impact of using Api in java is expedient the development as it makes predefined classes
and packages available for intended program . however that’s not the only advantages but more .
i. Java API keep human involvement as least as possible and empower computer so much that
they take care of the entire development job. Java API’s deploy automation of highest grade
into action and makes crucial work flow quick and error free.
ii. Service delivery is much more flexible with java Api as these Api’s are available for every
components and lift all the data access restriction. Additionally, the content or code
generated using java Api is set to be released and work . All the related channel are allow to
access this freshly generated content. This makes development quick from the ground level
iii. Java Api exhibit unmatched integration abilities as they ready to be embed in any software or
program or website . The high and integration makes data fluid enough to be used at any
platform where ever enhanced user experience for fulfilment demands .
iv. There are some other most important advantages of Api .
1. Adaptation
2. Customization
3. Scope
4. Integration
5. SQL support
6. Application
7. Efficiency
8. Automation
Java applets:- applets is a special types of program that is embedded in the web page to generate
the dynamic content. Java applet is an entity which runs inside the browser and works at clint site.
Hierarchy of applets:-
Object
Components
container
Pannel
Java applets
Lifecycle of java applets:-
1. Firstly applets is initialized when started, then printed, then stop and then destroyed lastly.
Applet is
initialized
Applet is stopped
Applet is painted
Java. Applet. Applet class:- for creating any applet “java. Applet. Applet class “ must be inherited.
a) Public void int () :- it is used to initialized the applet, it is invoked only one
b) Public void start () :- it is used to start the applet it is invoked after the int () method or
browser is maximized .
c) Public void stop () :- it is used to stop the applet , it is invoked when applet is stop or
browser is minimized .
d) Public void destroy () :- it is used to destroy the applet and invoked only once .
Local and remote applets:- an applet developed locally and stored in a local system smooth as local
applets. When a web page is trying to find a local applet it does not need to use internet and
therefore the local system does not require the internet collection is simply purchase the direction in
the local system and loads the specify applets.
A remote applet is that which is developed by someone else and stored on a remote computer
connected to the internet. If our system is connected to the internet so we can download the remote
applet In to our system via the internet and run it . in order to load a remote applet we must know
the applet address that is URL .
Important :- Applet v/s application :-
I. When we need to include something dynamic to included in our web page then
we can use applet directly .
II. We use applet when we required some flash out like applet to produce some
sound , animation or some special effect when displaying some certain pages.
III. We use applets when we want to create a program and want it to make
available on net so that it could used by other .
Step 1. :- in order to create an applet tab we have to use two classes namely ‘applet’ and ‘graphics’
from the java class library. The applets class which is contain in the java , applet package provides life
and behaviour to the applet through its methods such as init() , start() and point() , unlike application
to which the execution starts from main() function, in applets class methods for running and rapping
the applet code when applet is loaded the applet class therefore maintains the lifecycle of an applets
the point() methods of an applets class, when it is called dislocate the result of the applet code on
the screen . The output ma be text, graphics or second , the point () methods require a graphic
objects as an argument.
Syntax of point():
It provides the applet code imports the java.Awt package contained in the graphics class.
Step2:- Now after typing the code, you have to safe save the file with any name with an
extension java and write after that you have to convert the java file to generate , class file
which is also called as byte code which is automatically generated to after the compilation of
the program.
Step3:- in order to run java applet, user used to create an HTML file and associate the applet
code with the HTML file.
Step 4:- To incorporate applet code to HTML document . we use <APPLET> .
In order to incorporate: the class file with <APPLET> so that it should be attached with HTML
file.
<applet code= file name.class height =200 widht = 400>
</applet>
Running the applet:- the order to run applet we must area have there 3 files under these
directories.
Example :- hey there.java, hey there. Class, hey there. HTML
# How to run an applet:-
• BY HTML file:-
Import java. applet . Applet ;
Import java. Awt. Graphics;
Public class first extends applet
Public void point (Graphics g)
{
g.drawstring(“welcome”,150,250);
}}
# <HTML>
<body>
<applet>
</body>
</HTML>
Abstract window tool kit :- It is an Api to develop GUI or window based application in java. AWT
components are platform dependent i.e. components are displayed according to the view of OS
.AWT is heavy weight i.e. the component of AWT through using the resources of OS . The
java.AWT.package provides classes for AWT or API such as text field, label text area , radio button ,
checkbox, choice list. Etc.
object
button
label
component
checkbox
choice
list
container
window
panel
applet
frame dialog
1) Container:- the container is a component in AWT that can contain other component like
buttons, text field and label etc. The class that extends container class are known as
container such as frame , dialog , panel .
2) Window:- The window is a container that has no border and menu bars you must use frame ,
dialog or another window for creating a window .
3) Panel:- The panel is a container that does’t contain the title bar and menu bar . it can help
other components like button text field, etc.
4) Frame:- The frame is a container that contain title bar and border.it is a container for other
GUI components and is used to create the main window of the Application.
→Frame class in java:-
Package = java.awt
External = windows
Implement = menu container
-→key features of frame:- it has the title bar that display the title of the window .
1) it is surrounding with a border .
2) it is resize able as it can be resized by the user.
3) it is closeable as it is closed by the user.
→common method of frame class:-
1) Set Title () :- Set the Title of the windows .
2) Set Size ():- Its Set the size of the windows.
3) Set Location ():- Its set the location of the windows.
4) Add ():- it adds component to the window .
5) Pack ():- It pack the window to its prefer heigh.
6) Set visible ():- it makes the windows visible or invisible .
Impact java.awt.frame;
{
public static void main (string [] args)
Frame.pack();
Frame.setvisible(true);
}
Useful method or components class:-
Method Description
1).
2) integrity method:- insure data has not been tempered with or altered during transmission or
storage.
3). Non repudiation :- from denying that they sent a message or data.
5) digital certificate;- validate the authentication of digital certificate , used for secure connection
and data inscription .
6) software distribution :- verify the authenticity integrity of software download insuring that they
sources.
Java beans :-reusability is the main concept in any programing language. Java beans is a software
components that has been design to be reusable in a variety of environments .
Java beans is a portable, platform independent model return in java programing language. Its
components are refers to as beans .
1) Java beans are classes which in capsulate several object into a single object. It helps in
accessing these objects from multiple places, java beans contains several elements like
constructor, getter /seter methods and much more .
Reusability : java beans can be easily reused in multiple application shaving time and effort
in development .
Encapsulation : java beans can encapsulate data and functionality making it easier to
manage and maintain code .
Plate form independent :- java beans can be used on any platform that supports java ,
making it highly portable and versatile.
Event handling : to handle events , a listener must a register java beans when an event occur,
the bean notify all register listeners. The listener than perform the necessary excel in
response the event .l,
1) The power of beans is not limited to design user interfaces a bean can be a non visual
components such as a data structure a proxy or proxy for a remote data base . bean
builder tools manipulate beans , helping to build application without requiring you to
right code . more over beans are not only useful in application design tools they can cure
useful in runtime environment as well ,
Features of java beans:-the bean specification define three tyupes of bean feature . to another
application on class, describing the state and behavior of the beans the three type of beans features
are :
All beans features must be public , this allows any other beans to inspect and modify properties ,
register itself as an event listener or call provided methods . this doesn’t mean that the actual data
inside the class means to be public , nor do all methods in the class needs to be public .
→TO use of simple naming convention a bean enables application to determine which features it
supports .Tools discover being features solely through the names of the public method define in a
bean class. A bean enabled tool can use the java language reflection API. To determine which public
method a class defines , the tool can also determines available bean features based on the hance of
those methods some beans also provides an explicit class called a bean info class that describes
features in more detail but this is not necessary this additional information can enhance design time
use of bean but has no affect on the run time behaviour of the bean .
# properties of java beans:- it may be read , write read only and write only. Java beans features
are accessed through two methods in the java beans implementation class.
If the property name is first name, the method name would be get() name to read that property .
this method is called the accessor .
ii) Set property name()
For example, if the property name is firstname, the method name would be
setfirstname() to write that property . This method is called the mutator.
Properties:- Properties describe part of the state of its bean, usually information that can
distinguish different instances of a bean. There are two types of properties: simple and indexed .
• Simple Property
• Simple properties act like individual bits of data, describing the state of a bean. You define
simple properties using sets of methods that match the following patterns:public TypeName
getPropertyName()
• TypeName is the name of a class or primitive type, and PropertyName is the name of the
property. The presence of a get or is method defines a readable property. A set method defines a
writeable property. The property name is actually a lower-cased version of whatever follows the
get or set in the method declaration.
Note:- that there can be both a get and is method for a boolean property; the is
method is allowed for readability. Normally, you define the get and set methods, but
sometimes the get method doesn’t read naturally.
For example:-
if (list.isEmpty()) {...}
if (list.getEmpty()) {...}
• The beauty of this model is its simplicity. Many programmers already use get and set methods
to access their data, so defining properties is no different from their current style.
• A tool that recognizes these get and set methods can present a list of properties to a user,
enabling the user to specify property values. The tool generates code to pass the specified values
to the set methods.
• Because the tool is only querying the names of the methods, there does not need to be any
actual data corresponding to the property. A property could simply be a computation or an
alternate means to validate and set other data inside the class. An isEmpty() method might
simply count items in a referenced list, or a if the property name is first name , the method name
would be set first name () to write that getMaximumValue() method might return an integer such
as five.
Indexed Properties :-
ndexed properties are an extension of simple properties that allow multiple values for that
property. The property acts like an array, even if there is no actual data for that property or if the
data is stored in a non-array structure.
• Recognizing these methods, a bean-builder tool can present a (possibly editable) list of values
for setting the property.
• Bound and constrained properties fire events that report any modification to their state.
Bound properties notify registered listeners after their state has changed, while constrained
properties notify listeners before they change, allowing those listeners to veto the change.
You can bind and constrain simple or indexed properties.
• Bound or constrained properties greatly enhance the flexibility of a bean. Bound properties
enable you easily to keep property values in different beans synchronized. VisualAge for Java
provides techniques to take advantage of bound properties. Constrained properties allow
you to plug in validation, in the form of listener objects, rather than hardcoding that
validation into the property code itself.
JavaBeans conventions .
• It should have a public no-arg constructor.
All properties in java bean must be private with public getters and setter methods.
Must implement Serializable. as it allows to save, store and restore the state of a
JavaBean you are working on
i) In object serialization an object can be represented as a sequence of bytes that
includes the object's data as well as information about the object's type and the
types of data stored in the object.
ii) After a serialized object has been written into a file, it can be read from the file
and deserialized that is, the type information and bytes that represent the object
and its data can be used to recreate the object in memory.
Setter and Getter Methods in Java
Properties for setter methods:
• It should be public in nature.
• The return type a should be void.
• The setter method should be prefixed with the set.
•
• It should take some argument i.e. it should not be a no-arg method. Properties for getter
methods:
• It should be public in nature.
• The return type should not be void i.e. according to our requirement, return type we have to
give the return type.
• The getter method should be prefixed with get.
• It should not take any argument.
Bean persistence:-
Beans use Java object serialization, by implementing the java. io. Serializable interface, to
save and restore states that might have changed as a result of customization. A bean has the
property of persistence when its properties, fields, and state information are saved to and
retrieved from storage. Component models provide a mechanism for persistence that
enables the state of components to be stored in a non-volatile place for later retrieval.
Methods: Methods in JavaBeans are similar to the normal Java methods. It does have any specific
naming convention.
• Run anywhere; write once – Java Beans eliminates the need for writing software repeatedly.
• One can work with JavaBeans on Numerous local platforms, which makes it valuable in the
global market.
• JavaBeans can capture the events that are sent by other objects. It enables object
communication.
• An application developer can control Methods, events, and the properties of any Java beans.
• Zero hassle at run time with auxiliary software; one can configure beans during design time.
• Reusable: One can make a persistence configuration setting in JavaBeans. Persistent storage
and restoration later can save the configuration setting of the bean.
Interface:- it is a blueprint of class . it has static constant and abstract methods. It is a mechanism to
achieve abstraction and multiple inheritance in java.it can have abstract methods and variable and it
be instantiated just like abstract class. It also represents I.S.A relationship .
➔ It provides total abstraction ,means all the method in an interface are declared with the
empty body an all the fields are public static and final by default .
➔ A class that implement an interface must be implement all the methods declare in the
interface .
SYNATX-> interface<interface_name>
{
//declare constant fields
//declare methods that abstracts
// by default
}
Note:- the java compile at public and abstract key word before the interface methods . more over it
adds public , static and final keywords before the data member , in other words interface fields are
public static and final by default and the methods are public and abstract .
Interface Interface
Class
Interface
Class Class
Interface printable
Void print();
Sout(“Hello”); }
Obj.print();
}}
Output:- “Hello”
Input -output :-
➔ Java input and output is used to process the input and produces the output .
➔ Java use the concept of a stream to make input and output operation faet.
➔ The java.io package contains all the classes required for input of output operation .
➔ We can perform file handling in java by java i/o API
Stream :-
➔ Output stream:- Java application uses an output stream to write data to a destination ; it may
be a file, an array peripheral device or socket .
➔ Input stream :- java application uses an input stream to read data from a source; it may be a
file , an array peripheral device or socket .
The Working of java output stream and input stream is given below:-
➔ It is an abstract class.
➔ It is the superclass of all classes representing an output stream of bytes.
• public void write (int) throws I/o • used to write a byte to the current
exception . output stream .
• public void write (bytes) throws I/O • used to write an array of byte to
exception current output stream .
• public void flesh() throws I/O • flushes the current output stream
exception . • used to close the current output
• public void class() throws I/o stream .
exception.
Output stream hierarchy:-
➔ it is an abstract class .
➔ it is the superclass of all classes representing an input stream of bytes.
Methods Description
• public abstract int read() throw to • Reads the nest bytes of date from the
exception. input stream.it return at the end of file .
• Public void class() throws I/O exception. • Used to class the current input stream .
Input stream Hierarchy:-
Try
Fileoutputstream.sout=new fileoutput
Stream(“0;\\testout.text”);
Fout.write(65);
Fout.class();
System.out.println(“success”);
}
Catch(exception)
System.out.println(e);
}}}
Output:- Success.
Syntax:
Output stream os= new buffered output stream (new file output stream
(“0:\\io package\\testout.ext”));
Declaration:- public class buffered output stream extends fetch output stream
Exceptional handling:- it is a mechanism that allow handling and managing run time errors or
exception by ensuring that the program doesn’t terminate abruptly without a major effect. It
enables developers tool detect exception . handle exception and recover from exception . an
exception is an event that distrupt the normal flow of the program it is an objective which is at
run time. And exception i.o exception SQL exception remote exception etc.
Example:- statement;
statement 2;
Statement 10;
There are 10 statement in code and there occur exception at statement 5 then rest of code will
not execute i.e; statement 6 to 10 and if we perform exception handling, rest of statement will
execute that’s why we use exception handling in java.
Types of Exception:- Mainly there are 2 types of exception
➔ Check
➔ Uncheck
A errors is considered as uncheck exception which came from run time error .
➔ Check exception:- The class which directly inherit “throwable” class except “runtime
exception and “error” are known as check exception.
Ex:- io exception SQL Exception
Check exception are checked at compile time.
➔ Unchecked Exception:- The class which inherit run time exception are know as run time
exception are known as run time exception such as arithamatic null pointer array index out
of bound exception .
➔ Error exception:-- error are irrecovroable
Ex; out of memory error virtual machine error etc.
# hierarchy of exception handling :-
Exception keyword :- There are 5 keywords in handling exception in java i.e, try , catch finally throw
.throws.
Try:- it is used to enclose the code that might through an exception and it must be through an
exception and it must be used within the method if an exception occurs at the particular statement
of ‘try’ blog . the rest of the block code will not to keeping the code in try block that will not throw an
exception .
Catch (exception_class_Name.ref)
{}