MCS-024 ASSIGNMENT SOLUTION (2019-20)

If you have any queries please leave a message here
Your Message
×


Q1. a) Explain basic concepts of Object Oriented Programming? Explain how data hiding is achieved.

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 :

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 use of different types of operators available in java with the help of examples.

Answer : -

Arithmetic Operators - Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication etc.

OperatorDescription
+
Addition (also used for string concatenation)
-
Subtraction
*
Multiplication
/
Division
%
Remainder

public class Arithmetic_Operators
{
public static void main(String args[])
{
int a=25, b=10;
System.out.println("Result of (a + b) is = " + (a + b));
System.out.println("Result of (a - b) is = " + (a - b));
System.out.println("Result of (a * b) is = " + (a * b));
System.out.println("Result of (a / b) is = " + (a / b));
System.out.println("Result of (a % b) is = " + (a % b));
}
}

Output :

Result of (a + b) is = 35
Result of (a - b) is = 15
Result of (a * b) is = 250
Result of (a / b) is = 2
Result of (a % b) is = 5


Relational Operators - Relational operators in Java programming are mostly used either in If Conditions or Loops. Java Relational operators are commonly used to check the relationship between two variables.

The Relational Operators in Java Programming show in the table given below :

OperatorDescription
>
greater than
<
less than
>=
greater than or equal to
<=
less than or equal to
==
equal to
!=
not equal to

public class Relational_Operators
{
public static void main(String args[])
{
int a=20, b=10;
System.out.println("Output of (a > b) is = " + (a > b));
System.out.println("Output of (a < b) is = " + (a < b));
System.out.println("Output of (a >= b) is = " + (a >= b));
System.out.println("Output of (a <= b) is = " + (a <= b));
System.out.println("Output of (a == b) is = " + (a == b));
System.out.println("Output of (a != b) is = " + (a != b));
}
}

Output :

Output of (a > b) is = true
Output of (a < b) is = false
Output of (a >= b) is = true
Output of (a <= b) is = false
Output of (a == b) is = false
Output of (a != b) is = true


Unary Operators - Unary operator performs operation on only one operand.

OperatorDescription
expr++
Post Increment (value is first used for computing the result and then incremented)
expr--
Post Decrement (value is first used for computing the result and then decremented)
++expr
Pre Increment (value is incremented first and then result is computed)
--expr
Pre Decrement (value is decremented first and then result is computed.)
!
Logical not operator
+expr
Unary Plus (not necessary to use since numbers are positive without using it)
-expr
Unary Minus (inverts the sign of an expression)
~expr
Unary Minus (inverts the sign of an expression)

public class Unary_Operators
{
public static void main(String args[])
{
int i=20, j=5, x=15, y=-10;
boolean a=true, b=false;
System.out.println("Output of (i++) is = " + (i++));
System.out.println("Output of (i--) is = " + (i--));
System.out.println("Output of (++i) is = " + (++i));
System.out.println("Output of (--i) is = " + (--i));
System.out.println("Output of (i++ + ++i) is = " + (i++ + ++i));
System.out.println("Output of (j++ + j++) is = " + (j++ + j++));
// Minus of total positive value which starts from 0
System.out.println("Output of (~x) is = " + ~x); // Output : -16
// Positive of total minus, positive starts from 0
System.out.println("Output of (~y) is = " + ~y); // Output : 9
System.out.println("Output of (!a) is = " + !a);
System.out.println("Output of (!b) is = " + !b);
}
}

Output :

Output of (i++) is = 20
Output of (i--) is = 21
Output of (++i) is = 21
Output of (--i) is = 20
Output of (i++ + ++i) is = 42
Output of (j++ + j++) is = 11
Output of (~x) is = -16
Output of (~y) is = 9
Output of (!a) is = false
Output of (!b) is = true


Java AND Operator

OperatorDescription
&&
Logical AND
&
Bitwise AND

The logical AND operator doesn't check second condition if first condition is false. It checks second condition only if first one is true.

