Download as pdf or txt
Download as pdf or txt
You are on page 1of 3

Applet, LifeCycle & Digram Multithreading, Adv.

& Disadvantages Exception Handling:


An applet is a Java program that Multithreading is a Java feature that allows concurrent execution Exception is an unwanted or unexpected event, which occurs
can be embedded into a web page. of two or more parts of a program for maximum utilization of during the execution of a program, i.e. at run time, that disrupts
It runs inside the web browser and CPU. Each part of such program is called a thread. So, threads are the normal flow of the program’s instructions. Exceptions can be
works at the client side. An applet light-weight processes within a process. caught and handled by the program. Exception Handling in Java is
is embedded in an HTML page using Benefits of Multithreading:- one of the effective means to handle the runtime errors so that
the APPLET or OBJECT tag and Improved throughput. ... the regular flow of the application can be preserved. Java
hosted on a web server. Applets are Simultaneous and fully symmetric use of multiple processors for Exception Handling is a mechanism to handle runtime errors such
used to make the website more computation and I/O. as ClassNotFoundException, IOException, SQLException,
dynamic and entertaining. Superior application responsiveness. ... RemoteException, etc.
It is important to understand the Improved server responsiveness. ... There are two types of exceptions :
order in which the various methods Minimized system resource usage. ... 1. Checked Exception: Checked exceptions are called
shown in the above image are Program structure simplification. ... compile-time exceptions because these exceptions are checked
called. When an applet begins, the Better communication. at compile-time by the compiler.
following methods are called, in Disadvantages of Multi-threading:- 2. Unchecked Exceptions: The unchecked exceptions are just
this sequence: init(), start(), It needs more careful synchronization. opposite to the checked exceptions. The compiler will not check
paint(). When an applet is It can consume a large space of stocks of blocked threads. these exceptions at compile time.
terminated following methods are It needs support for thread or process. Example:
called, in this sequence: stop(), If a parent process has several threads for proper process public class JavaExceptionExample{
destroy() functioning, the child processes should also be multithreaded public static void main(String args[]){
because they may be required. try{
Garbage Collection It imposes context switching overhead. //code that may raise exception
Garbage collection in Java is the process by which Java programs int data=100/0;
perform automatic memory management. Java programs compile to Layout Manager & Its Types }catch(ArithmeticException e){System.out.println(e);}
bytecode that can be run on a Java Virtual Machine, or JVM for A layout manager is an object that controls the size and position //rest code of the program
short. When Java programs run on the JVM, objects are created on of the components in the container. Every container object has a System.out.println("rest of the code...");
the heap, which is a portion of memory dedicated to the program. layout manager object that controls its layout. }
Eventually, some objects will no longer be needed. The garbage Actually, layout managers are used to arrange the components in }
collector finds these unused objects and deletes them to free up a specific manner. It is an interface that is implemented by all
memory. the classes of layout managers. There are some classes that String Class:
Advantage: Removes bugs like Dangling pointer bugs, Double free represent the layout managers. 1. The String class is immutable.
bugs & Memory leaks. The Abstract Windowing Toolkit (AWT) has the following five 2. String is slow and consumes more memory when we
Disadvantage: Brings some runtime overhead which is out of layout managers:- concatenate too many strings because every time it creates new
control of programmers. java.awt.BorderLayout instance.
java.awt.FlowLayout 3. String class overrides the equals() method of Object class. So
Abstract class & Implementation java.awt.GridLayout you can compare the contents of two strings by equals() method.
A class which is declared with the abstract keyword is known as an java.awt.CardLayout 4. String class is slower while performing concatenation
abstract class in Java.It can have abstract and non-abstract java.awt.GridBagLayout operation.
methods. It needs to be extended and its method implemented. It 5. String class uses String constant pool.
cannot be instantiated. Interface, Implementation & Adv. : String Buffer Class:
Implementation of abstract class : An Interface in Java programming language is defined as an 1. The StringBuffer class is mutable.
abstract class Bank{ abstract type used to specify the behavior of a class. An interface 2. StringBuffer is fast and consumes less memory when we
abstract int getRateOfInterest(); in Java is a blueprint of a class. A Java interface contains static concatenate t strings.
} constants and abstract methods. The interface in Java is a 3. StringBuffer class doesn't override the equals() method of
class SBI extends Bank{ mechanism to achieve abstraction and multiple inheritance in Object class.
int getRateOfInterest(){return 7;} java. To implement Interface we use interface keyword. 4. StringBuffer class is faster while performing concatenation
} Syntax: operation.
class PNB extends Bank{ interface { 5. StringBuffer uses Heap memory
int getRateOfInterest(){return 8;} // declare constant fields
} // declare methods that abstract Throw:
class TestBank{ // by default. 1. Java throw keyword is used to explicitly throw an exception.
public static void main(String args[]){ } 2. Checked exception cannot be propagated using throw only.
Bank b; It is used to provide total abstraction. It means all the methods in 3. Throw is followed by an instance.
b=new SBI(); an interface are declared with an empty body and are public and 4. Throw is used within the method.
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" all fields are public, static, and final by default. 5. You cannot throw multiple exceptions.
%"); Advantages: Throws:
b=new PNB(); 1. Without bothering about the implementation part, we can 1. Java throws keyword is used to declare an exception.
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" achieve the security of the implementation. 2. Checked exception can be propagated with throws.
%"); 2. In Java, multiple inheritance is not allowed, however, you can 3. Throw is followed by a class.
}} // Output : use an interface to make use of it as you can implement more 4. Throw is used with the method signature.
Rate of Interest is: 7 % than one interface. 5. You can declare multiple exceptions e.g. public void
Rate of Interest is: 8 % method()throws IO Exception, SQL Exception.
CLI. and Server Program to show TCP Connection
Stream Tokenizer & Importance establishment & Data Transfer Datagram Socket
The Java. io. StreamTokenizer is a class that takes an input stream Client Side: Datagram socket is a type of network socket which provides
and parses it into "tokens", allowing the tokens to be read one at a package socket: connection-less point for sending and receiving packets. Every
time. The stream tokenizer can recognize identifiers, numbers, import java.io.*; packet sent from a datagram socket is individually routed and
quoted strings, and various comment styles. import java.net.*; delivered. It can also be used for sending and receiving broadcast
Following is the declaration for Java.io.StreamTokenizer class − public class Clientm( messages. Datagram Sockets is the java’s mechanism for providing
public class StreamTokenizer public static void main(String[]args)throws Exception network communication via UDP instead of TCP.
extends Object { Datagram packets are used to implement a connectionless packet
Sockets=new Socket("localhost",9999); delivery service. Each message is routed from one machine to
RMI, steps for creation of stub & skeleton, protocol & DataOutputStream another based solely on information contained within that
security problems dout=newDataOutputStream(s.getOutputStream()); packet. E.g.
Remote Method Invocation (RMI) is an API that allows an object to BufferedReader br=new BufferedReader(new //DSender.java
invoke a method on an object that exists in another address space, InputStreamReader(System.in)); import java.net.*;
which could be on the same machine or on a remote machine. while(true) public class DSender{
Through RMI, an object running in a JVM present on a computer ( public static void main(String[] args) throws Exception {
(Client-side) can invoke methods on an object present in another } DatagramSocket ds = new DatagramSocket();
JVM (Server-side). RMI creates a public remote server object that String so=br.readLine(); String str = "Welcome java";
enables client and server-side communications through simple dout.writeUTF(so); InetAddress ip = InetAddress.getByName("127.0.0.1");
method calls on the server object. if(so.equalsIgnoreCase("exit"))
The is given the 6 steps to write the RMI program:- break; DatagramPacket dp = new DatagramPacket(str.getBytes(),
Create the remote interface s.close();} str.length(), ip, 3000);
Provide the implementation of the remote interface Server Side: ds.send(dp);
Compile the implementation class and create the stub and skeleton package socket; ds.close();
objects using the rmic tool import java.io.*; }
Start the registry service by rmiregistry tool import java.net.*; }
Create and start the remote application public class Serverm{
Create and start the client application public static void main(String[] args)throws Exception Interface, Inheritance using Interface
The RMI protocol makes use of two other protocols for its { Inheritance is the mechanism in java by which one class is
on-the-wire format: Java Object Serialization and HTTP. The ServerSocket s=new ServerSocket(9999); allowed to inherit the features of another class. Interface is the
Object Serialization protocol is used to marshal call and return Socket ss=s.accept(); blueprint of the class. It specifies what a class must do and not
data. The HTTP protocol is used to "POST" a remote method System.out.println("connected"); how. Example demonstrating inheritance using interface.
invocation and obtain return data when circumstances warrant. DataInputStream dout=new interface AnimalEat {
DataInputStream(ss.getInputStream()); void eat();
BufferedReader br=new BufferedReader(new }
InputStreamReader(System.in)); interface AnimalTravel {
while(true) void travel();
( }
String yoo=dout.readUTF(): class Animal implements AnimalEat, AnimalTravel {
System.out.println("client:"+yoo); public void eat() {
} System.out.println("Animal is eating");
ss.close(); }
} public void travel() {
} System.out.println("Animal is travelling");
}
Container: }
Containers are an integral part of SWING GUI components. A public class Demo {
container provides a space where a component can be located. A public static void main(String args[]) {
Container in AWT is a component itself and it provides the Animal a = new Animal();
capability to add a component to itself. a.eat();
JPanel is the simplest container. It provides space in which any a.travel();
other component can be placed, including other panels. }
A JFrame is a top-level window with a title and a border. } // Output-\n Animal is eating.
Animal is travelling.
Servlets , life cycle & program Object serialization & Working What is Implement & its use
Servlets are the Java programs that run on the Java-enabled web Java provides a mechanism, called object serialization where an the implements keyword is used to implement an interface. An
server or application server. They are used to handle the request object can be represented as a sequence of bytes that includes interface is a special type of class which implements a complete
obtained from the webserver, process the request, produce the the object's data as well as information about the object's type abstraction and only contains abstract methods. Example -
response, then send a response back to the webserver. and the types of data stored in the object. // Defining an interface
Properties of Servlets are as follows: After a serialized object has been written into a file, it can be interface One {
Servlets work on the server-side. read from the file and deserialized that is, the type information public void methodOne();
Servlets are capable of handling complex requests obtained from and bytes that represent the object and its data can be used to }
the webserver. recreate the object in memory. // Defining the second interface
Life cycle of servlets: The ObjectOutputStream class is used to serialize an Object. interface Two {
The web container maintains the life cycle of a servlet instance. When the program is done executing, a file named employee.ser public void methodTwo();
Let's see the life cycle of the servlet: is created. The program does not generate any output, When }
1. Servlet class is loaded. serializing an object to a file, the standard convention in Java is // Implementing the two interfaces
2. Servlet instance is created. to give the file a .ser extension. class Three implements One, Two {
3. init method is invoked. public void methodOne()
4. service method is invoked. Package, Import & need of importing package {
5. destroy method is invoked. A java package is a group of similar types of classes, interfaces
Simple Servlet generating HTML to write hello students and sub-packages. // Implementation of the method
import java.io.*; Package in java can be categorized in two form, built-in package }
import javax.servlet.*; and user-defined package. public void methodTwo()
import javax.servlet.http.*; There are many built-in packages such as java, lang, awt, javax, {
public class WelcomeStudents extends HttpServlet{ swing, net, io, util, sql etc.
public void doGet (HttpServletRequest req, Import is used to make the classes and interface of another // Implementation of the method
HttpServletResponse res) throws ServletException, IOException { package accessible to the current package. }
res.setContentType("text/html"); Needs: }
PrintWriter out = res.getWriter(); 1. It categorizes the classes and interfaces so that they can be
out.println("<HTML><HEAD><TITLE>Welcome Students</TITLE> easily maintained. Object and Procedure Oriented Approach & features
out.println("<BODY><H1> Welcome Students </H1>"); 2. Java package provides access protection. Object Oriented :
out.println("This output was generated by the module 4 3. Java package removes naming collision. 1. In, object oriented programming, the program is divided into
servlet."); smaller parts called objects.
out.println("</BODY></HTML>"); Explain public static void main(String Args[]) 2. Object oriented programming follows bottom-up approach.
out.close(); a.public-This is the access modifier of the main method.It has to 3. It has access specifiers like private, public, protected, etc.
} be public so that java runtime can execute this method. 4. Adding new data and function is easy.
} b.static-In this main method has to be static so that JVM can 5. Object-oriented programming provides data hiding so it is more
load the class into memory and call the main method. secure.
Cookies & their role in session Handling c.void-Java main method doesn't return anything,that's why it's 6. Examples: C++, Java, Python, C#, etc.
A cookie is a small piece of information that is persisted between return type is void Procedure Oriented :
the multiple client requests. d.main-This is the name of java main method.It's fixed and 1. In procedural programming, the program is divided into small
A cookie has a name, a single value, and optional attributes such when we start a java program,it looks for the main method. parts called functions.
as a comment, path and domain qualifiers, a maximum age, and a e.String[]args-Java main method accepts a single argument of 2. Procedural programming follows a top-down approach.
version number. type String array.This is also called as java command line 3. There is no access specifier in procedural programming.
Web Pages have no memories. A user going from page to page will arguments. 4. Adding new data and functions is not easy.
be treated by the website as a completely new visitor. Session 5. Procedural programming does not have any proper way of
cookies enable the website you are visiting to keep track of your Byte code diff. b/w compiled code of java & C hiding data so it is less secure.
movement from page to page so you don’t get asked for the same Bytecode in Java is the reason java is platform-independent, as 6. C, FORTRAN, Pascal, Basic, etc.
information you’ve already given to the site. soon as a Java program is compiled bytecode is generated. To be
Cookies allow you to proceed through many pages of a site more precise a Java bytecode is the machine code in the form of JDBC , Drivers used in JDBC
quickly and easily without having to authenticate or reprocess a . class file. A bytecode in Java is the instruction set for Java JDBC stands for Java Database Connectivity. JDBC is a Java API to
each new area you visit. Virtual Machine and acts similar to an assembler. connect and execute the query with the database. It is a part of
C is a compiled language that is it converts the code into machine JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to
Transient & Volatile Modifiers language so that it could be understood by the machine or connect with the database.
The Volatile keyword is used to mark the JVM and thread to read system. Java is an Interpreted language that is in Java, the code JDBC helps you to
its value from primary memory and not utilize cached value is first transformed into bytecode and that bytecode is then write Java
present in the thread stack. It is used in concurrent programming executed by the JVM (Java Virtual Machine). applications that
in java. Volatile can be used with static and final keyword. manage these three
The Transient keyword is used with the instance variable to Final , finally & Finalize programming
eliminate it from the serialization process. During serialization, Final :- activities:
the value of the transient field or variable is not saved. It is a keyword. 1. Connect to a data
Transient cannot be used with static and final keyword. It is used to apply restrictions on classes, methods and variables. source, like a
It can’t be inherited. database.
Stream Sockets It can’t be overridden. 2. Send queries and
Stream socket allows processes to use the Transfer Control Final methods can’t be inherited by any class. update statements to
Protocol (TCP) for communication. A stream socket provides a It is needed to initialize the final variable when it is being the database
sequenced, constant or reliable, and two-way (bidirectional) flow declared. 3. Retrieve and
of data. After the establishment of connection, data can be read Its value, once declared, can’t be changed or re-initialized. process the results
and written to these sockets in a byte stream. The socket type of Finally :- received from the
stream socket is SOCK_STREAM. It is a block. database in
It is used to place important code in this block. answer to your query
Java Beans Features & How its diff. from instance of It gets executed irrespective of whether the exception is handled There are four types of JDBC drivers:
JDBC-ODBC Bridge Driver,
normal java class or not.
Finalize :- Native Driver,
A JavaBean is a Java class that should follow the following
It is a method. Network Protocol Driver, and
conventions:
It is used to perform clean up processing right before the object Thin Driver
It should have a no-arg constructor.
It should be Serializable. is collected by garbage collector.
doGet() and doPost() methods comparison
It should provide methods to set and get the values of the
properties, known as getter and setter methods. Casting, Explicit & Implicit
Features :- Type casting is a method or process that converts a data type into
The JavaBean properties and methods can be exposed to another another data type in both ways manually and automatically. The
application. automatic conversion is done by the compiler and manual
It provides an ease to reuse the software components. conversion performed by the programmer.
A class is nothing but a blueprint or a template for creating There are two types of casting :
different objects which defines its properties and behaviors. Java 1. Implicit Casting - Converting a lower data type into a higher
class objects exhibit the properties and behaviors defined by its one is called widening type casting. It is also known as implicit
class. conversion or casting. It is done automatically. It is safe because
there is no chance to lose data.
Thread Creation by Runnable interface, thread priority 2. Explicit Casting - Converting a higher data type into a lower
java.lang.Runnable is an interface that is to be implemented by a one is called narrowing type casting. It is also known as explicit
class whose instances are intended to be executed by a thread. conversion or casting. It is done manually by the programmer. If
> Steps to create a new thread using Runnable we do not perform casting then the compiler reports a
1. Create a Runnable implementer and implement the run() compile-time error.
method. AWT & Swing
2. Instantiate the Thread class and pass the implementer to the Extend & Use
AWT stands for Abstract Window Toolkit. It is a
Thread, Thread has a constructor which accepts Runnable The extends keyword is used to indicate that the class which is
platform-dependent API to develop GUI (Graphical User Interface)
instances. being defined is derived from the base class using inheritance. So
or window-based applications in Java. It was developed by
3. Invoke start() of Thread instance, start internally calls run() of basically, extends keyword is used to extend the functionality of
heavily Sun Microsystems In 1995. It is heavy-weight in use
the implementer. Invoking start() creates a new Thread that the parent class to the subclass. Example :-
because it is generated by the system’s host operating system. It
executes the code written in run(). Calling run() directly doesn’t class One {
contains a large number of classes and methods, which are used
create and start a new Thread, it will run in the same thread. To public void methodOne()
for creating and managing GUI.
start a new line of execution, call start() on the thread. {
Swing is a lightweight Java graphical user interface (GUI) that is
Thread Priority : is a concept where each thread is having a
used to create various applications. Swing has
priority which in layman’s language one can say every object is // Some Functionality
platform-independent components. It enables the user to create
having priority here which is represented by numbers ranging from }
buttons and scroll bars. Swing includes packages for creating
1 to 10. }
desktop applications in Java. Swing components are written in
Java language. It is a part of Java Foundation Classes(JFC).
Use of Super Keyword class Two extends One {
The super keyword in Java is a reference variable which is used to
public static void main(String args[])
Dynamic Binding
refer immediate parent class object.
When type of the object is determined at run-time, it is known as
Whenever you create the instance of subclass, an instance of {
dynamic binding. In Dynamic binding compiler doesn’t decide the
parent class is created implicitly which is referred by super Two t = new Two();
method to be called. Overriding is a perfect example of dynamic
reference variable.
binding. In overriding both parent and child classes have the same
Usage of Java super Keyword : // Calls the method one
method.
super can be used to refer immediate parent class instance // of the above class
variable. t.methodOne();
super can be used to invoke immediate parent class method. }
super() can be used to invoke immediate parent class constructor. }

You might also like