Sei sulla pagina 1di 45

Q1.

(A) The Object Oriented Programming ( OOPs ) can be defined as a


programming model or paradigm that emphasizes or focus mainly on objects.
The object oriented programming considers data important rather than actions
(functions). Object Oriented Programming is not a programming language
rather than it is a programming model that the programming languages follow.

Advantages / benefits of the objects:


• Objects can hide the actual data from the outside world by making the data
private and allowing the data access through the functions or methods only.
• The source codes of each object are independent of each other, so we can
achieve the modularity in the program using objects.
• If an object is raising some errors so we can easily replace with another so the
debugging becomes easy.
• In Object Oriented Programming abstraction concept the actual
implementation is hidden from the user and only required functionality
will be accessible or available to the user.

• Abstraction is a powerful methodology to manage complex systems.


Abstraction is managed by well-defined objects and their hierarchical
classification.

• Data Hiding in OOP -


• Data hiding is the process of making the data members private so those
will not be visible to other classes. The data of a object is not accessible
to another objects, because each object has independent copy of the
instance variables.

Q1 (B) Operator in java is a symbol that is used to perform operations. For example:
+, -, *, / etc.

There are many types of operators in java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %

additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator


The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.:

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --


1. class OperatorExample{
2. public static void main(String args[]){
3. int x=10;
4. System.out.println(x++);//10 (11)
5. System.out.println(++x);//12
6. System.out.println(x--);//12 (11)
7. System.out.println(--x);//10
8. }}

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=10;
5. System.out.println(a++ + ++a);//10+12=22
6. System.out.println(b++ + b++);//10+11=21
7.
8. }}

Output:

22
21

Java Unary Operator Example: ~ and !


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=-10;
5. boolean c=true;
6. boolean d=false;
7. System.out.println(~a);//-11 (minus of total positive value which starts from 0)
8. System.out.println(~b);//9 (positive of total minus, positive starts from 0)
9. System.out.println(!c);//false (opposite of boolean value)
10. System.out.println(!d);//true
11. }}

Output:

-11
9
false
true

Java Arithmetic Operators


Java arithmatic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.

Java Arithmetic Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. System.out.println(a+b);//15
6. System.out.println(a-b);//5
7. System.out.println(a*b);//50
8. System.out.println(a/b);//2
9. System.out.println(a%b);//0
10. }}

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression


1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10*10/5+3-1*4/2);
4. }}

Output:

21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10<<2);//10*2^2=10*4=40
4. System.out.println(10<<3);//10*2^3=10*8=80
5. System.out.println(20<<2);//20*2^2=20*4=80
6. System.out.println(15<<4);//15*2^4=15*16=240
7. }}

Output:

40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move left operands value to right by the number
of bits specified by the right operand.

Java Right Shift Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. System.out.println(10>>2);//10/2^2=10/4=2
4. System.out.println(20>>2);//20/2^2=20/4=5
5. System.out.println(20>>3);//20/2^3=20/8=2
6. }}

Output:
2
5
2

Java Shift Operator Example: >> vs >>>


1. class OperatorExample{
2. public static void main(String args[]){
3. //For positive number, >> and >>> works same
4. System.out.println(20>>2);
5. System.out.println(20>>>2);
6. //For negative number, >>> changes parity bit (MSB) to 0
7. System.out.println(-20>>2);
8. System.out.println(-20>>>2);
9. }}

Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &


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

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

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a<c);//false && true = false
7. System.out.println(a<b&a<c);//false & true = false
8. }}

Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a<b&&a++<c);//false && true = false
7. System.out.println(a);//10 because second condition is not checked
8. System.out.println(a<b&a++<c);//false && true = false
9. System.out.println(a);//11 because second condition is checked
10. }}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


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

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

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int c=20;
6. System.out.println(a>b||a<c);//true || true = true
7. System.out.println(a>b|a<c);//true | true = true
8. //|| vs |
9. System.out.println(a>b||a++<c);//true || true = true
10. System.out.println(a);//10 because second condition is not checked
11. System.out.println(a>b|a++<c);//true | true = true
12. System.out.println(a);//11 because second condition is checked
13. }}