The bitwise AND operator always checks both conditions whether first condition is true or false.

public class AND_Operators
{
public static void main(String args[])
{
int a=20, b=10, c=30;
// Second condition is not checked
System.out.println((a < b) && (a++ < c));
System.out.println("Value of a = " + a);
// Both conditions are checked
System.out.println((a < b) & (a++ < c));
System.out.println("Value of a = " + a);
}
}

Output :

false
Value of a = 20
false
Value of a = 21


Java OR Operator

OperatorDescription
||
Logical OR
|
Bitwise OR

The logical OR operator doesn't check second condition if first condition is true. It checks second condition only if first one is false.

The bitwise OR operator always checks both conditions whether first condition is true or false.

public class OR_Operators
{
public static void main(String args[])
{
int a=20, b=10, c=30;
// Second condition is not checked
System.out.println((a > b) || (a++ < c));
System.out.println("Value of a = " + a);
// Both conditions are checked
System.out.println((a > b) | (a++ < c));
System.out.println("Value of a = " + a);
}
}

Output :

true
Value of a = 20
true
Value of a = 21


Ternary Operator - Ternary operator is a shorthand version of if-else statement. it is the only conditional operator which takes three operands.

public class Ternary_Operators
{
public static void main(String args[])
{
int a=20, b=10;
int max = (a < b) ? a : b;
System.out.println("Maximum Number = " + max);
}
}

Output :

Maximum Number = 20


Assignment Operators - An assignment operator assigns a value to the left operand based on the value of its right operand with the help of equals (=) sign. Thus, x = y assigns the value of y into x.

In many cases assignment operator can be combined with other operators to build a shorter version of statement called Compound Statement.

OperatorDescription
+=
Adding left operand with right operand and then assigning it to variable on the left.
-=
subtracting left operand with right operand and then assigning it to variable on the left.
*=
multiplying left operand with right operand and then assigning it to variable on the left.
/=
dividing left operand with right operand and then assigning it to variable on the left.
%=

public class Ternary_Operators
{
public static void main(String args[])
{
int x=20, y=10;
x += y
System.out.println("Output of (x += y) is = " + x);
x /= y
System.out.println("Output of (x /= y) is = " + x);
}
}

Output :

Output of (x += y) is = 30
Output of (x /= y) is = 3




Q2. a) Explain how class is defined in java with the help of an example. Also explain what are the things which are kept inside a class.

Answer : -

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




Q2. b) Write a java program to create an Account class and define constructors in it. Inherit Saving_Bank_Account class from Account class. Override constructors of Account class in Saving_Bank_Account class. Define appropriate methods to operate the accounts. Make necessary assumptions.

Answer : -

public class Account
{
protected long AccountNo;
protected String CustomerName;
protected int Balance;
public Account()
{
AccountNo = 0;
CustomerName = "";
Balance = 0;
}
}

public class Saving_Bank_Account extends Account
{
public Account(long accno, String name, int amount)
{
AccountNo = accno;
CustomerName = name;
Balance = amount;
}
public void print()
{
System.out.println(AccountNo + "\t" + CustomerName + "\t" + Balance);
}
}

If we define Parent class constructor inside Child class it will give compile time error for return type and consider it a method.




Q3. a) Explain use of static methods in java.

Answer : -

In core Java program, execution starts from main method when you type java main-class-name, JVM search for public static void main(String args[ ]) method in that class and if it doesn't find that method it throws error NoSuchMethodError:main and terminates.




Q3. b) Write a java program to add two matrices of 4X4 in java.

Answer : -

