Java Theory
Java Theory
Java Theory
Object-Oriented-Programming (OOP)
Object Oriented Programming is used to describe programming
approach based of classes and objects.
Print function
In JAVA, the most common function used to display data is
System.out.print(“ ”);
Alternative function which also jumps to next line automatically
is
System.out.println(“ ”);
3
Class
A class is a collection of objects of similar types. A class is a
user-define type which holds data (variable) and method
(function) in it which we can use via their objects. A class can
have many objects. Only class object’s can access class’s data.
SYNTAX:
class class_name{
access specifier data_type variable;
access specifier return_type function()
}
NOTE: If we do not put any access specifier, all data will be
available to whole program by default. Cannot be access from
outside the program.
Object
Object is a variable of class which can access its data and
methods. As variables, we cannot make two objects with same
name or any object with keyword name. Every object have their
own data.
Initializing object SYNTAX:
class_name object_name = new classname();
4
Access Specifier
Access Specifier defines what members of an class can access
data.
Four types of Access Specifier in JAVA:
public – data starting with public keyword can be accessed by
any member of any class.
private – data starting with private keyword can only be access
class members and not by other class members.
protected - members cannot be accessed from outside the
class. However, they can be accessed in inherited classes.
no specifier – If we don’t add any access specifier in front of
5
data, then they can only be access by current file’s all class
members and not by outside of file.
Scanner Class
Scanner is used to take input from user. Scanner is a class which
we can use by importing a file “java.util.*”.
We need to create an object of Scanner class and put
“System.in” in parameter. Then we can take input from user
using that object.
We must connect next() function of Scanner class with our
object.
SYNTAX:
import java.util.*;
class File_Name{
public static void main(String args[]){
Scanner object_name = new Scanner(System.in);
char variable = input.next();
}
}
6
Loads
Verifies
Executes code.
JVM provides:
Memory area
Class file format
Register set
Garbage-collected heap
7
Member function
Function which is declared inside a class is called a member
function. Once a function is declared in a class, it is devoted to
that class and will only be used by an object.
SYNTAX:
class class_name{
return_type function_name(parameter){
definition;
}
}
Instance Variable
A variable created inside the class but outside the method is
called instance variable. Instance Variable does not get memory
at compile time but gets memory in runtime.
8
SYNTAX:
class class_name{
access_specifier data_type variable_name;
}
Encapsulation
The technique of binding data and methods into a single unit is
called Encapsulation. In OOPs, encapsulation is having data and
methods inside a class.
Constructor
Constructor is a special member function which is used to
initialize objects of the class. It has the same name as the class
with no return type and will only get called when an object is
created. Since, constructor is a function, it can also take
parameters. We can make as many constructors as we want by
changing its parameters.
In Inheritance, base class’s constructors are always in the
derived class constructor and base class constructor will get call
first when a derived class’s object is created.
9
Characteristics of Constructor
SYNTAX:
class class_name{
class_name(parameter){
contructor’s definition;
}
}
Types of constructor:
Default Constructor
Parameterized Constructor
Copy Constructor
10
Inheritance
Inheritance is a technique of creating a class derived from
another existing class to copy existing class’s properties.
The new class is called Derived/child/extended/sub class while
the class we used to create it is called Base/Parent/super class.
The derived class inherits all the properties, data and method
from its base class and can also have their own properties.
In Inheritance, base class’s constructors are always in the
derived class constructor and base class constructor will get call
first when a derived class’s object is created.
SYNTAX:
class derived_class_name extends base_class_name{
Properties;
}
Type of Inheritance:
Single Inheritance
Multiple Inheritance
Multi level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
11
Single Inheritance
When a single class is derived from a single base class, it is
called Single Inheritance.
Multi-level Inheritance
When we derive a class from a class which also a derived class
of 3rd class, then we call it Multi-level Inheritance.
12
Multiple Inheritance
When a derived class has more than one base class, it’s called
Multiple Inheritance.
Hierarchical Inheritance
When multiple classes are derived from a single base class, it is
called Hierarchical Inheritance.
13
Hybrid Inheritance
Hybrid Inheritance is a combination of Hierarchical and Multiple
Inheritance. When two classes are derived from a single base
class and those two derived class also have same derived class.
Polymorphism
The technique of having multiple methods with the same
name is called Polymorphism. The word polymorphism
comes with combining two word “poly” which means
many and “morphism” which means form.
There are three types of Polymorphism:
Function overloading
Operator overloading
Function overriding
14
Method overloading
Method overloading refers to creating multiple functions with
the same name. We can do this by two ways.
1. By changing their number of arguments.
2. By changing their type of arguments.
SYNTAX:
access_specifier return_type function_name(){
Definition;
}
access_specifier return_type function_name(parameter){
Definition;
}
Operator Overloading
Operator Overloading refers to creating functions with having
an operator as name.
Example: +();
We can only overload operators which already exist. Hence, we
cannot create a new operator.
15
SYNTAX:
access_specifier operator Operator_symbol(){
definition;
}
There are two types of Operator overloading:
Unary overloading
Binary overloading
Method Overriding
The technique of overriding/ rewriting a function in derived
class which was taken from base class is called overriding.
When we derive a class, it have all properties of base class. But
we can update base class’s function in derived class by declaring
it.
16
SYNTAX:
class base_class{
access_specifier return_type function_name(parameter){
definition;
}
}
class derived_class extends base_class{
access_specifier return_type function_name(parameter){
new definition;
}
}
Virtual Function
Virtual Function is a base class’s function which is overridden in
the derived class. They can have their own definition too. The
compile perform late binding on this function. The class having
a virtual function cannot have any objects. Virtual function is
created by adding virtual keyword in front of return type while
creating it.
SYNTAX:
17
class class_name{
virtual return_type function_name(){
definition;
}
}
Abstract Function
Similar to Virtual function, Abstract function is also declared
only to be overridden in derived classes. It has no
implementation/definition.
SYNTAX:
abstract return_type abstract_function_name();
Abstraction
A class having abstract functions is called abstract class.
Abstract class does not have much use unless it has a sub class.
Abstract class only exists to provide an interface for their
derived classes. We cannot create any object of abstract class
We must override abstract function otherwise the derived class
will become abstract too.
18
SYNTAX:
abstract class base_class_name{
abstract return_type abstract_function_name();
}
class derived_class_name extends base_class_name{
return_type abstract_function_name(){
definition;
}
}
Interface
An Interface is a blueprint of a class. It has only static constant
and abstract methods only. Similar to abstract class, it only
exists to give an interface to its derived class.
19
SYNTAX:
interface class_name{
return_type function_name(parameter);
}
class derived_class_name implements class_name{
return_type function_name(parameter){
definition;
}
}
Static
Static is a keyword which is mainly used for memory
management.
The static keyword belongs to the class than an instance of the
class. The static keyword is a non-access modifier which is
applicable for
Block
Variable
Method
Classes
20
Static Block
Static block of a class is invoked when program starts executing.
Static Variable
Every object has its own data / variables but static data is a
variable which only has one copy for all the objects of that
class. Every object of a class shares the same variable and
changes from one object will update static variable for all other
objects.
SYNTAX:
class class_name{
static data_types variable_name;
}
Static method
A function with static keyword is called static method. A static
method is can be called before any object of the class is
created. We do not need reference of an object to access static
method. That’s why the main function is also static function.
21
Static Class
A class with static keyword is called static class. We cannot
create a static class unless the class is nested or inside of
another class. The methods of static can be called directly by
connecting the nested class without outer class.
SYNTAX:
class outer_class_name{
static class nested_class_name{
return_type function_name(){
definition;
}
}
}
class File_name{
public static void main(String args[]){
outer_class_name.nested_class_name object=
new outer_class_name.nested_class_name();
object.function_name();
22
}
}
this
this keyword is used inside a class in the object’s place for a
reference of that object.
this keyword can be used to refer current class instance
variable.
this keyword used to invoke current class method (implicitly).
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can be used to return the current class instance.
SYNTAX:
class class_name{
access_specifier return_type variable;
access_specifier return_type function_name(){
this.variable = value; // “this” is the current object
23
}
}
this()
this() used to invoke current class constructor.
super
Similar to “this” keyword, super keyword is also used as a
reference of an object in the object’s place. But super keyword
is used inside derived class to take a reference of base class’s
functions.
SYNTAX:
class base_class_name{
access_specifier return_type variable_name;
}
class derived_class_name extends base_class_name{
24
derived_class_name(parameter){
super.variable_name = value;
}
}
super()
super() function used to invoke parent class’s constructor inside
derived class.
SYNTAX:
class base_class_name{
base_class_name(parameter){
definition;
}
}
class derived_class_name extends base_class_name{
derived_class_name(parameter){
super(parameter);
}
25
Garbage Collection
Garbage collection in Java is the process by which Java
programs perform automatic memory management.
When Java programs run, objects are created on heap which is
a part of memory.
When objects are no longer needed, the garbage collector
deletes these unused objects to free memory.
final
final keyword can be used along with variable to make it
constant. Value of final variable cannot be changed inside the
class or in derived class.
final keyword can be used along with method so that method’s
definition cannot be changed after defining once neither
directly nor in derived class.
final keyword can be used along with class to make it unable to
extend. A class with final keyword cannot have derived class.
26
finally
finally keyword is used for exception handling along with try
and catch.
A finally block will always execute even if there is no exception.
finalized()
finalized() is a method, which is available in Object super class.
The purpose of finalized method is to release the resources
which is allocated by unused object before unused object gets
removed by garbage collector.
Package
Java package is a group of similar types of classes, interfaces
and sub-packages.
There are built-in packages which have predefined class and
functions for programmer to use.
We can also make user-defined packages.
Package creating SYNTAX:
package package_name;
Package using SYNTAX:
27
import package_name;
Exception Handling
Exception Handling is a mechanism to handle the runtime
errors so that the normal flow of the application can be
maintained. Normally, the program stops when a runtime error
occurs but Exception Handling can perform a substitute task if it
happens.
5 keywords used for exception handling:
try
catch
finally
throw
throws
try
The code which might throw exception is written inside try
block. A catch block must be present right after try block with
alternative code.
28
catch
If try block gets exception, the alternative code which is
supposed to execute is written inside catch block.
SYNTAX:
catch(Exception exception_reference){ }
finally
The code which is should always run even if there is no
exception is written inside finally block. finally block is added
after try block.
throw
throw keyword is used inside a method to throw exception
towards catch block.
SYNTAX:
throw exception;
29
throws
throws keyword added while declaring the function which
might throw exception to pass it towards the catch block.
With throws keyword, we can pass more than one exception.
SYNTAX:
return_type function_name() throws exception{
code which might throw exception;
}
Thread
Multi threaded program contains two or more parts that can
run simultaneously at the same time.
Threads can be used to perform complicated tasks in the
background without interrupting the main program.
Thread object can be created extending its class from Thread
class.
Stages of Thread:
New -
30
Thread Priority:
When multiple threads run at the same time, thread priority
determines which thread will execute first. Their range is in
between MIN_PRIORITY to MAX_PRIORITY which is 1 to 10.
All threads have NORM_PRIORITY by default.
31
Runnable Interface
Runnable is a predefine Interface which have predefined
methods for threads.
Some of these methods are:
start() -
Starts the thread in a separate path of execution.
run() -
Gives a entry point for thread.
Thread(Runnable thread_object, String thread_name)-
Allocates a new thread object.
Thread Scheduler
Thread Scheduler decides which thread will run first. Only one
thread can run at a time.
Daemon Thread
Daemon Thread is invoked automatically after all the user
threads are terminated. It is used for garbage collection.
33
Synchronization
Synchronization is used to control the flow of multiple threads
which are running at the same time on the same objective. It
allows only one thread to word at one time on that shared
resource.
Mutual Synchronization
Mutual Synchronization uses three mechanisms to do
Synchronization which are:
Synchronized method.
Synchronized block
Static synchronization
Inter-Thread Communication
In this mechanism, thread in paused on a specific situation.
It is implemented by the following methods of thread class:
wait()
It causes the current method to wait until another thread
invokes notify() or notifyall().
notify()
It causes an already waiting thread to start running again.
34
notifyall()
It causes all the waiting thread to start running again.
FileInputStream
FileInputStream are used to read raw bytes from files.
FileOutputStream
FileOutputStream are used to write data in files.
Stream Tokenizer
The Java. io. StreamTokenizer is a class that takes an input
streamand parses it into "tokens", allowing the tokens to be
read one at atime. The stream tokenizer can recognize
identifiers, numbers,quoted strings, and various comment
styles.
String
Java.util.String have pre-defined methods to do various things
with String.
Some of them methods are:
35
toUpperCase() -
To convert all letters of string in Upper Case.
toLowerCase() –
To convert all letters of string in Lower Case
trim() –
To remove unnecessary spaces from front and end.
length() –
To display the length of String.
String Buffer
String Buffer helps us create mutable (modifiable) String.
We can do changes in these string which were not available
with String class.
Some of String Buffer’s methods are:
append(new_string)-
To add given argument after already existing string.
insert(index_location, new_string)-
To input another string in specific location.
replace(starting_index, ending_index, new_string)-
To replace all characters from starting_index to
ending_index with new_string.
delete(starting_index, ending_index)-
36
Applet
Applet is a special type of program which can embed in the
webpage to generate the dynamic content. It runs inside the
web browser and works at the client side.
An applet is embedded in an HTML page using the APPLET or
OBJECT tag and hosted on a web server.
Cycle of Applet:
37
init()-
This method is used to initialize applet. Its only called once
during the run time of applet.
start()-
This method is invoked after init() method. This method
makes out applet to start executing the task.
paint()-
This method is called each time an AWT-based applet’s
output must be redrawn.
stop()-
This method is used to stop applet. Applet won’t stop
permanently and can be started again using start().
destroy()-
This method is used to terminate our applet. It will
completely remove our applet from memory.
Container in Applet:
An applet container is the environment that runs a Java applet
and provides secure applet execution.
38
RMI Diagram:
RMI Steps
1. Create the remote interface.
2. Provide the implementation of the remote interface.
3. Compile the implementation class and create the stub and
skeleton objects using the rmic tool.
4. Start the registry service by rmi registry tool.
5. Create and start the remote application.
6. Create and start the client application.
40
Servlet
Java Servlets are the Java programs that run on the Java-
enabled web server or application server. They are used to
handle the request obtained from the web server, process the
request, produce the response, and then send a response back
to the web server.
The properties of Servlets are as follows:
Container Class
The Container class holds the methods for grouping the
components together, laying out the components inside it, and
dealing with events occurring within it.
Because Container is an abstract class, you never see a pure
Container object; you only see subclasses that add specific
behaviors to a generic container.
Containers are an integral part of SWING GUI components. A
container provides a space where a component can be located.
A Container in AWT is a component itself and it provides the
capability to add a component to it.
42
JDBC
JDBC stands for Java Database Connectivity. JDBC is a Java API
to connect and execute the query with the database. It is a part
of JavaSE (Java Standard Edition).
JDBC API uses JDBC drivers to connect with the database.
Java applications that manage these three programming
activities:
1. Connect to the database.
2. Execute queries and update statements to the database.
3. Retrieve the result received from the database
There are four types of JDBC drivers:
Dynamic Binding
When type of the object is determined at run-time, it is known
as dynamic binding. In Dynamic binding compiler doesn’t
decide the method to be called. Overriding is a perfect example
of dynamic binding. In overriding both parent and child classes
have the same method.
Session
A session is used to temporarily store the information on the
server to be used across multiple pages of the website. It is the
total time used for an activity.
The user session starts when he logs-in to a particular network
application and ends when the user logs out from the
application or shutdowns the system.
Cookie
A cookie is a small text file that is stored on the user's
computer. The maximum file size of a cookie is 4KB. It is also
known as an HTTP cookie, web cookie, or internet Cookie.
Whenever a user visits a website for the first time, the site
sends packets of data in the form of a cookie to the user's
computer.
44