Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
Output:
10
12
12
10
Output:
22
21
Output:
-11
9
false
true
Output:
15
5
50
2
0
Output:
21
Output:
40
80
80
240
Output:
2
5
2
Output:
5
5
-5
1073741819
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
Output:
false
10
false
11
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
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:
Output:
14
16
Output:
13
9
18
9
Output:
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;
}
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.
• Q3©Single Inheritance
• Multiple Inheritance (ThroughInterface)
• Multilevel Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance (Through Interface)
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.
void display() {
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
Example:
final class stud {
void show() {
System.out.println("Book-Class method");
B1.show();
Example:
class stud {
void show() {
B2.show();
import java.lang.*;
import java.io.*;
class stud {
stud() {
val = 60;
void method() {
System.out.println(val);
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
import java.util.Vector;
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.
Compile time errors can be again classified again into two types:
• Syntax Errors
• Semantic Errors
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.
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.
During the actual production run, the server is down. When your program tried to
access it, an exception is raised.
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){
return i;
}
try
{
res = divideByZero(a,b);
}
// doesn't matches with ArithmeticException
catch(NumberFormatException ex)
{
System.out.println("NumberFormatException is occured");
}
return res;
}
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.
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
}
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
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(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:
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
should be notified by notify() or notifyAll() methods after the specified amount of time, sleep is
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.*;
// y coordinates of vertices
int y[] = { 140, 110, 50, 40, 30, 10 };
// number of vertices
int numberofpoints = 6;
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{
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.
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");
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.
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.
Output:
Success...
testout.txt
BASIS FOR
STRING STRINGBUFFER
COMPARISON
increased.
immutable. mutable.
concatenation. concatenation.
memory.
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);
}
}
5. No Installation
A pure JDBC technology-based driver does not require special installation.
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.