Q1. a) What is Object Oriented Programming (OOP)? Explain its advantages. Also describe concept of data hiding in OOP.
Answer : - Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects. It simplifies the software development and maintenance by providing some concepts :
Object - Any entity that has state and behavior is known as an object. An Object can be defined as an instance of a class.
Class - Collection of objects is called class. It is a logical entity. A class can also be defined as a blueprint from which you can create an individual object. Class doesn't consume any space.
Inheritance - When one object acquires all the properties and behaviors of a parent object, it is known as inheritance.
Polymorphism - If one task is performed by different ways, it is known as polymorphism. In Java, we use method overloading and method overriding to achieve polymorphism.
Abstraction - Hiding internal details and showing functionality is known as abstraction. In Java, we use abstract class and interface to achieve abstraction.
Encapsulation - Binding (or wrapping) code and data together into a single unit are known as encapsulation. A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.
Advantage of Object Oriented Programming System (OOPs) -
OOPs makes development and maintenance easier whereas in a procedure-oriented programming language it is not easy to manage if code grows as project size increases.
OOPs provides data hiding whereas in a procedure-oriented programming language a global data can be accessed from anywhere.
OOPs provides the ability to simulate real-world event much more effectively. We can provide the solution of real word problem if we are using the Object-Oriented Programming language.
Data Hiding - Data hiding is a software development technique specifically used in object-oriented programming (OOP) to hide internal object details (data members). Data hiding ensures exclusive data access to class members and protects object integrity by preventing unintended or intended changes.
Data hiding also reduces system complexity for increased robustness by limiting interdependencies between software components.
Q1. b) Explain different data types available in Java.
Answer : - In Java data types are divided into two groups :
- Primitive data types - includes byte, short, int, long, float, double, boolean and char
- Non-primitive data types - such as String, Arrays and Classes
Primitive Data Types
Data Type | Size | Description and Example |
---|---|---|
byte | 1 bytes | Stores whole numbers from -128 to 127 Example : byte a = 10, byte b = -20; |
short | 2 bytes | Stores whole numbers from -32,768 to 32,767 Example : short s = 10000, short r = -5000; |
int | 4 bytes | Stores whole numbers from -2,147,483,648 to 2,147,483,647 Example : int a = 100000, int b = -200000; |
long | 8 bytes | Stores whole numbers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 Note that you should end the value with an "L". Example : long a = 100000L, long b = -200000L; |
float | 4 bytes | Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits Note that you should end the value with an "f": Example : float x = 234.5f; |
double | 8 bytes | Stores fractional numbers. Sufficient for storing 15 decimal digits Example : double y = 12.3; |
boolean | 1 bit | Stores true or false values Example : char letter = 'A'; |
char | 2 bytes | Stores a single character/letter or ASCII values Example : Boolean b = false; |
Non-Primitive Data Types
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are :
- Primitive types are predefined (already defined) in Java. Non-primitive types are created by the programmer and is not defined by Java (except for String).
- Non-primitive types can be used to call methods to perform certain operations, while primitive types cannot.
- A primitive type has always a value, while non-primitive types can be null.
String - The String data type is used to store a sequence of characters (text). String values must be surrounded by double quotes :
Example - String message = "Hello World";
Q1. c) Describe features of Java programming language.
Answer : - The primary objective of Java programming language creation was to make it portable, simple and secure programming language. Apart from this, there are also some excellent features which play an important role in the popularity of this language.
A list of most important features of Java language is given below.
Simple - Java is very easy to learn, and its syntax is simple, clean and easy to understand.
Object-Oriented - Java is an object-oriented programming language. Everything in Java is an object. Object-oriented means we organize our software as a combination of different types of objects that incorporates both data and behavior.
Basic concepts of OOPs are :
- Object
- Class
- Inheritance
- Polymorphism
- Abstraction
- Encapsulation
Platform Independent - Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere(WORA).
Secured - Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because :
No explicit pointer
Java Programs run inside a virtual machine sandbox
Classloader : Classloader in Java is a part of the Java Runtime Environment(JRE) which is used to load Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for the classes of the local file system from those that are imported from network sources.
Bytecode Verifier : It checks the code fragments for illegal code that can violate access right to objects.
Security Manager : It determines what resources a class can access such as reading and writing to the local disk.
Robust - Robust simply means strong. Java is robust because :
It uses strong memory management.
There is a lack of pointers that avoids security problems.
There is automatic garbage collection in java which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make Java robust.
Architecture Neutral - Java is architecture neutral because there are no implementation dependent features, for example, the size of primitive types is fixed.
Portable - Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
Distributed - Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB are used for creating distributed applications. This feature of Java makes us able to access files by calling the methods from any machine on the internet.
Multithreaded - A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Dynamic - Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on demand.
Q2. a) What is a class? Define a class in Java and with the help of that class describe meaning of data members and member functions. Also describe use of different types of access spcifiers available in Java.
Answer : -
- A Class is a user defined data-type which have data members and member functions.
- Data members are the data variables and member functions are the functions used to manipulate these variables and together these data members and member functions defines the properties and behavior of the objects in a Class.
- A class is like a blueprint for an object.
class Student { //Data Members private int id; private String name; //Member Functions public static void main(String args[]) { id=10; name="Debabrata"; System.out.println(id + "\t" + name); } } |
There are 4 types of access spcifiers in Java :
private - The private access modifier is accessible only within class.
default - If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.
protected - The protected access modifier is accessible within package and outside the package but through inheritance only.
public - The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Q2. b) Describe advantages of abstract method. Write a java program to create a Shape class with an abstract method Find_Area( ). Inherit Circle and Rectangle classes from Shape class. Implement Find_Area( ) method in derived classes. Make necessary assumptions.
Answer : - A method which is declared as abstract and does not have implementation is known as an abstract method.
Example : abstract void printStatus( ); // No Method Body
If a class includes abstract methods, then the class itself must be declared abstract.
Abstraction is a process of hiding the implementation details and showing only functionality to the user.
Another way, it shows only essential things to the user and hides the internal details, for example, sending SMS where you type the text and send the message. You don't know the internal processing about the message delivery.
public abstract class Shape import java.io.*; import java.io.*; import java.io.*; Output : |
Q3. a) Explain use(s) of following keywords of Java with the help of program/example.
- final
- finally
- super
Answer : -
final Keyword
- Final is a keyword or non-access modifier in java.
- It can be apply with class, variables, and methods.
- If you make any class as final class then you cannot inherit(extends) this class. If you make any variable as final variable then you cannot change the value of this variable after initialization. If you make any method as final method then you cannot override this method.
- If we declare final variable along with static keyword will become a constants.
class Speed { //final variable final int speedlimit=90; void run() { speedlimit=400; } public static void main(String args[]) { Speed obj=new Speed(); obj.run(); } } |
Output : Compile Time Error
finally Keyword -
- The finally keyword is used to create a block of code that follows a try block.
- Java finally block of code is used to execute important code such as closing connection, stream etc.
- Java finally block is always executed whether exception is handled or not.
Example :
class TestFinallyBlock Output : |
super Keyword - We can use super keyword to access the data member and methods of parent class. It is used if parent class and child class have same methods or variables.
Example ://Parent Class class Base { int fact; void Factorial(int n) { fact=1; for(int i=1;i<=n;i++) fact=fact*i; } } //Child Class |
Q3. b) What is interface? How interface is different from abstract class? Write a program in Java to explain how interfaces are implemented.
Answer : - Like a class, an interface can have methods and variables, but the methods declared in interface are by default abstract (only method signature, no body). Interfaces specify what a class must do and not how.
A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body). Method that are declared without any body within an abstract class are called abstract method. The method body will be defined by its subclass. Abstract method can never be final and static. Any class that extends an abstract class must implement all the abstract methods declared by the super class.
Abstract Class | Interface |
---|---|
Abstract class can have abstract and non-abstract methods. | Interface can have only abstract methods. |
Abstract class doesn't support multiple inheritance. | Interface supports multiple inheritance. |
Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables. |
Abstract class can provide the implementation of interface. | Interface can't provide the implementation of abstract class. |
An abstract class can extend another Java class and implement multiple Java interfaces. | An interface can extend another Java interface only. |
A Java abstract class can have class members like private, protected, etc. | Members of a Java interface are public by default. |
Java Interface Example
interface Bank class SBI implements Bank class RBL implements Bank class InterestCheck |
Q4. a) What is polymorphism? Explain use of polymorphism in java programming.
Answer : - Polymorphism in Java is a concept by which we can perform a single action in different ways. There are two types of polymorphism in Java : compile-time polymorphism and runtime polymorphism.
Run time Polymorphism also known as method overriding. Method overriding means having two or more methods with the same name, same signature but with different implementation.
Compile time Polymorphism also known as method overloading. Method overloading means having two or more methods with the same name but with different signatures.
Example of Polymorphism
class Bank { double getRateOfInterest() { return 0.0; } } class SBI extends Bank { double getRateOfInterest() { return 6.2; } } class ICICI extends Bank { double getRateOfInterest() { return 6.8; } } class AXIS extends Bank { double getRateOfInterest() { return 6.5; } } class TestPolymorphism { public static void main(String args[]) { Bank b; b=new SBI(); System.out.println("SBI Interest Rate = " + b.getRateOfInterest()); b=new ICICI(); System.out.println("ICICI Interest Rate = " + b.getRateOfInterest()); b=new AXIS(); System.out.println("AXIS Interest Rate = " + b.getRateOfInterest()); } } |
Q4. b) What is exception? What are different types of exceptions? Explain need of exceptions handling with the help of a program.
Answer : - Exceptions are events that occur during the execution of programs that distrup the normal flow of instructions (example - divide by zero, array access out of bound, etc.).
In Java, an exception is an object that wraps an error event that occurred within a method and contains :
- Information about the error including its type
- The state of the program when the error occurred
- Optionally, other custom information
Different Types of Java Exceptions
ArithmeticException
If we divide any number by zero, there occurs an ArithmeticException.
int a = 50/0; //ArithmeticException NullPointerException
If we have a null value in any variable, performing any operation on the variable throws a NullPointerException.
String s = null;
System.out.println(s.length( )); //NullPointerExceptionNumberFormatException
The wrong formatting of any value may occur NumberFormatException. Suppose I have a string variable that has characters, converting this variable into digit will occur NumberFormatException.
String s = "abc";
int i=Integer.parseInt(s); //NumberFormatExceptionArrayIndexOutOfBoundsException
If you are inserting any value in the wrong index, it would result in ArrayIndexOutOfBoundsException as shown below :
int a[ ] = new int[5];
a[10]=50; //ArrayIndexOutOfBoundsException
There are 5 keywords which are used in handling exceptions in Java.
Keyword | Description |
---|---|
try | The "try" keyword is used to specify a block where we should place exception code. The try block must be followed by either catch or finally. It means, we can't use try block alone. |
catch | The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use catch block alone. It can be followed by finally block later. |
finally | The "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not. |
throw | The "throw" keyword is used to throw an exception. |
throws | The "throws" keyword is used to declare exceptions. It doesn't throw an exception. It specifies that there may occur an exception in the method. It is always used with method signature. |
Java Exception Handling Example
public class JavaExceptionExample Output : |
Q5. a) What is multithreading? Explain advantages of multithreading. Describe use of setPriority and getPriority methods for Java multithreading. Also describe how threads are synchronized in Java with the help of a program.
Answer : - Multithreading in java is a process of executing multiple threads simultaneously. Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking.
We use multithreading than multiprocessing because threads share a common memory area. They do not allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation etc.
Advantages of Java Multithreading
- It does not block the user because threads are independent and you can perform multiple operations at same time.
- You can perform many operations together so it saves time.
- Threads are independent so it does not affect other threads if exception occur in a single thread.
setPriority( ) - The setPriority( ) method of thread class is used to change the thread's priority. Every thread has a priority which is represented by the integer number between 1 to 10.
Syntax : public final void setPriority(int a)
getPriority( ) - The getPriority( ) method of thread class is used to check the priority of the thread. When we create a thread, it has some priority assigned to it. Priority of thread can either be assigned by the JVM or by the programmer explicitly while creating the thread.
Syntax : public final int getPriority( )
Thread class provides 3 constant properties :
- public static int MIN_PRIORITY
- public static int NORM_PRIORITY
- public static int MAX_PRIORITY
Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of MAX_PRIORITY is 10.
Example of priority of a Thread
class PriorityExample extends Thread { public void run() { System.out.println("running thread priority : "+Thread.currentThread().getPriority()); } public static void main(String args[]) { PriorityExample p1=new PriorityExample(); p1.setPriority(Thread.MAX_PRIORITY); p1.start(); } } |
Output :
running thread name : Thread-0
running thread priority : 10
Java - Thread Synchronization
When we start two or more threads within a program, there may be a situation when multiple threads try to access the same resource and finally they can produce unforeseen result due to concurrency issues. For example, if multiple threads try to write within a same file then they may corrupt the data because one of the threads can override data or while one thread is opening the same file at the same time another thread might be closing the same file.
So there is a need to synchronize the action of multiple threads and make sure that only one thread can access the resource at a given point in time. This is implemented using a concept called monitors. Each object in Java is associated with a monitor, which a thread can lock or unlock. Only one thread at a time may hold a lock on a monitor.
Java programming language provides a very handy way of creating threads and synchronizing their task by using synchronized blocks. You keep shared resources within this block.
Without Synchronization
public class Table class Thread1 extends Thread class Thread2 extends Thread class TestSynchronization Output : |
With Synchronization
public class Table { //Synchronized Method synchronized void printTable(int n) { for(int i=1;i<=5;i++) { System.out.println(n*i); try { Thread.sleep(500); } catch(Exception e) { System.out.println(e); } } } } class Thread1 extends Thread class Thread2 extends Thread class TestSynchronization Output : |
Q5. b) Write program to create an Applet which draw a circle inside a triangle. Keep color of circle blue and triangle yellow.
Answer : -
import java.applet.*; import java.awt.*; import java.awt.event.*; public class DrawingExample extends Applet { public void paint(Graphics g) { // x coordinates of vertices int x[] = { 200, 50, 350 }; // y coordinates of vertices int y[] = { 50, 300, 300 }; // Number of vertices int vertices = 3; // Create a Polygon with given x, y coordinates Polygon p = new Polygon(x, y, vertices); // Draw a Triangle g.setColor(Color.yellow); g.fillPolygon(p); // Draw a Circle g.setColor(Color.blue); g.fillOval(120, 135, 160, 160); } } |
Q6. a) What is layout manager? Describe use of flow layout and grid layout with the help of program code.
Answer : - Coming Soon
Q6. b) What is event driven program? Describe different components of event in Java
Answer : - Coming Soon
Q7. a) Explain use of stream classes in Java. Write a java program to read the contents of a given file and display it.
Answer : -
Java Stream Class
Byte Stream
InputStream
- FileInputStream
- ByteArrayInputStream
- ObjectInputStream
- PipedInputStream
FilterInputStream
- BufferedInputStream
- DataInputStream
OutputStream
- FileOutputStream
- ByteArrayOutputStream
- ObjectOutputStream
- PipedOutputStream
FilterOutputStream
- BufferedOutputStream
- DataOutputStream
Character Stream
Reader
- BufferedReader
- CharArrayReader
- StringReader
- FilterReader
InputStreamReader
- FileReader
Writer
- BufferedWriter
- CharArrayWriter
- StringWriter
- FilterWriter
InputStreamWriter
- FileWriter
Read the Contents of a given File
import java.io.*; class CopyFile { public static void main(String args[])throws IOException { FileInputStream Fread =new FileInputStream("File1.txt"); int c; while((c=Fread.read()) != -1) System.out.print((char)c); Fread.close(); } } |
Q7. b) Explain use of Socket and DatagramPacket classes.
Answer : - Coming Soon
Q8. a) What is Servlet ? Explain Servlet life cycle. Also explain use of GET and POST methods of Servlet.
Answer : - Servlet can be described in many ways, depending on the context.
- Servlet is a technology which is used to create a web application.
- Servlet is an API that provides many interfaces and classes including documentation.
- Servlet is an interface that must be implemented for creating any Servlet.
- Servlet is a class that extends the capabilities of the servers and responds to the incoming requests. It can respond to any requests.
- Servlet is a web component that is deployed on the server to create a dynamic web page.
Servlet Life Cycle
Loading Servlet Class - When the Web Server (e.g. Apache Tomcat) starts up, the Web Container deploy and loads all the servlet classes.
Creating instance of Servlet - Once all the Servlet classes loaded, the Web Container creates instances of each servlet class. The servlet instance is created only once in the Servlet Life Cycle.
Invoke init( ) method - Once all the servlet classes are instantiated, the init() method is invoked for each instantiated servlet. This method initializes the servlet. There are certain init parameters that you can specify in the deployment descriptor (web.xml) file. For example, if a servlet has value >=0 then its init() method is immediately invoked during web container startup.
Syntax of the init( ) method is given below :
public void init(ServletConfig config) throws ServletExceptionThe init( ) method is called only once during the life cycle of servlet.
Invoke service( ) method - Each time the web server receives a request for servlet, it spawns a new thread that calls service() method. If the servlet is GenericServlet then the request is served by the service() method itself, if the servlet is HttpServlet then service() method receives the request and dispatches it to the correct handler method based on the type of request.
The service() method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client.
Syntax of the service( ) method is given below :
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOExceptionInvoke destroy( ) method - When Web Container shuts down(this usually happens when we stop the web server), it unloads all the Servlets and calls destroy() method for each initialized Servlets.
Syntax of the destroy( ) method is given below :
public void destroy( )
GET Method
The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? (question mark) symbol as follows −
http://www.questionsolves.com/Test?firstname=AMIT&lastname=DAS |
The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation : only 1024 characters can be used in a request string.
This information is passed using QUERY_STRING header and will be accessible through QUERY_STRING environment variable and Servlet handles this type of requests using doGet( ) method.
POST Method
A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET method, but instead of sending it as a text string after a ? (question mark) in the URL it sends it as a separate message. This message comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost( ) method.
Servlets handles form data parsing automatically using the following methods depending on the situation −
getParameter( ) − You call request.getParameter( ) method to get the value of a form parameter.
getParameterValues( ) − Call this method if the parameter appears more than once and returns multiple values, for example checkbox.
getParameterNames( ) − Call this method if you want a complete list of all parameters in the current request.
Q8. b) What is JDBC? Explain how connection is established in JDBC.
Answer : - 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. There are four types of JDBC drivers :
JDBC-ODBC Bridge Driver
The JDBC Type 1 driver converts JDBC method calls into ODBC function calls. The bridge is usually used when there is no pure-Java driver available for a particular database. The driver is implemented in the sun.jdbc.odbc.JdbcOdbcDriver class and comes with the Java 2 SDK, Standard Edition.
Advantages
- Almost any database for which ODBC driver is installed, can be accessed.
Disadvantages
- Performance degraded because JDBC method call is converted into the ODBC function calls.
- The ODBC driver needs to be installed on the client machine.
Native-API Driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantages
- Better performance than Type 1 since no jdbc to odbc translation is needed.
Disadvantages
- The vendor client library needs to be installed on the client machine.
- Cannot be used in internet due the client side software needed. (That means the Native driver needs to be installed on the each client machine)
- Not all databases give the client side library.
Net-Protocol Driver
The Net-Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantages
- No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.
- Can be used in internet since there is no client side software needed.
Disadvantages
- Requires database-specific coding to be done in the middle tier.
- Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.
Native-Protocol Driver
The Native-protocol driver converts JDBC calls directly into the vendor-specific database protocol. It is fully written in Java language and installed inside the Java Virtual Machine of the client.
Advantages
- Better performance than all other drivers.
- No software is required at client side or server side.
Disadvantages
- At client side, a separate driver is needed for each database.
Q8. c) What is RMI? Explain RMI architecture.
Answer : - The RMI (Remote Method Invocation) is an API that provides a mechanism to create distributed application in java. The RMI allows an object to invoke methods on an object running in another JVM.
The RMI provides remote communication between the applications using two objects stub and skeleton. RMI uses stub and skeleton object for communication with the remote object. A remote object is an object whose method can be invoked from another JVM.
Stub - The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed through it. It resides at the client side and represents the remote object.
Skeleton - The skeleton is an object, acts as a gateway for the server side object. All the incoming requests are routed through it.
Understanding requirements for the Distributed Applications
If any application performs these tasks, it can be distributed application.
- The application need to locate the remote method
- It need to provide the communication with the remote objects, and
- The application need to load the class definitions for the objects.