Output:

true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one liner replacement for if-then-else statement and used
a lot in java programming. it is the only conditional operator which takes three operands.

Java Ternary Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=2;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Another Example:

1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=5;
5. int min=(a<b)?a:b;
6. System.out.println(min);
7. }}

Output:

Java Assignment Operator


Java assignment operator is one of the most common operator. It is used to assign the
value on its right to the operand on its left.

Java Assignment Operator Example


1. class OperatorExample{
2. public static void main(String args[]){
3. int a=10;
4. int b=20;
5. a+=4;//a=a+4 (a=10+4)
6. b-=4;//b=b-4 (b=20-4)
7. System.out.println(a);
8. System.out.println(b);
9. }}

Output:

14
16

Java Assignment Operator Example


1. class OperatorExample{
2. public static void main(String[] args){
3. int a=10;
4. a+=3;//10+3
5. System.out.println(a);
6. a-=4;//13-4
7. System.out.println(a);
8. a*=2;//9*2
9. System.out.println(a);
10. a/=2;//18/2
11. System.out.println(a);
12. }}

Output:

13
9
18
9

Java Assignment Operator Example: Adding short


1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. //a+=b;//a=a+b internally so fine
6. a=a+b;//Compile time error because 10+10=20 now int
7. System.out.println(a);
8. }}

Output:

Compile time error

After type cast:

1. class OperatorExample{
2. public static void main(String args[]){
3. short a=10;
4. short b=10;
5. a=(short)(a+b);//20 which is int now converted to short
6. System.out.println(a);
7. }}

Q2(a) A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all objects of
one type. In general, class declarations can include these components, in order:
1. Modifiers : A class can be public or has default access (Refer this for details).
2. Class name: The name should begin with a initial letter (capitalized by
convention).
3. Superclass(if any): The name of the class’s parent (superclass), if any, preceded
by the keyword extends. A class can only extend (subclass) one parent.
4. Interfaces(if any): A comma-separated list of interfaces implemented by the class,
if any, preceded by the keyword implements. A class can implement more than
one interface.
5. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the
state of the class and its objects, and methods are used to implement the behavior of
the class and its objects.
There are various types of classes that are used in real time applications such
as nested classes, anonymous classes, lambda expressions.
1. class Lamp {
2.
3. // instance variable
4. private boolean isOn;
5.
6. // method
7. public void turnOn() {
8. isOn = true;
9. }
10.
11. // method
12. public void turnOff() {
13. isOn = false;
14. }
15. }
Q2(B)
package com.jwt.core.java;

