0% found this document useful (0 votes)
3 views45 pages

Java Theory

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 45

1

IMPORTANT TOPICS (priority wise)


1. Exception Handling 27
2. String 34
3. String Buffer 35
4. Thread 29
5. Inter-thread 33
6. Applet 36
7. Servlet 40
8. Inheritance 10
9. Interface 18
10. Session vs. Cookie 44
11. Applet vs. Servlet 44
12. Polymorphism 13
13. Method Overloading 13
14. Method Overriding 15
15. Abstraction 17
16. RMI 38
17. Final 25
18. Finally 26
19. Finalize 26
20. Constructor 08
21. Synchronization 33
22. Runnable Interface 31
23. Garbage Collection 25
2

Object-Oriented-Programming (OOP)
Object Oriented Programming is used to describe programming
approach based of classes and objects.

Difference between Object Oriented Programming and


Structured Programming
Structured Programming is designed which focuses on process/
logical structure and then data required for that process.
Structured programming follows top-down approach.
Object Oriented Programming is designed which focuses on
data. Object oriented programming follows bottom-up
approach.

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

Dot operator ‘.’


Dot operator is used to connect object with its class’s data and
methods so that we can use them as normal variables and
functions.
SYNTAX:
object.data;

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

There are various functions of Scanner class for different data


types. Some of them are:

 next() - To take word from user.


 nextInt() - To take interger.
 nextFloat() – To take float number.
 nextDouble() – To take double number.
 nextLine() – To take String from user.

JVM – Java Virtual Machine


JVM (Java Virtual Machine) is an abstract machine. It is a
specification that provides runtime environment in which java
bytecode can be executed. JVM are available for many
hardware & software platform. It is platform dependent.
The JVM performs following operation:

 Loads
 Verifies
 Executes code.
JVM provides:

 Memory area
 Class file format
 Register set
 Garbage-collected heap
7

 Fatal error reporting.

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;
}
}

Abstract Data Type


A set of data values and associated operations that are defined
independent of any particular implementation.

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

A new thread begins its life in a new state. It remains in


this state until the program starts the thread.
 Runnable –
When a new thread starts executing its task, then its in
Runnable state.
 Waiting –
A thread stays in waiting state when it waits for another
thread to perform a task. A thread goes back to Runnable
thread after waiting is finished.
 Time waiting –
A thread can stay in waiting state for a specific period of
time. It will go back to running state either when given
time expired or the event it was waiting for occurs.
 Terminated-
A Runnable thread goes to Terminated state when it
finishes its task or get terminated.

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.

 public final void setName(String name)-


Changes the name of the Thread object.
 public final void setPriority(int priority) -
Sets the priority of this Thread object. The possible values
are between 1 and 10.
 public final void setDaemon(boolean on)-
A parameter of true denotes this Thread as a daemon
thread.
 public final boolean isAlive()-
Returns true if the thread is alive.
32

Class making SYNTAX:


class class_name extends Threads{
public void run(){
Your_code;
}
}
Thread making and calling SYNTAX:
class_name object_name = new class_name();
object_name.start();

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

To delete all characters from starting_index to


ending_index.
 reverse()-
To reverse a string.

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 - Remote Method Invocation


Remote Method Invocation (RMI) is an API that allows an object
to invoke a method on an object that exists in another address
space, which could be on the same machine or on a remote
machine.
It allows objects on one computer or Java Virtual Machine
(JVM) to interact with objects running on a different JVM in a
distributed network.
The RMI provides remote communication between the
applications using two objects stub and skeleton.

Stub Object: The stub object on the client machine builds an


information block and sends this information to the server.
The block consists of

 An identifier of the remote object to be used


 Method name which is to be invoked
 Parameters to the remote JVM

Skeleton Object: The skeleton object passes the request from


the stub object to the remote object.
It performs the following tasks
39

 It calls the desired method on the real object present on


the server.
 It forwards the parameters received from the stub object
to the method.

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:

 Servlets work on the server side.


 Servlets are capable of handling complex requests
obtained from the web server.

Servlet execution process:


1. The Clients send the request to the Web Server.
2. The Web Server receives the request.
3. The Web Server passes the request to the corresponding
servlet.
4. The Servlet processes the request and generates the
response in the form of output.
5. The Servlet sends the response back to the webserver.
6. The Web Server sends the response back to the client and
the client browser displays it on the screen.
41

Life cycle of servlet:


1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

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:

 JDBC-ODBC Bridge Driver


 Native Driver
 Network Protocol Driver
 Thin Driver
43

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

Difference between Session and Cookie

 Sessions are server-side files that store the user


information, whereas Cookies are client-side files that
contain user information on a local computer.
 Sessions are cookies dependent, whereas Cookies are not
dependent on Session.
 The session ends when the user closes the browser or
logout from the application, whereas Cookies expire at the
set time.
 A session can store as much data as a user want, whereas
Cookies have a limited size of 4KB.

Difference between Applet and Servlet

 A Java applet is a small application which is written in Java


and delivered to users in the form of bytecode while A
servlet is a Java programming language class used to
extend the capabilities of a server.
 Applets are executed on client side, whereas Servlets are
executed on server side.
 Cycle of Applets are init(), stop(), paint(), start() and
destroy() while Lifecycle of servlets are init( ), service( ),
and destroy( ).
45

 Applets use user interface classes like AWT and Swing


while in Servlet, no User interface required.
 Applets are more prone to risk as it is on the client
machine, whereas Servlets are under the server security.

You might also like