import java.io.*;
public class MatrixAddition
{
public static void main(String args[])throws IOException
{
int A[4][4], B[4][4], C[4][4], i, j,;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
// Input Matrix A
System.out.println("Input First Matrix");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
System.out.println("Enter the value of A["+i+"]["+j+"] ");
A[i][j]=Integer.parseInt(br.readLine());
}
}
// Input Matrix B
System.out.println("Input Second Matrix");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
System.out.println("Enter the value of B["+i+"]["+j+"] ");
B[i][j]=Integer.parseInt(br.readLine());
}
}
// Addition of Matrix A and Matrix B
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
C[i][j] = A[i][j] + B[i][j];
}
}
// Display the Addition Result
System.out.println("Result of Addition");
for(i=0;i<4;i++)
{
for(j=0;j<4;j++)
{
System.out.print("\t" + C[i][j]);
}
System.out.println();
}
}
}




Q3. c) Explain different types of inheritance that are supported by java with the help of examples.

Answer : -

Single Inheritance - A derived class with only one base class is called single inheritance.

//Base Class
public class A
{
public void Method_of_A()
{
System.out.println("Base Class");
}
}

//Derived Class
public class B extends A
{
public void Method_of_B()
{
System.out.println("Derived Class");
}
}

public class CallMethod
{
public static void main(String args[])
{
B ob1=new B();
ob1.Method_of_A();
ob1.Method_of_B();
}
}

Output
Base Class
Derived Class

Multilevel Inheritance - A derived class with one base class and that base class is a derived class of another is called multilevel inheritance.

public class A
{
public void Method_of_A()
{
System.out.println("Method of Class A");
}
}

public class B extends A
{
public void Method_of_B()
{
System.out.println("Method of Class B");
}
}

public class C extends B
{
public void Method_of_C()
{
System.out.println("Method of Class C");
}
}

public class CallMethod
{
public static void main(String args[])
{
C ob1=new C();
ob1.Method_of_A();
ob1.Method_of_B();
ob1.Method_of_C();
}
}

Output
Method of Class A
Method of Class B
Method of Class C

Heirarchical Inheritance - Multiple derived classes with same base class is called hierarchical inheritance.

public class A
{
public void Method_of_A()
{
System.out.println("Method of Class A");
}
}

public class B extends A
{
public void Method_of_B()
{
System.out.println("Method of Class B");
}
}

public class C extends A
{
public void Method_of_C()
{
System.out.println("Method of Class C");
}
}

public class D extends A
{
public void Method_of_D()
{
System.out.println("Method of Class D");
}
}

public class CallMethod
{
public static void main(String args[])
{
B ob1=new B();
ob1.Method_of_B();
ob1.Method_of_A();
System.out.println();
C ob2=new C();
ob2.Method_of_C();
ob2.Method_of_A();
System.out.println();
D ob3=new D();
ob3.Method_of_D();
ob3.Method_of_A();
}
}

Output
Method of Class B
Method of Class A

Method of Class C
Method of Class A

Method of Class D
Method of Class A




Q4. a) Explain uses of final and super keywords in java with the help of examples.

Answer : -

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.

//Parent Class
class Base
{
int fact;
void Factorial(int n)
{
fact=1;
for(int i=1;i<=n;i++)
fact=fact*i;
}
}

//Child Class
class Derived extends Base
{
void Factorial(int n)
{
//Call the Overriding Method of Parent Class
super.Factorial(n);
System.out.println("Factorial = "+super.fact);
}
}

final Keyword

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




Q4. b) Explain the need of package in Java. Explain accessibility rules for packages.

Answer : - Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.

Advantages of using a Package in Java


There are 4 types of java access modifiers :

privatedefaultprotectedpublic
Within same classYesYesYesYes
Within other class of same packageNoYesYesYes
Within derived class of other packageNoNoYesYes
Within external class of other packageNoNoNoYes




Q4. c) Explain advantages of polymorphism with the help of example.

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




Q5. a) What is interface? How it is different from abstract class? Explain.

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 ClassInterface
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
{
double RateOfInterest();
double ATMcharges();
}

class SBI implements Bank
{
public double RateOfInterest() { return 6.2; }
public double ATMcharges() { return 100.0; }
}

class RBL implements Bank
{
public double RateOfInterest() { return 6.8; }
}