public class Account {

private int balance = 3000;

public int balance() {


return balance;
}

public void withdraw(int amount) throws InSufficientFundException {


if (amount > balance) {
throw new InSufficientFundException(String.format(
"Current balance %d is less than requested amount %d",
balance, amount));
}
balance = balance - amount;
}

public void deposit(int amount) {


if (amount <= 0) {
throw new IllegalArgumentException(String.format(
"Invalid deposit amount %s", amount));
}
}

}
Test.java
Now create a test class to test our implemented Custom Exception Class.
1 package com.jwt.core.java;
2
3 public class Test {
4
5 public static void main(String args[]) {
6 Account acct = new Account();
7 System.out.println("Current balance : " + acct.balance());
8 System.out.println("Withdrawing $200");
9 acct.withdraw(200);
10 System.out.println("Current balance : " + acct.balance());
11 acct.withdraw(3500);
12
13 }
14
15

Q3(A) If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.

Example of static method


1. //Java Program to demonstrate the use of a static method.
2. class Student{
3. int rollno;
4. String name;
5. static String college = "ITS";
6. //static method to change the value of static variable
7. static void change(){
8. college = "BBDIT";
9. }
10. //constructor to initialize the variable
11. Student(int r, String n){
12. rollno = r;
13. name = n;
14. }
15. //method to display values
16. void display(){System.out.println(rollno+" "+name+" "+college);}
17. }
18. //Test class to create and display the values of object
19. public class TestStaticMethod{
20. public static void main(String args[]){
21. Student.change();//calling change method
22. //creating objects
23. Student s1 = new Student(111,"Karan");
24. Student s2 = new Student(222,"Aryan");
25. Student s3 = new Student(333,"Sonoo");
26. //calling display method
27. s1.display();
28. s2.display();
29. s3.display();
30. }
31. }

1. Q3(B) import java.util.Scanner;


2.
3. class AddTwoMatrix
4. {
5. public static void main(String args[])
6. {
7. int m, n, c, d;
8. Scanner in = new Scanner(System.in);
9.
10. System.out.println("Enter the number of rows and columns
of matrix");
11. m = in.nextInt();
12. n = in.nextInt();
13.
14. int first[][] = new int[m][n];
15. int second[][] = new int[m][n];
16. int sum[][] = new int[m][n];
17.
18. System.out.println("Enter the elements of first
matrix");
19.
20. for (c = 0; c < m; c++)
21. for (d = 0; d < n; d++)
22. first[c][d] = in.nextInt();
23.
24. System.out.println("Enter the elements of second
matrix");
25.
26. for (c = 0 ; c < m ; c++)
27. for (d = 0 ; d < n ; d++)
28. second[c][d] = in.nextInt();
29.
30. for (c = 0; c < m; c++)
31. for (d = 0; d < n; d++)
32. sum[c][d] = first[c][d] + second[c][d]; //replac
e '+' with '-' to subtract matrices
33.
34. System.out.println("Sum of the matrices:");
35.
36. for (c = 0; c < m; c++)
37. {
38. for (d = 0; d < n; d++)
39. System.out.print(sum[c][d]+"\t");
40.
41. System.out.println();
42. }
43. }
44. }

• Q3©Single Inheritance
• Multiple Inheritance (ThroughInterface)
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance (Through Interface)

Lets see about each one of them one by one.

1. Single Inheritance in Java


Single Inheritance is the simple inheritance of all, When a class extends another
class(Only one class) then we call it as Single inheritance. The below diagram
represents the single inheritance in java where Class B extends only one class Class
A. Here Class B will be the Sub class and Class A will be one and only Super class.

Single Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispA() method of ClassA
b.dispA();
//call dispB() method of ClassB
b.dispB();
}
}
Output :

disp() method of ClassA


disp() method of ClassB
2. Multiple Inheritance in Java
Multiple Inheritance is nothing but one class extending more than one class. Multiple
Inheritance is basically not supported by many Object Oriented
Programminglanguages such as Java, Small Talk, C# etc.. (C++ Supports Multiple
Inheritance). As the Child class has to manage the dependency of more than
one Parent class. But you can achieve multiple inheritance in Java using Interfaces.

3. Multilevel Inheritance in Java


In Multilevel Inheritance a derived class will be inheriting a parent class and as well
as the derived class act as the parent class to other class. As seen in the below
diagram. ClassB inherits the property of ClassA and again ClassB act as a parent
for ClassC. In Short ClassA parent for ClassB and ClassB parent for ClassC.
MultiLevel Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference
ClassC c = new ClassC();
//call dispA() method of ClassA
c.dispA();
//call dispB() method of ClassB
c.dispB();
//call dispC() method of ClassC
c.dispC();
}
}
Output :

disp() method of ClassA


disp() method of ClassB
disp() method of ClassC
4. Hierarchical Inheritance in Java
In Hierarchical inheritance one parent class will be inherited by many sub classes. As
per the below example ClassA will be inherited by ClassB,
ClassC and ClassD. ClassAwill be acting as a parent class for ClassB,
ClassC and ClassD.

Hierarchical Inheritance Example

public class ClassA