class InterestCheck
{
public static void main(String args[])
{
Bank ob1=new SBI();
System.out.println("SBI Interest Rate = " + ob1.RateOfInterest());
System.out.println("SBI ATM Charges = " + ob1.ATMcharges());
Bank ob2=new RBL();
System.out.println("RBL Interest Rate = " + ob2.RateOfInterest());
}
}

Abstract Class Example

abstract class Bank
{
abstract double RateOfInterest();
public void ATMcharges()
{
System.out.println("ATM Charges = Rs. 100/-");
}
}

class SBI extends Bank
{
double RateOfInterest() { return 6.2; }
}

class PNB extends Bank
{
double RateOfInterest() { return 6.5; }
}

class InterestCheck
{
public static void main(String args[])
{
Bank ob1=new SBI();
System.out.println("SBI Interest Rate = " + ob1.RateOfInterest());
ob1.ATMcharges();
Bank ob2=new PNB();
System.out.println("PNB Interest Rate = " + ob2.RateOfInterest());
ob2.ATMcharges();
}
}




Q5. b) What is an exception? Explain various causes of exceptions. With the help of a program explain how exceptions are handled in java.

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 :


Common Scenarios of Java Exceptions


There are 5 keywords which are used in handling exceptions in Java.

KeywordDescription
tryThe "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.
catchThe "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.
finallyThe "finally" block is used to execute the important code of the program. It is executed whether an exception is handled or not.
throwThe "throw" keyword is used to throw an exception.
throwsThe "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
{
public static void main(String args[])
{
try
{
// Code that may raise exception
int data=100/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("Rest of the code...");
}
}

Output :
java.lang.ArithmeticException:/ by zero
Rest of the code...


Create Custom Exception in Java

class InvalidAgeException extends Exception
{
InvalidAgeException(String s)
{
super(s);
}
}

class TestCustomException
{
static void validate(int age)throws InvalidAgeException
{
if(age < 0)
throw new InvalidAgeException("Negative value not allow");
}
public static void main(String args[])
{
try
{
validate(-12);
}
catch(Exception e)
{
System.out.println(e);
}
System.out.println("Rest of the code...");
}
}

Output :
InvalidAgeException:Negative value not allow
Rest of the code . . .




Q5. c) What is multithreading? Explain how threads are created in java. Describe java thread model.

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


There are two ways to create a thread :

  1. By extending Thread class
  2. By implementing Runnable interface

Thread class provide constructors and methods to create and perform operations on a thread.

Commonly used Constructors of Thread class :


Java Thread Example by extending Thread class

class MultiThread extends Thread
{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
MultiThread ob1=new MultiThread();
ob1.start();
}
}

Java Thread Example by implementing Runnable interface

class MultiThread implements Runnable
{
public void run()
{
System.out.println("Thread is running...");
}
public static void main(String args[])
{
MultiThread ob1=new MultiThread();
Thread th =new Thread(ob1);
th.start();
}
}

NOTE - If you are implementing Runnable interface in your class, then you need to explicitly create a Thread class object and need to pass the Runnable interface implemented class object as a parameter in its constructor.


Java Thread Model

The life cycle of the thread in java is controlled by JVM. The java thread states are as follows :




Q6. a) Explain various applications where multithreading may be used. Also explain how interthread communication takes place in java.

Answer : - A thread is a basic unit of CPU utilization, which consists of a program counter, a stack, and a set of registers. It is used whenever a process has multiple tasks to perform independently of the others. The benefits of multithreading are faster responsiveness and effective usage of resources. Thread libraries provide programmers with an API for creating and managing threads like java threads.

For example in a word processor, one thread may check for spelling mistakes while another thread stores or process the inputs simultaneously.

Another good example is web server, where multiple threads works on multiple requests sent by clients.

Many GUI frameworks are multi-threaded.


inter-thread Communication

Inter-thread communication or Co-operation is all about allowing synchronized threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused running in its critical section and another thread is allowed to enter (or lock) in the same critical section to be executed. It is implemented by following methods of Object class :


Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows :

  1. Threads enter to acquire lock.
  2. Lock is acquired by on thread.
  3. Now thread goes to waiting state if you call wait( ) method on the object. Otherwise it releases the lock and exits.
  4. If you call notify( ) or notifyAll( ) method, thread moves to the notified state (runnable state).
  5. Now thread is available to acquire lock.
  6. After completion of the task, thread releases the lock and exits the monitor state of the object.




Q6. b) Create an Applet to draw different shapes on the basis of input given by user.

Answer : -

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class GenerateInputShape extends Applet
{
TextField t;
public void init()
{
t = new TextField(20);
add(t);
t.setText("");
}
public void paint(Graphics g)
{
String str="";
g.drawString("Enter the Shape Name", 20, 20);
try
{
str = t.getText();
}
catch(Exception e) { }
if(str.equalsIgnoreCase("Circle"))
{
// Draw a Circle
g.drawOval(150, 100, 180, 180);
}
else if(str.equalsIgnoreCase("Square"))
{
// Draw a Square
g.drawRect(150, 100, 150, 150);
}
else if(str.equalsIgnoreCase("Rectangle"))
{
// Draw a Rectangle
g.drawRect(150, 100, 200, 150);
}
else if(str.equalsIgnoreCase("Triangle"))
{
// x coordinates of vertices
int x[] = { 225, 300, 150 };
// y coordinates of vertices
int y[] = { 100, 250, 250 };
// 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.drawPolygon(p);
}
}
public boolean action(Event event, Object obj)
{
repaint();
return true;
}
}




Q7. a) What is object serialization? Explain working and use of object serialization.

Answer : - When you create a class, you may create an object for that particular class and once we execute/terminate the program, the object is destroyed by itself via the garbage collector thread.

What happens if you want to call that class without re-creating the object? In those cases, what you do is use the serialization concept by converting data into a byte stream.

Object Serialization is a process used to convert the state of an object into a byte stream, which can be persisted into disk/file or sent over the network to any other running Java virtual machine. The reverse process of creating an object from the byte stream is called deserialization. The byte stream created is platform independent. So, the object serialized on one platform can be deserialized on a different platform.

It is mainly used in Hibernate, RMI, JPA, EJB and JMS technologies.

For serializing the object, we call the writeObject( ) method of ObjectOutputStream class, and for deserialization we call the readObject( ) method of ObjectInputStream class. We must have to implement the Serializable interface for serializing the object.


java.io.Serializable interface

Serializable is a marker interface (has no data member and method). It is used to "mark" Java classes so that the objects of these classes may get a certain capability. It must be implemented by the class whose object you want to persist.

The String class and all the wrapper classes implement the java.io.Serializable interface by default.

Let's see the example given below :

import java.io.Serializable;
public class Student implements Serializable
{
int id;
String name;
public Student(int id, String name)
{
this.id = id;
this.name = name;
}
}

In the above example, Student class implements Serializable interface. Now its objects can be converted into stream.


Example of Java Serialization

In this example, we are going to serialize the object of Student class. The writeObject( ) method of ObjectOutputStream class provides the functionality to serialize the object. We are saving the state of the object in the file named Test.txt.