{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB
b.dispB();
//call dispA() method of ClassA
b.dispA();

//Assigning ClassC object to ClassC reference


ClassC c = new ClassC();
//call dispC() method of ClassC
c.dispC();
//call dispA() method of ClassA
c.dispA();

//Assigning ClassD object to ClassD reference


ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Output :

disp() method of ClassB


disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA
5. Hybrid Inheritance in Java
Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface we can
achieve this. Flow diagram of the Hybrid inheritance will look like below. As you
can ClassA will be acting as the Parent class for ClassB & ClassC and ClassB &
ClassC will be acting as Parent for ClassD.
Q4.SUPERSuper is a keyword of Java which refers to the immediate parent of a class
and is used inside the subclass method definition for calling a method defined in the
superclass. A superclass having methods as private cannot be called. Only the methods
which are public and protected can be called by the keyword super. It is also used by
class constructors to invoke constructors of its parent class.

Syntax:
super.<method-name>();

Usage of superclass
• Super variables refer to the variable of a variable of the parent class.
• Super() invokes the constructor of immediate parent class.
• Super refers to the method of the parent class.

Here is an example of Java program which uses the super


keyword
Example:
class employee {
int wt = 8;

class clerk extends employee {

int wt = 10; //work time

void display() {

System.out.println(super.wt); //will print work time of clerk

public static void main(String args[]) {

clerk c = new clerk();

c.display();

Output:
8

Instance refers an instance variable of the current class by default, but when you have
to refer parent class instance variable, you have to use super keyword to distinguish
between parent class (here employee) instance variable and current class (here, clerk)
instance variable.

FINAL KEYWORD:

Final is a keyword in Java that is used to restrict the user and can be used in many
respects. Final can be used with:

• Class
• Methods
• Variables

Class declared as final


When a class is declared as final, it cannot be extended further. Here is an example
what happens within a program

Example:
final class stud {

// Methods cannot be extended to its sub class

class books extends stud {

void show() {

System.out.println("Book-Class method");

public static void main(String args[]) {

books B1 = new books();

B1.show();

This will show an error that:

error: cannot inherit from final stud

class books extends stud{

This is because classes declared as final cannot be inherited.


Method declared as Final
A method declared as final cannot be overridden; this means even when a child class
can call the final method of parent class without any issues, but the overriding will not
be possible. Here is a sample program showing what is not valid within a Java program
when a method is declared as final.

Example:
class stud {

final void show() {

System.out.println("Class - stud : method defined");

class books extends stud {

void show() {

System.out.println("Class - books : method defined");

public static void main(String args[]) {

books B2 = new books();

B2.show();

Variable declared as final


Once a variable is assigned with the keyword final, it always contains the same exact
value. Again things may happen like this; if a final variable holds a reference to an
object then the state of the object can be altered if programmers perform certain
operations on those objects, but the variable will always refer to the same object. A final
variable that is not initialized at the time of declaration is known as a blank final variable.
If you are declaring a final variable in a constructor, then you must initialize the blank
final variable within the constructor of the class. Otherwise, the program might show a
compilation error.

Here is an example of a program in Java showing the use of the


final variable
Example:
import java.util.*;

import java.lang.*;

import java.io.*;

class stud {

final int val;

stud() {

val = 60;

void method() {

System.out.println(val);

public static void main(String args[]) {

stud S1 = new stud();

S1.method();

}
What is blank or uninitialized final variable?
A final variable that is not initialized at the time of declaration is called the blank final
variable. when you want to create a variable that is initialized at the time of creating an
object and once initialized may not be changed, use the final keyword, and it will be
beneficial in this case. For example PAN CARD number of an employee. It can be
initialized only in the constructor

Q4(B) Packages In Java


Package in Java is a mechanism to encapsulate a group of classes, sub packages and
interfaces. Packages are used for:
• Preventing naming conflicts. For example there can be two classes with name
Employee in two packages, college.staff.cse.Employee and
college.staff.ee.Employee
• Making searching/locating and usage of classes, interfaces, enumerations and
annotations easier
• Providing controlled access: protected and default have package level access
control. A protected member is accessible by classes in the same package and its
subclasses. A default member (without any access specifier) is accessible by
classes in the same package only.
• Packages can be considered as data encapsulation (or data-hiding).
All we need to do is put related classes into packages. After that, we can simply write an
import class from existing packages and use it in our program. A package is a container
of a group of related classes where some of the classes are accessible are exposed
and others are kept for internal purpose.
We can reuse existing classes from the packages as many time as we need it in our
program.
How packages work?
Package names and directory structure are closely related. For example if a package
name is college.staff.cse, then there are three directories, college, staff and cse such
that cse is present in staff and staff is present college. Also, the directory college is
accessible through CLASSPATH variable, i.e., path of parent directory of college is
present in CLASSPATH. The idea is to make sure that classes are easy to locate.
Package naming conventions : Packages are named in reverse order of domain
names, i.e., org.geeksforgeeks.practice. For example, in a college, the recommended
convention is college.tech.cse, college.tech.ee, college.art.history, etc.

import java.util.Vector;

public class ImportDemo


{
public ImportDemo()
{
// java.util.Vector is imported, hence we are
// able to access directly in our code.
Vector newVector = new Vector();

// java.util.ArrayList is not imported, hence


// we were referring to it using the complete
// package.
java.util.ArrayList newList = new java.util.ArrayList();
}

public static void main(String arg[])


{
new ImportDemo();
}
}
Q4©ADVANTAGES OF POLYMORPHISM
• It helps programmers reuse the code and classes once written, tested and
implemented. They can be reused in many ways.
• Single variable name can be used to store variables of multiple data types(Float,
double, Long, Int etc).
• Polymorphism helps in reducing the coupling between different functionalities.

DISADVANTAGES OF POLYMORPHISM
• One of the disadvantages of polymorphism is that developers find it difficult to
implement polymorphism in codes.
• Run time polymorphism can lead to the performance issue as machine needs to
decide which method or variable to invoke so it basically degrades the performances as
decisions are taken at run time.
• Polymorphism reduces the readability of the program. One needs to identify the
runtime behavior of the program to identify actual execution time.

Q5(A) Difference Between Interface and Abstract Class


Last modified on September 7th, 2014 by Joe.

1. Main difference is methods of a Java interface are implicitly abstract and


cannot have implementations. A Java abstract class can have instance
methods that implements a default behavior.
2. Variables declared in a Java interface is by default final. An abstract class
may contain non-final variables.
3. Members of a Java interface are public by default. A Java abstract class can
have the usual flavors of class members like private, protected, etc..
4. Java interface should be implemented using keyword “implements”; A
Java abstract class should be extended using keyword “extends”.
5. An interface can extend another Java interface only, an abstract class can
extend another Java class and implement multiple Java interfaces.
6. A Java class can implement multiple interfaces but it can extend only one
abstract class.
7. Interface is absolutely abstract and cannot be instantiated; A Java abstract
class also cannot be instantiated, but can be invoked if a main() exists.
8. In comparison with java abstract classes, java interfaces are slow as it
requires extra indirection.

Q5(B) Exception is an event that interrupts the normal flow of execution. It is a


disruption during the execution of the Java program.

There are two types of errors:

1. Compile time errors


2. Runtime errors

Compile time errors can be again classified again into two types:

• Syntax Errors
• Semantic Errors

Syntax Errors Example:

Instead of declaring int a; you mistakenly declared it as in a; for which compiler


will throw an error.

Example: You have declared a variable int a; and after some lines of code you
again declare an integer as int a;. All these errors are highlighted when you
compile the code.

Runtime Errors Example

A Runtime error is called an Exceptions error. It is any event that interrupts the
normal flow of program execution.
Example for exceptions are, arithmetic exception, Nullpointer exception, Divide by
zero exception, etc.

Exceptions in Java are something that is out of developers control.

Click here if the video is not accessible

Why do we need Exception?


Suppose you have coded a program to access the server. Things worked fine while
you were developing the code.

During the actual production run, the server is down. When your program tried to
access it, an exception is raised.

How to Handle Exception


So far we have seen, exception is beyond developer's control. But blaming your
code failure on environmental issues is not a solution. You need a Robust
Programming, which takes care of exceptional situations. Such code is known
as Exception Handler.

In our example, good exception handling would be, when the server is down,
connect to the backup server.

To implement this, enter your code to connect to the server (Using traditional if
and else conditions).

You will check if the server is down. If yes, write the code to connect to the backup
server.
Such organization of code, using "if" and "else" loop is not effective when your
code has multiple java exceptions to handle.

class connect{
if(Server Up){
// code to connect to server
}
else{
// code to connect to BACKUP server
}

class ExceptionThrown
{
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found within this method.
static int divideByZero(int a, int b){

// this statement will cause ArithmeticException(/ by zero)


int i = a/b;

return i;
}

// The runTime System searches the appropriate Exception handler


// in this method also but couldn't have found. So looking forward
// on the call stack.
static int computeDivision(int a, int b) {

int res =0;

try
{
res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}

// In this method found appropriate Exception handler.


// i.e. matching catch block.
public static void main(String args[]){

int a = 1;
int b = 0;
try
{
int i = computeDivision(a,b);

// matching ArithmeticException
catch(ArithmeticException ex)
{
// getMessage will print description of exception(here / by zero)
System.out.println(ex.getMessage());
}
}
}
Q5©Multithreading is a Java feature that allows concurrent execution of two or more
parts of a program for maximum utilization of CPU. Each part of such program is called
a thread. So, threads are light-weight processes within a process.

Threads can be created by using two mechanisms :


1. Extending the Thread class
2. Implementing the Runnable Interface

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class overrides the
run() method available in the Thread class. A thread begins its life inside run() method.
We create an object of our new class and call start() method to start the execution of a
thread. Start() invokes the run() method on the Thread object.

filter_none
edit
play_arrow
brightness_4
// Java code for thread creation by extending
// the Thread class
class MultithreadingDemo extends Thread
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
public class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

Thread creation by implementing the Runnable Interface

We create a new class which implements java.lang.Runnable interface and override


run() method. Then we instantiate a Thread object and call start() method on this object.
filter_none
edit
play_arrow
brightness_4
// Java code for thread creation by implementing
// the Runnable Interface
class MultithreadingDemo implements Runnable
{
public void run()
{
try
{
// Displaying the thread that is running
System.out.println ("Thread " +
Thread.currentThread().getId() +
" is running");

}
catch (Exception e)
{
// Throwing an exception
System.out.println ("Exception is caught");
}
}
}

// Main Class
class Multithread
{
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i=0; i<8; i++)
{
Thread object = new Thread(new MultithreadingDemo());
object.start();
}
}
}
Output :
Thread 8 is running
Thread 9 is running
Thread 10 is running
Thread 11 is running
Thread 12 is running
Thread 13 is running
Thread 14 is running
Thread 15 is running

Q6(A) 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:

o wait()
o notify()
o notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description

public final void wait()throws InterruptedException waits until object is notified.

public final void wait(long timeout)throws InterruptedException waits for the specified amou

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting
on this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at
the discretion of the implementation. Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

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.

Why wait(), notify() and notifyAll() methods are defined in Object


class not Thread class?
It is because they are related to lock and object has a lock.

Difference between wait and sleep?


Let's see the important differences between wait and sleep methods.

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.

is the method of Object class is the method of Thread class

is the non-static method is the static method

is the non-static method is the static method

should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is

Example of inter thread communication in java


Let's see the simple example of inter thread communication.

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}
Output: going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed
Q6(B) drawPolygon(int[] x, int[] y, int numberofpoints) : draws a polygon with the
given set of x and y points.

filter_none
edit
play_arrow
brightness_4
// Java program to draw polygon using
// drawPolygon(int[] x, int[] y, int numberofpoints)
// function
import java.awt.*;
import javax.swing.*;

public class poly extends JApplet {

// called when applet is started


public void init()
{
// set the size of applet to 300, 300
setSize(200, 200);
show();
}

// invoked when applet is started


public void start()
{
}

// invoked when applet is closed


public void stop()
{
}

public void paint(Graphics g)


{
// x coordinates of vertices
int x[] = { 10, 30, 40, 50, 110, 140 };

// y coordinates of vertices
int y[] = { 140, 110, 50, 40, 30, 10 };

// number of vertices
int numberofpoints = 6;

// set the color of line drawn to blue


g.setColor(Color.blue);

// draw the polygon using drawPolygon function


g.drawPolygon(x, y, numberofpoints);
}
}
Output :

Q7(A) Serialization is a mechanism of converting the state of an object into a byte


stream. Deserialization is the reverse process where the byte stream is used to recreate
the actual Java object in memory. This mechanism is used to persist the object.
The byte stream created is platform independent. So, the object serialized on one
platform can be deserialized on a different platform.
To make a Java object serializable we implement the java.io.Serializable interface.
The ObjectOutputStream class contains writeObject() method for serializing an Object.
public final void writeObject(Object obj)
throws IOException
The ObjectInputStream class contains readObject() method for deserializing an object.
public final Object readObject()
throws IOException,
ClassNotFoundException

Advantages of Serialization
1. To save/persist state of an object.
2. To travel an object across a network.
Only the objects of those classes can be serialized which are
implementing java.io.Serializable interface.
Serializable is a marker interface (has no data member and method). It is used to
“mark” java classes so that objects of these classes may get certain capability. Other
examples of marker interfaces are:- Cloneable and Remote.
Points to remember
1. If a parent class has implemented Serializable interface then child class doesn’t need
to implement it but vice-versa is not true.
2. Only non-static data members are saved via Serialization process.
3. Static data members and transient data members are not saved via Serialization
process.So, if you don’t want to save value of a non-static data member then make it
transient.
4. Constructor of object is never called when an object is deserialized.
5. Associated objects must be implementing Serializable interface.
Example :
class A implements Serializable{

// B also implements Serializable


// interface.
B ob=new B();
}

Q7(B) A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a
stream because it is like a stream of water that continues to flow.

In Java, 3 streams are created for us automatically. All these streams are attached with the
console.

1) System.out: standard output stream


2) System.in: standard input stream

3) System.err: standard error stream

Let's see the code to print output and an error message to the console.

1. System.out.println("simple message");
2. System.err.println("error message");

Let's see the code to get input from console.

1. int i=System.in.read();//returns ASCII code of 1st character


2. System.out.println((char)i);//will print the character

Java FileOutputStream Class


Java FileOutputStream is an output stream used for writing data to a file.

If you have to write primitive values into a file, use FileOutputStream class. You can write
byte-oriented as well as character-oriented data through FileOutputStream class. But, for
character-oriented data, it is preferred to use FileWriter than FileOutputStream.

FileOutputStream class declaration


Let's see the declaration for Java.io.FileOutputStream class:

1. public class FileOutputStream extends OutputStream

FileOutputStream class methods

Method Description

protected void finalize() It is used to clean up the connection with the file output stream.

void write(byte[] ary) It is used to write ary.length bytes from the byte array to the file
stream.

void write(byte[] ary, int off, It is used to write len bytes from the byte array starting at offset
int len) output stream.
void write(int b) It is used to write the specified byte to the file output stream.

FileChannel getChannel() It is used to return the file channel object associated with the file
stream.

FileDescriptor getFD() It is used to return the file descriptor associated with the stream.

void close() It is used to closes the file output stream.

Java FileOutputStream Example 1: write byte


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. fout.write(65);
7. fout.close();
8. System.out.println("success...");
9. }catch(Exception e){System.out.println(e);}
10. }
11. }

Output:

Success...

The content of a text file testout.txt is set with the data A.

testout.txt

Java FileOutputStream example 2: write string


1. import java.io.FileOutputStream;
2. public class FileOutputStreamExample {
3. public static void main(String args[]){
4. try{
5. FileOutputStream fout=new FileOutputStream("D:\\testout.txt");
6. String s="Welcome to javaTpoint.";
7. byte b[]=s.getBytes();//converting string into byte array
8. fout.write(b);
9. fout.close();
10. System.out.println("success...");
11. }catch(Exception e){System.out.println(e);}
12. }
13. }

Q7© Comparison Chart

BASIS FOR
STRING STRINGBUFFER
COMPARISON

Basic The length of the String The length of the

object is fixed. StringBuffer can be

increased.

Modification String object is StringBuffer object is

immutable. mutable.

Performance It is slower during It is faster during

concatenation. concatenation.

Memory Consumes more Consumes less memory.

memory.

Storage String constant pool. Heap Memory.


Q8(A) n Java, the proxy itself is not as important as the proxy’s behaviour.
The latter is done in an implementation
of java.lang.reflect.InvocationHandler. It has only a single method to
implement:
public Object invoke(Object proxy, Method method, Object[] args)

• proxy: the proxy instance that the method was invoked on


• method: the Method instance corresponding to the interface method
invoked on the proxy instance. The declaring class of the Method
object will be the interface that the method was declared in, which
may be a superinterface of the proxy interface that the proxy class
inherits the method through
• args: an array of objects containing the values of the arguments
passed in the method invocation on the proxy instance, or null if
interface method takes no arguments. Arguments of primitive types
are wrapped in instances of the appropriate primitive wrapper class,
such as java.lang.Integer or java.lang.Boolean

Let’s take a simple example: suppose we want a List that can’t be added
elements to it. The first step is to create the invocation handler:
public class NoOpAddInvocationHandler implements InvocationHandler {
private final List proxied;
public NoOpAddInvocationHandler(List proxied) {
this.proxied = proxied;
}
public Object invoke(Object proxy, Method method, Object[] args) throws Thr
owable {
if (method.getName().startsWith("add")) {
return false;
}
return method.invoke(proxied, args);
}
}

Q8(B) List the advantages of JDBC


1. Provide Existing Enterprise Data
Businesses can continue to use their installed databases and access
information even if it is stored on different database management
systems.
2. Simplified Enterprise Development
The combination of the Java API and the JDBC API makes application
development easy and cost effective.

3. Zero Configuration for Network Computers


No configuration is required on the client side centralizes software
maintenance. Driver is written in the Java, so all the information needed to
make a connection is completely defined by the JDBC URL or by a
DataSource object. DataSource object is registered with a Java Naming
and Directory Interface (JNDI) naming service.

4. Full Access to Metadata


The underlying facilities and capabilities of a specific database connection
need to be understood. The JDBC API provides metadata access that
enables the development of sophisticated applications.

5. No Installation
A pure JDBC technology-based driver does not require special installation.

6. Database Connection Identified by URL


The JDBC API includes a way to identify and connect to a data source,
using a DataSource object. This makes code even more portable and
easier to maintain.

Q8©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.test.com/hello?key1 = value1&key2 = value2
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.

Reading Form Data using Servlet


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(D) 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.
One end of a peer-to-peer connection of a TCP/IP based distributed network application
described by a socket is uniquely defined by
• Internet address
for example 127.0.0.1 (in an IPv4 network) or FF01::101 (in an IPv6 network).
• Communication protocol
o User Datagram Protocol (UDP)
o Transmission Control Protocol (TCP)
• Port
A numerical value, identifying an application. We distinguish between
o "well known" ports, for example port 23 for Telnet
o user defined ports
Socket applications were usually C or C++ applications using a variation of the socket
API originally defined by the Berkeley Software Distribution (BSD). The JAVA language
also provides a socket API. JAVA based Client/Server applications exploit those socket
services.
Socket programming interfaces have been standardized for ease of portability by The
Open Group for example.
Besides TCP/IP based sockets, UNIX systems provide socket interfaces for
interprocess communication (IPC) within the local UNIX host itself. Those UNIX sockets
use the local file system for interprocess communication.
z/VSE provides TCP/IP based socket services. They can be used for IPC too, although
they are primarily aimed for network communication only.

Potrebbero piacerti anche