import java.io.*;
class Serialization
{
public static void main(String args[])
{
try
{
// Creating the object
Student ob1 = new Student(25,"Debabrata");
// Creating stream and writing the object
FileOutputStream fout = new FileOutputStream("Test.txt")
ObjectOutputStream out = new ObjectOutputStream(fout);
out.writeObject(ob1);
out.flush();
// Closing the stream
out.close();
System.out.println("Success");
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output :

Success


Example of Java Deserialization

Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. Let's see an example where we are reading the data from a deserialized object.

import java.io.*;
class Deserialization
{
public static void main(String args[])
{
try
{
// Creating stream to read the object
FileInputStream fin = new FileInputStream("Text.txt")
ObjectInputStream in = new ObjectInputStream(fin);
Student ob1 = (Student)in.readObject();
// Printing the data of the serialized object
System.out.println(ob1.id + "\t" + ob1.name);
// Closing the stream
in.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}

Output :

25   Debabrata




Q7. b) Explain different stream classes in java. Also write a java program to save the given data in a file.

Answer : -

Java Stream Class

import java.io.*;
public class FileWriteExample
{
public static void main(String args[])
{
try
{
FileWriter fw=new FileWriter("D:\\Test.txt");
fw.write("Welcome to Question Solves");
fw.close();
}
catch(Exception e){ System.out.println(e); }
System.out.println("Success...");
}
}




Q7. c) Explain difference between Srting and StringBuffer classes.

Answer : -

StringStringBuffer
String is slow and consumes more memory when you concat too many strings because every time it creates new instance.StringBuffer is fast and consumes less memory when you concat strings.
String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.StringBuffer class doesn't override the equals() method of Object class.



Q8. a) What is proxy server? Explain URL class and its methods in java.

Answer : - A proxy server is basically another computer which serves as a hub through which internet requests are processed. By connecting through one of these servers, your computer sends your requests to the server which then processes your request and returns what you were wanting. In this way it serves as an intermediary between your home machine and the rest of the computers on the internet.

Proxies are used for a number of reasons such as :


Java URL

The Java URL class represents an URL. URL is an acronym for Uniform Resource Locator. It points to a resource on the World Wide Web. For example :

http://www.questionsolves.com/Test.jsp

A URL contains many information :


Constructors of Java URL class

URL(String spec)
Creates an instance of a URL from the String representation.

URL(String protocol, String host, int port, String file)
Creates an instance of a URL from the given protocol, host, port number, and file.

URL(String protocol, String host, int port, String file, URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file, and handler.

URL(String protocol, String host, String file)
Creates an instance of a URL from the given protocol name, host name, and file name.

URL(URL context, String spec)
Creates an instance of a URL by parsing the given spec within a specified context.

URL(URL context, String spec, URLStreamHandler handler)
Creates an instance of a URL by parsing the given spec with the specified handler within a given context.


Commonly used methods of Java URL class

The java.net.URL class provides many methods. The important methods of URL class are given below.

MethodDescription
public String getProtocol( )it returns the protocol of the URL.
public String getHost( )it returns the host name of the URL.
public String getPort( )it returns the Port Number of the URL.
public String getFile( )it returns the file name of the URL.
public String getAuthority( )it returns the authority of the URL.
public String toString( )it returns the string representation of the URL.
public String getQuery( )it returns the query string of the URL.
public String getDefaultPort( )it returns the default port of the URL.
public URLConnection openConnection( )it returns the instance of URLConnection i.e. associated with this URL.
public Object getContent( )it returns the content of the URL.




Q8. b) Explain advantages of JDBC.

Answer : -




Q8. c) What is Servlet? Explain GET and POST methods of Servlet.

Answer : - Servlet can be described in many ways, depending on the context.


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 −




Q8. d) Explain TCP/IP Sockets.

Answer : - A socket programming interface provides the routines required for interprocess communication between applications, either on the local system or spread in a distributed, TCP/IP based network environment. Once a peer-to-peer connection is established, a socket descriptor is used to uniquely identify the connection. The socket descriptor itself is a task specific numerical value.

Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.

On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.

If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.

On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.

The client and server can now communicate by writing to or reading from their sockets.



ABOUT US

QuestionSolves.com is an educational website that helps worldwide students in solving computer education related queries.

Also, different software like Visual Studio, SQL Server, Oracle etc. are available to download in different versions.

Moreover, QuestionSolves.com provides solutions to your questions and assignments also.


MORE TOPIC


Windows Command

UNIX Command

IGNOU Assignment Solution

IGNOU Question Paper Solution

Solutions of Different Questions


WHAT WE DO


Website Devlopment

Training

Home Learning

Provide BCA, MCA Projects

Provide Assignment & Question Paper Solution


CONTACT US


Follow Us