320245-VIMP Java Questions
320245-VIMP Java Questions
It is a binary operator denoted by the symbol &. It returns 1 if and only if both bits are 1, else returns
0.
It is a binary operator denoted by the symbol ^ (pronounced as caret). It returns 0 if both bits are the
same, else returns 1
String str=”5”;
int value=5;
String str=Integer.toString(value);
Ans - Constructor: A constructor is a special member which initializes an object immediately upon
creation. It has the same name as class name in which it resides and it is syntactically similar to any
method. When a constructor is not defined, java executes a default constructor which initializes all
numeric members to zero and other types to null or spaces. Once defined, constructor is
automatically called immediately after the object is created before new operator completes.
Types of constructors:
1. Default constructor
2. Parameterized constructor
3. Copy constructor
Ans - The access specifiers in java specify accessibility (scope) of a data member, method,
constructor or class. There are 5 types of java access specifier:
public
private
default (Friendly)
protected
Ans - An array is a homogeneous data type where it can hold only objects of one data type.
Types of Array:
1)One-Dimensional
2)Two-Dimensional
Ans - Garbage collection in Java is the automated process of deleting code that's no longer needed
or used. This automatically frees up memory space and ideally makes coding Java apps easier for
developers. Java applications are compiled into bytecode that may be executed by a JVM.
9. Draw structural diagram of fiber optic cable and write its functions.
Ans –
1. Single-mode fibers - Used to transmit one signal per fiber (used in telephones
2. Multi-mode fibers - Used to transmit many signals per fiber (used in computer networks, local
area networks)
10. List the types of inheritance which is supported by java. (Summer 19)(Winter 22)
Ans –
Ans –
1.java.lang
2.java.util
3.java.io
4.java.awt
5.java.net
6.ava.applet
Ans –
Use of finalize( ):
Sometimes an object will need to perform some action when it is destroyed. Eg. If an object holding
some non java resources such as
the finalize() method. The java run-time calls this method whenever it
Syntax:
e.g.c:\mypack
import mypack.*;
-d c:\mypack className.java
To run
Java className
14. List out different ways to access package from another package
Ans –
There are three ways to access the package from outside the package.
1) import package.*;
2) import package.classname;
Ans - Errors are mistakes that can make a program go wrong. Errors may be logical or may be typing
mistakes. An error may produce an incorrect output or may terminate the execution of the program
abruptly or even may cause the system to crash. Errors are broadly classified into two categories:
2. Runtime errors
Ans –
try{
} catch(ThrowableInstance1 obj) {
} catch(ThrowableInstance2 obj2) {
//Statements
Ans - 1. Thread is a smallest unit of executable code or a single task is also called as thread.
2. Each tread has its own local variable, program counter and lifetime.
Ans –
2. Improper casing
3. Mismatched brackets
4. Missing semicolons
5. Method is undefined
19. Differentiate between starting thread with run() method and start()method
Ans - start method of thread class is implemented as when it is called a new Thread is created and
code inside run() method is executed in that new Thread. While if run method is executed directly
than no new Thread is created and code inside run() will execute on current Thread and no multi-
threading will take place.
4 Marks Questions
Ans –
Code:
class PrimeExample
{
public static void main(String args[]){
int i,m=0,flag=0;
int n=7;//it is the number to be checked
m=n/2;
if(n==0||n==1){
System.out.println(n+" is not prime number");
}else{
for(i=2;i<=m;i++){
if(n%i==0){
System.out.println(n+" is not prime number");
flag=1;
break;
}
}
if(flag==0) { System.out.println(n+" is prime number"); }
}//end of else
}
}
Output:
7 is prime number
Ans - Logical Operators: Logical operators are used when we want to form
compound conditions by combining two or more relations. Java has three
logical operators as shown in table
Ans –
public class ReverseNumberExample1 {
public static void main(String[] args) {
int number = 987654, reverse =0;
while(number !=0) {
int remainder = number % 10;
reverse = reverse * 10 + remainder;
number = number/10; }
System.out.printtln(“The reverse of the given number is: “ + reverse); } }
2)Robust
The English mining of Robust is strong. Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security problems.
Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of
objects which are not being used by a Java application anymore.
There are exception handling and the type checking mechanism in Java. All these points make Java
robust.
3)Architecture-neutral
Java is architecture neutral because there are no implementation dependent features, for example, the
size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
7. Write all primitive data types available in Java with their storage Sizes in bytes. (winter 22)
Ans –
8. Write a Java program to find out the even numbers from 1 to 100 using for loop. (summer 22)
9. Explain switch case and conditional operator in java with suitable example(summer 22)
Ans –
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some
wrapper types like Byte, Short, Int, and Long.
There can be one or N number of case values for a switch expression.
import java.io.*;
System.out.println(); }
{ System.out.println("Withdrawn Operation:");
displayBalance(balance);
else {
System.out.println(); }
System.out.println("Deposit Operation:");
displayBalance(balance);
return balance; }
displayBalance(balance);
// withdrawing amount
// depositing amount
Output
Withdrawn Operation:
Deposit Operation:
Depositing Amount : 2000
11. Describe instance Of and dot (.) operators in Java with suitable example.(summer 19 )
Ans - Instance of operator:
false. If we apply the instance of operator with any variable that has
null value, it returns false.
Example
class Simple1{
public static void main(String args[]){
Simple1 s=new Simple1();
System.out.println(sinstanceofSimple1);//true
}
}
dot (.) operator:
Example
this.name=”john”; where name is a instance variable referenced by
‘this’ keyword
12. Explain the types of constructors in Java with suitable example. (summer 19,winter 19
,Summer 23)
Ans –
1. Default constructor
3. Parameterized constructor
4. Copy constructor
class test1 {
int i;
boolean b;
byte bt;
String s;
System.out.println(t.i);
System.out.println(t.s);
System.out.println(t.b);
System.out.println(t.bt);
System.out.println(t.ft);
any parameters. All the objects created using this type of constructors
Eg:
class Student {
int roll_no;
String name;
Student() {
roll_no = 50;
name="ABC";
void display() {
System.out.println("Name is : "+name);
s.display();
class Student {
int roll_no;
String name;
Student(int r, String n) {
roll_no = r;
name=n;
void display() {
System.out.println("Name is : "+name);
s.display();
a new object using an existing object of the same class and initializes
class Rectangle
int length;
int breadth;
Rectangle(int l, int b)
breadth= b;
//copy constructor
Rectangle(Rectangle obj)
length = obj.length;
breadth= obj.breadth;
(r1.length*r1.breadth));
(r1.length*r1.breadth));
13. Define a class student with int id and string name as data members and a method void SetData
( ). Accept and display the data for five students. (summer 2019)
Ans –
import java.io.*;
class student
int id;
String name;
InputStreamReader(System.in));
void SetData()
try
id=Integer.parseInt(br.readLine());
name=br.readLine();
catch(Exception ex)
{}
void display()
student[] arr;
int i;
for(i=0;i<5;i++)
for(i=0;i<5;i++)
arr[i].SetData();
for(i=0;i<5;i++)
arr[i].display();
14. Differentiate between String and String Buffer. (winter 19,Summer 22,Summer 23)
Ans –
Ans –
to lower case.
Syntax: s1.toLowerCase()
System.out.println(s.toLowerCase());
Output: sachin
upper case
Syntax: s1.toUpperCase()
Example:
String s="Sachin";
System.out.println(s.toUpperCase());
Output: SACHIN
3) trim (): Returns a copy of the string, with leading and trailing
whitespace omitted.
Syntax: s1.trim()
Example:
System.out.println(s.trim());
Output:Sachin
Syntax: s1.replace(‘x’,’y’)
Example:
of "Java" to "Kava"
System.out.println(s2);
17. Define a class employee with data members 'empid , name and salary. Accept data for three
objects and display it (winter 22)
Ans –
class employee
{
int empid;
String name;
double salary;
void getdata()
{
18. Write a program to add 2 integer, 2 string and 2 float values is a vector. Remove the element
specified by the user and display the list. (winter 22)
Ans –
import java.io.*;
import java.lang.*;
import java.util.*;
class vector2
{
public static void main(String args[])
{
vector v=new vector();
Integer s1=new Integer(1);
Integer s2=new Integer(2);
String s3=new String("fy");
String s4=new String("sy");
Float s7=new Float(1.1f);
Float s8=new Float(1.2f);
v.addElement(s1);
v.addElement(s2);
v.addElement(s3);
v.addElement(s4);
19. Explain four methods of vector class with example? (Summer 23)
Ans –
The add() is a Java Vector class method which is used to insert the specified element in the given
Vector. There are two different types of Java add() method which can be differentiated depending on
its parameter. These are:
Example:
import java.util.Vector;
vc.add("A");
vc.add("B");
vc.add("C");
vc.add("D");
vc.add("E");
} } }
Output:
--Elements of Vector are--
Alphabet= A
Alphabet= B
Alphabet= C
Alphabet= D
Alphabet= E
The clear() method of Java Vector class is used to remove all of the elements from the vector which
is in use.
Syntax:
Example:
import java.util.Vector;
vc.add("A");
vc.add("B");
vc.add("C");
vc.clear();
Output:
Example:
import java.util.*;
vec.add(1);
vec.add(2);
vec.add(3);
vec.add(4);
Output:
Element at index 1 is = 2
Element at index 3 is = 4
The capacity() method of Java Vector class is used to get the current capacity of the vector which is
in use.
Syntax:
Example :
import java.util.Vector;
vecObject.add(3);
vecObject.add(5);
vecObject.add(2);
vecObject.add(4);
} Output:
Current capacity of Vector is: 5
20. What advantages does TDM have over FDM in a circuit switched network?
Ans –
In TDM, each signal uses all of the bandwidth some of the time, while for FDM, each signal
uses a small portion of the bandwidth all of the time.
TDM uses the entire frequency range but dynamically allocates time, certain jobs might
require less or more time, which TDM can offer but FDM is unable to as it cannot change
the width of the allocated frequency.
TDM provides much better flexibility compared to FDM.
TDM offers efficient utilization of bandwidth
Low interference of signal and minimizes cross talk
Ans –
Ans –
Kevlar strands are placed inside the jacket to strengthen the cable.
Below the Kevlar strands, there is another plastic coating which acts as acushion.
The fiber is at the center of the cable, and it consists of cladding and glass core.
Ans –
Advantages:
3. Many receiver stations can receive signals from same sender station
Disadvantages :
1..Radio waves travel through Lowest portion of atmosphere which can have lot of noise and
interfering signals
2. Radio wave communication through unguided media is an insecure communication. 3.Radio wave
propagation is susceptible to weather effects like rain, thunder and storm etc.
Ans –
Multiplexing is a technique by which different analog and digital streams of transmission can be
simultaneously processed over a shared link. Multiplexing divides the high capacity medium into low
capacity logical medium which is then shared by different streams. Communication is possible over
the air (radio frequency), using a physical media (cable), and light (optical fiber). All mediums are
capable of multiplexing. When multiple senders try to send over a single medium, a device called
Multiplexer divides the physical channel and allocates one to each. On the other end of
communication, a De-multiplexer receives data from a single medium, identifies each, and sends to
different receivers
Frequency Division Multiplexing: When the carrier is frequency, FDM is used. FDM is an analog
technology. FDM divides the spectrum or carrier bandwidth in logical channels and allocates one
user to each channel. Each user can use the channel frequency independently and has exclusive
access of it. All channels are divided in such a way that they do not overlap with each other.
Channels are separated by guard bands. Guard band is a frequency which is not used by either
channel.
Time Division Multiplexing: TDM is applied primarily on digital signals but can be applied on
analog signals as well. In TDM the shared channel is divided among its user by means of time slot.
Each user can transmit data within the provided time slot only. Digital signals are divided in frames,
equivalent to time slot i.e. frame of an optimal size which can be transmitted in given time slot. TDM
works in synchronized mode. Both ends, i.e. Multiplexer and Demultiplexer are timely synchronized
and both switch to next channel simultaneously.
When channel A transmits its frame at one end, the De-multiplexer provides media to channel A on
the other end. As soon as the channel A’s time slot expires, this side switches to channel B. On the
other end, the De-multiplexer
works in a synchronized manner and provides media to channel B. Signals from different channels
travel the path in interleaved manner.
Circuit Establishment: In this phase, a dedicated circuit is established from the source to the
destination through a number of intermediate switching centers. The sender and receiver transmits
communication signals to request and acknowledge establishment of circuits.
Data Transfer: Once the circuit has been established, data and voice are transferred from the source
to the destination. The dedicated connection remains as long as the end parties communicate.
Circuit Disconnection: When data transfer is complete, the connection is relinquished. The
disconnection is initiated by any one of the user. Disconnection involves removal of all intermediate
links from the sender to the receiver.
The diagram represents circuit established between two telephones connected by circuit switched
connection. The blue boxes represent the switching offices and their connection with other switching
offices. The black lines connecting the switching offices represent the permanent link between the
offices.
26. Draw a neat diagram of twisted pair cable and state its types.
Ans –
Ans –
28. State the use of final keyword with respect to inheritance. (Winter 22)
Ans –
Final keyword : The keyword final has three uses. First, it can be used to create the equivalent of a
named constant.( in interface or class we use final as shared constant or constant.)
Other two uses of final apply to inheritance
Using final to Prevent Overriding While method overriding is one of Java’s most powerful features,
To disallow a method from being overridden, specify final as a modifier at the start of its declaration.
Methods declared as final cannot be overridden.
The following fragment illustrates final:
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{ // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Ans –
Syntax:
//implementation
class A
class B extends A
}}
Final variable behaves like class variables and they do not take
Ans –
The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in
the Java interface, not the method body. It is used to achieve abstraction and multiple inheritances
in Java using Interface.
interface {
// by default.
// A simple interface
interface In1 {
void display();
// interface.
System.out.println("Geek");
// Driver Code
t.display();
System.out.println(a);
Output
Geek
10
Ans –
class Animal{
void eat(){System.out.println("eating...");}
void bark(){System.out.println("barking...");}
void meow(){System.out.println("meowing...");}
class TestInheritance3{
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
33. Explain dynamic method dispatch in Java with suitable example. .(Summer 19)6m & 4 m
Ans –
that method is to be executed based upon the type of the object being
(not the type of the reference variable) that determines which version
dispatch:
class A
void m1()
class B extends A
// overriding m1()
void m1(){
class C extends A
// overriding m1()
void m1()
// Driver class
class Dispatch
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
A ref;
ref = a;
ref.m1();
ref = b;
ref.m1();
ref = c;
ref.m1();
Ans –
An exception is a problem that arises during the execution of a program. Java exception handling is
used to handle error conditions in a program systematically by taking the necessary action
Built-in exceptions:
• ClassNotFoundException
• IO Exception: Caused by general I/O failures, such as inability to read from a file.
• OutOfMemoryException: Caused when there’s not enough memory to allocate a new object.
• SecurityException: Caused when an applet tries to perform an action not allowed by the browser’s
security setting.
35. Explain life cycle of thread. (winter 22)(summer 19)(Summer 22)(winter 23)
Ans -
37. Explain exception handling mechanism. w.r.t. try, catch, throw and finally.
Ans –
The Exception Handling in Java is one of the powerful mechanism to handle theruntime
errors so that the normal flow of the application can be maintained. The core advantage of
exception handling is to maintain the normal flow of the application. An exception
normally disrupts the normal flow of the application; that is why we need to handle
exceptions.
Example :
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5; System.out.println(data);
}
//catch won't be executed
catch(NullPointerException e){
. System.out.println(e);
.}
. //executed regardless of exception occurred or not
. finally {
. System.out.println("finally block is always executed");
6 Marks Questions
1. Explain the command line arguments with suitable example (summer 19)
Ans –
Java Command Line Argument: The java command-line argument is an argument i.e. passed at the
time of running the java program.
The arguments passed from the console can be received in the java program and it can be used as an
input. So, it provides a convenient way to check the behaviour of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Command Line Arguments can be used to specify configuration information while launching your
application.
There is no restriction on the number of java command line arguments.
You can specify any number of arguments Information is passed as Strings.
They are captured into the String args of your main method Simple example of command-line
argument in java
In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample {
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);
}}
compile by > javac CommandLineExample.java
run by > java CommandLineExample sonoo
2. Describe the use of any methods of vector class with their syntax.
(Note: Any method other than this but in vector class shall be considered for answer). (summer 19)
Ans –
3. Write a program to create a vector with five elements as (5,15, 25, 35, 45). Insert new element
at 2nd position. Remove 1st and 4th element from vector. (winter 19)
Ans –
import java.util.*;
class VectorDemo
v.addElement(new Integer(5));
v.addElement(new Integer(15));
v.addElement(new Integer(25));
v.addElement(new Integer(35));
v.addElement(new Integer(45));
");
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
v.removeElementAt(0);
v.removeElementAt(3);
for(int i=0;i<v.size();i++)
System.out.println(v.elementAt(i));
}}}
4. Write a program to check whether the string provided by the user is palindrome or not. (winter
22)
Ans –
import java.lang.*;
import java.io.*;
import java.util.*;
class palindrome
{
public static void main(String arg[ ]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String word=br.readLine( );
int len=word.length( )-1;
int l=0;
int flag=1;
int r=len;
while(l<=r)
{
Ans –
When no access modifier is specified for a class, method, or data member – It is said to be having
the default access modifier by default. The data members, classes, or methods that are not
declared using any access modifiers i.e. having default access modifiers are accessible only within
the same package.
package p1;
void display()
System.out.println("Hello World!");
package p1;
class A
System.out.println("GeeksforGeeks");
class B
// of another class
obj.display();
// Class A
public class A
System.out.println("GeeksforGeeks");
package p2;
// Class B is subclass of A
class B extends A
obj.display();
The public access modifier has the widest scope among all other access modifiers.
Classes, methods, or data members that are declared as public are accessible from everywhere in
the program. There is no restriction on the scope of public data members.
public class A
System.out.println("GeeksforGeeks");
package p2 ;
import p1.*;
class B {
obj.display();
}}
6. Write a program to copy all elements of one array into another array(Summer 23)
Ans –
//Initialize array
arr2[i] = arr1[i];
System.out.println();
Output:
12345
12345
Ans –
Switching is a mechanism by which data/information sent from source towards destination which
are not directly connected. Networks have interconnecting devices, which receives data from
directly connected sources, stores data, analyse it and then forwards to the next interconnecting
device closest to the destination.
Circuit switching
Message switching
because:
8. Describe the principles of packet switching and circuit switching techniques with neat diagram.
Ans –
Circuit Switching: When two nodes communicate with each other over a dedicated communication
path, it is called circuit switching. There 'is a need of pre-specified route from which data will travels
and no other data is permitted. In circuit switching, to transfer the data, circuit must be established so
that the data transfer can take place. Circuits can be permanent or temporary. Applications which use
circuit switching may have to go through three phases:
1.Establish a circuit
Circuit switching was designed for voice applications. Telephone is the best suitable example of
circuit switching. Before a user can make a call, a virtual path between callers and called is
established over the network.
It is easier for intermediate networking devices to store small size packets and they do not take much
resource either on carrier path or in the internal memory of switches
Packet switching enhances line efficiency as packets from multiple applications can be multiplexed
over the carrier. The internet uses packet switching technique. Packet switching enables the user to
differentiate data streams based on priorities. Packets are stored and forwarded according to their
priority to provide quality of service.
9. Write a program to create a class 'salary with data members empid', ‘name' and
‘basicsalary'. Write an interface 'Allowance’ which stores rates of calculation for da as 90% of
basic salary, hra as 10% of basic salary and pf as 8.33% of basic salary. Include a method to
calculate net salary and display it. (Winter 22)
Ans –
interface allowance
{
double da=0.9*basicsalary;
double hra=0.1*basicsalary;
double pf=0.0833*basicsalary;
void netSalary();
}
class Salary
{
int empid;
String name;
float basicsalary;
Salary(int i, String n, float b)
{
empid=I;
name=n;
basicsalary =b;
}
void display()
{
System.out.println("Empid of Emplyee="+empid);
System.out.println("Name of Employee="+name);
System.out.println("Basic Salary of Employee="+ basicsalary);
}
}
class net_salary extends salary implements allowance
{
10. Define package. How to create user defined package? Explain with example(Winter
19)(Summer 23 for 4m)
Ans –
Java provides a mechanism for partitioning the class namespace into more manageable parts. This
mechanism is the package. The package is both naming and visibility controlled mechanism. Package
can be created by including package as the first statement in java source code. Any classes declared
within that file will belong to the specified package. Package defines a namespace in which classes
are stored.
package pkg;
eg : package
mypack;
Packages are mirrored by directories. Java uses file system directories to store packages. The class
files of any classes which are declared in a package must be stored in a directory which has same
name as package name. The directory must match with the package name exactly. A hierarchy can
be created by separating package name and sub package name by a period(.) as pkg1.pkg2.pkg3;
which requires a directory structure as pkg1\pkg2\pkg3.
To access package In a Java source file, import statements occur immediately following the package
statement (if it exists) and before any class definitions .
Syntax:
import pkg1[.pkg2].(classname|*);
Example:
package package1;
int l= 5;
int b = 7;
int h = 8;
System.out.println("Volume is:"+(l*b*h));
Source file:
import package1.Box;
class volume
b.display();
Ans –
interface Salary
class Employee
String Name;
int age;
Employee(String n, int b)
Name=n;
age=b;
void Display()
System.out.println("Name of Employee
:"+Name);
double HRA,TA,DA;
super(n,b);
HRA=h;
TA=t;
DA=d;
System.out.println("Basic Salary
:"+Basic_Salary);
void Total_Sal()
Display();
Basic_Sal();
double Total_Sal=Basic_Salary + TA + DA +
HRA;
class EmpDetails
{ Gross_Salary s=new
Gross_Salary("Sachin",20,1000,2000,7000);
12. Write a program to create two threads one thread will print even
no. between 1 to 50 and other will print odd number between 1 to 50
Ans –
import java.lang.*;
class Even extends Thread
{
public void run()
{
try
{
for(int i=2;i<=50;i=i+2)
{
System.out.println("\t Even thread :"+i);
sleep(500);
}
}
catch(InterruptedException e)
{System.out.println("even thread interrupted");
}
}
}
class Odd extends Thread
{
public void run()
{
try
{
for(int i=1;i<50;i=i+2)
{
System.out.println("\t Odd thread :"+i); sleep(500);
}
}
catch(InterruptedException e)
{System.out.println("odd thread interrupted");
}
}
}
class EvenOdd
{
public static void main(String args[])
{
new Even().start();
new Odd().start();
}
}
Ans-
class Ascending extends Thread
{
public void run()
{
for(int i=1; i<=15;i++)
{
System.out.println("Ascending Thread : " + i);
}
}
}
class Descending extends Thread
{
public void run()
{
for(int i=15; i>0;i--) { System.out.println("Descending
Thread : " + i);
}
}
}
public class AscendingDescending Thread
{
public static void main(String[] args)
{
Ascending a=new Ascending();a.start();
Descending d=new Descending();d.start();
}
}
14. Write a program to input name and salary of employee and throw user defined
exception if entered salary is negative.
Ans –
import java.io.*;
class NegativeSalaryException extends Exception
{
public NegativeSalaryException (String str)
{
super(str);
}
}
public class S1
{
public static void main(String[] args) throws IOException
{
15. Define an exception called 'No Match Exception' that is thrown when the
passward accepted is not equal to "MSBTE'. Write the program. (Summer 22) OR
Write a program that throws an exception called “NoMatchException ”when a string is
not equal to “India”(Winter 23) for this refer following program
Ans –
import java.io.*;
class NoMatchException extends Exception
{
NoMatchException(String s)
{
super(s);
}
}
class test1
{
public static void main(String args[]) throws IOException
{
BufferedReader br= new BufferedReader(new InputStreamReader(System.in) );
System.out.println("Enter a word:");
String str= br.readLine();
try
{ if (str.compareTo("MSBTE")!=0) // can be done with equals()
throw new NoMatchException("Strings are not equal");
else
System.out.println("Strings are equal");
}
catch(NoMatchException e)
{
System.out.println(e.getMessage());
}}}
Ans-
Thread Priority:
In java each thread is assigned a priority which affects the order in which it is scheduled for
running. Threads of same priority are given equal treatment by the java scheduler.
Default priority values as follows
The thread class defines several priority constants as: -
MIN_PRIORITY =1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
Thread priorities can take value from 1-10.
getPriority(): The java.lang.Thread.getPriority() method returns the priority of thegiven
thread.
setPriority(int newPriority): The java.lang.Thread.setPriority() method updates or assign
the priority of the thread to newPriority. The method throws IllegalArgumentException if
the value newPriority goes out of the range, which is1 (minimum) to 10 (maximum).
import java.lang.*;
public class ThreadPriorityExample extends Thread
{
public void run()
{
System.out.println("Inside the run() method");
}
public static void main(String argvs[])
{
ThreadPriorityExample th1 = new ThreadPriorityExample(); ThreadPriorityExample th2 =
new ThreadPriorityExample(); ThreadPriorityExample th3 = new ThreadPriorityExample();
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());th1.setPriority(6);
th2.setPriority(3);
th3.setPriority(9);
System.out.println("Priority of the thread th1 is : " + th1.getPriority());
System.out.println("Priority of the thread th2 is : " + th2.getPriority());
System.out.println("Priority of the thread th3 is : " + th3.getPriority());
System.out.println("Currently Executing The Thread : " + Thread.currentThread().gtName());
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPrority();
Thread.currentThread().setPriority(10);
System.out.println("Priority of the main thread is : " +
Thread.currentThread().getPiority());
}
17. Write a Java program in which thread A will display the even numbers
between 1 to 50 and thread B will display the odd numbers between 1 to 50.After 3
iterations thread A should go to sleep for 500 ms.
evenThread.start();
oddThread.start();
}
}
Ans –
i) The most common errors can be broadly classified as follows:
1. Run Time Error:
Run Time errors occur or we can say, are detected during the execution of the program.
// Main class
class ThreadDemo extends Thread {
// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in main()
public void run()
{
// Print statement System.out.println("Inside run
method");
}
// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "
// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "
+ t2.getPriority());
// Thread 3
System.out.println("t3 thread priority : "
+ t3.getPriority());
// 2
System.out.println("t1 thread priority : "
+ t1.getPriority());
// 5
System.out.println("t2 thread priority : "
+ t2.getPriority());
// 8
System.out.println("t3 thread priority : "
+ t3.getPriority());
// Main thread
The students will be able to write interactive applets and make use of graphics in
programming.
They will also learn to change the background and the foreground color and to use the
different fonts.
Contents:
5.1 Introduction to applets Applet, Applet life cycle (skeleton), Applet tag, Adding Applet
To HTML file, passing parameter to applet, embedding <applet>tags in java code, adding
controls to applets.
5.2 Graphics Programming Graphics classes, lines, rectangles, ellipse, circle, arcs,
polygons, color & fonts, setColor(), getColor(), setForeGround(), setBackGround(), font
class, variable defined by font class: name, pointSize, size, style, font methods: getFamily(),
getFont(), getFontname(), getSize(), getStyle(), getAllFonts() &
getavailablefontfamilyname() of the graphics environment class.
Applet Basics-
Basically, an applet is dynamic and interactive java program that inside the web
page or applets are small java programs that are primarily used in internet computing. The
java application programs run on command prompt using java interpreter whereas
the java applets can be transported over the internet form one computer to another and run
using the appletviewer or any web browser that supports java.
An applet is like application program which can perform arithmetic
operations, display graphics, play sounds accept user input, create animation and
play interactive games. To run an applet, it must be included in HTML tags for web page.
Web browser is a program to view web page.
Every applet is implemented by creating sub class of Applet class.
Following diagram shows the inheritance hierarchy of Applet class.
java.lang.Object
java.awt.Component
java.awt.Container
java.awt.Panel
java.applet.Applet
Fig. Chain of classes inherited by Applet class in java
5.1.1 Differentiate between applet and application (4 points). [W-14, S-15, W-15 ]
Applet Application
Applet does not use main() method for Application use main() method for initiating
initiating execution of code execution of code
Applet cannot run independently Application can run independently
Applet cannot read from or write to files in Application can read from or write to files in
local computer local computer
Applet cannot communicate with other Application can communicate with other
servers on network servers on network
Applet cannot run any program from local Application can run any program from local
computer. computer.
Applet are restricted from using libraries Application are not restricted from using
from other language such as C or C++ libraries from other language
Applet enters the running state when the system calls the start() method
of Applet class. This occurs automatically after the applet is initialized. start() can also
be called if the applet is already in idle state. start() may be called more than once.
start() method may be overridden to create a thread to control the applet.
APPLET Tag:
The APPLET tag is used to start an applet from both an HTML document and
from an applet viewer.
<APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]>
[< PARAM NAME = AttributeName1 VALUE = AttributeValue>]
[<PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
</APPLET>
CODE is a required attribute that give the name of the file containing your applet‟s
compiled class file which will be run by web browser or appletviewer.
ALT: Alternate Text. The ALT tag is an optional attribute used to specify a short text
message that should be displayed if the browser cannot run java applets.
NAME is an optional attribute used to specifies a name for the applet instance.
WIDTH AND HEIGHT are required attributes that give the size(in pixels) of the
applet display area.
VSPACE AND HSPACE attributes are optional, VSPACE specifies the space, in
pixels, about and below the applet. HSPACE VSPACE specifies the space, in
pixels, on each side of the applet
PARAM NAME AND VALUE: The PARAM tag allows you to specifies applet-
specific arguments in an HTML page applets access there attributes with the
get Parameter()method.
Example
import java.awt.*;
import java.applet.*;
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
The Applet tag in HTML document allows passing the arguments using param tag.
The syntax of <PARAM…> tag
import java.awt.*;
import java.applet.*;
<HTML>
<Applet code = ―hellouser.class‖ width = 400 height = 400>
<PARAM NAME = "username" VALUE = abc>
</Applet>
</HTML>
Graphics can be drawn with the help of java. java applets are written to
draw lines, figures of different shapes, images and text in different styles even
with the colours in display.
Every applet has its own area of the screen known as canvas, where it creates the
display in the area specified the size of applet‘s space is decided by the attributes of
<APPLET...> tag.
A java applet draws graphical image inside its space using the coordinate system
shown in following fig., which shows java‘s coordinate system has the origin (0, 0) in
the upper-left corner, positive x values are to be right, and positive y values are to the
bottom. The values of coordinates x and y are in pixels.
X
(0, 0)
1. Write a java applet code and save it with as a class name declared in a program by
extension as a .java.
e.g. from above java code file we can save as a Welcome.java
3. After successfully compiling java file, it will create the .class file, e.g
Welcome.class. then we have to write applet code to add this class into applet.
4. Applet code
<html>
<Applet code= ― Welcome.class‖ width= 500 height=500>
</applet>
</html>
5. Save this file with Welcome.html in ‗bin‘ library folder.
The Graphics class of java includes methods for drawing different types
of shapes, from simple lines to polygons to text in a variety of fonts.
Method Description
clearRect( ) Erases a rectangular area of the canvas
copyArea( ) Copies a rectangular area of the canvas to another area
drawArc( ) Draws a hollow arc.
drawLine( ) Draws a straight line
drawOval( ) Draws a hollow oval
drawPolygon( ) Draws a hollow polygon
drawRect( ) Draws a hollow rectangle
drawRoundRect( ) Draws a hollow rectangle with rounded corners.
drawstring( ) Displays a text string
fillArc( ) Draws a filled arc
fillOval( ) Draws a filled arc
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle
fillRoundRect( ) Draws filled rectangle with rounded corners
getColor( ) Retrieves the current drawing color
getFont( ) Retrieves the currently used font
getFontMetrics( ) Retrieves information about the current font.
setColor( ) Sets the drawing color
setFont( ) Seta fonts.
Displaying String:
drawString() method is used to display the string in an applet window
Syntax:
void drawString(String message, int x, int y);
where message is the string to be displayed beginning at x, y
Example:
g.drawString(―WELCOME‖, 10, 10);
5.2.3.1. drawLine( )
The drawLine ( ) method is used to draw line which takes two pair
of
coordinates (x1,y1) and (x2, y2) as arguments and draws a line between
them. The graphics object g is passed to paint( ) method.
The syntax is
g.drawLine(x1,y1,x2,y2);
e.g. g.drawLine(20,20,80,80);
Syntax: void drawRect(int top, int left, int width, int height)
This method takes four arguments, the first two represents the x and y
co- ordinates of the top left corner of the rectangle and the remaining two represent the
width and height of rectangle.
Example: g.drawRect(10,10,60,50);
Q. Design an Applet program which displays a rectangle filled with red color
and message as “Hello Third year Students” in blue color. [S-16]
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.blue);
g.drawString("Hello Third year Students",70,100);
}
}
Syntax: void drawOval( int top, int left, int width, int height)
Example: g.drawOval(10,10,50,50);
Syntax- void fillOval(int top, int left, int width, int height):
Example g.fillOval(10,10,50,50);
Q. Write a simple applet program which display three concentric circle. [S-16]
Program-
import java.awt.*;
import java.applet.*;
g.drawOval(100,100,190,190);
g.drawOval(115,115,160,160);
g.drawOval(130,130,130,130);
}
}
(OR)
HTML Source:
<html> <applet code=‖CircleDemo.class‖ height=300 width=200>
</applet>
</html>
Program-
import java.awt.*;
import java.applet.*;
g.setColor(Color.green);
g.fillOval(50,150,100,100);
g.setColor(Color.yellow);
g.fillOval(50,250,100,100);
}
}
Output
Example:
g.drawArc(10, 10, 30, 40, 40, 90);
g.drawPolygon(x, y, n);
Q. Write the syntax and example for each of following graphics methods:
import java.applet.*;
import java.awt.*;
/*
<applet code = DrawGraphics.class height = 500 width = 400>
</applet>*/
void setBackground(Color.newColor)
where newColor specifies the new color. The class color defines the constant
for specific color listed below.
setForeground (Color.yellow);
The following methods are used to retrieve the current background and foreground
color.
Color getBackground( )
Color getForeground( )
A font determines look of the text when it is painted. Font is used while painting text
on a graphics context & is a property of AWT component.
Variable Meaning
String name Name of the font
float pointSize Size of the font in points
int size Size of the font in point
int style Font style
The Font class states fonts, which are used to render text in a visible way.
It is used to set or retrieve the screen font.
To select a new font, you must first construct a Font object that describes that
font. Font constructor has this general form:
fontName specifies the name of the desired font. The name can be specified
using either the logical or face name.
All Java environments will support the following fonts:
Dialog, DialogInput, Sans Serif, Serif, Monospaced, and Symbol. Dialog is the
font used by once system‟s dialog boxes.
Dialog is also the default if you don‟t explicitly set a font. You can also use
any other fonts supported by particular environment, but be careful—these other fonts
may not be universally available.
The style of the font is specified by fontStyle. It may consist of one or more of
these three constants:
Font.PLAIN, Font.BOLD, and Font.ITALIC. To combine styles, OR
them together.
For example,
Font.BOLD | Font.ITALIC specifies a bold, italics style.
The size, in points, of the font is specified by pointSize.
To use a font that you have created, you must select it using setFont( ), which
is defined by Component.
It has this general form:
void setFont(Font fontObj)
Here, fontObj is the object that contains the desired font
Q. Describe any three methods of font class with their syntax and example
of each. [W-14, S-15 ]
Sr.
Methods Description
No
1 static Font decode(String str) Returns a font given its name.
boolean equals(Object Returns true if the invoking object contains the
2 same font as that specified by FontObj.Otherwise,
FontObj) :
it returns false.
3 String toString( ) Returns the string equivalent of the invoking font.
Returns the name of the font family to which the
4 String getFamily( )
invoking font belongs.
static Font getFont(String Returns the font associated with the system
5 property specified by property. null is returned if
property)
property does not exist.
Returns the font associated with the System
static Font getFont(String property specified by property.
6 property,Font defaultFont)
The font specified by defaultFont is returned if
property does not exist.
7 String getFontName( ) Returns the face name of the invoking font.
8 String getName( ) Returns the logical name of the invoking font.
Example:-
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.applet.*;
Q. Write method to set font of a text and describe its parameters. [S-16]
The AWT supports multiple type fonts emerged from the domain of traditional
type setting to become an important part of computer-generated documents and
displays. The AWT provides flexibility by abstracting font-manipulation
operations and allowing for dynamic selection of fonts.
Fonts have a family name, a logical font name, and a face name. The family
name is the general name of the font, such as Courier. The logical name specifies a
category of font, such as Monospaced. The face name specifies a specific font, such as
Courier Italic To select a new font, you must first construct a Font object that
describes that font.
One Font constructor has this general form:
Font(String fontName, intfontStyle, intpointSize)
To use a font that you have created, you must select it using setFont( ), which
is defined by Component.
It has this general form:
void setFont(Font fontObj)
Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class SampleFonts extends Applet
{
int next = 0;
Font f;
String msg;
Syntax:
public abstract String[ ] getAvailableFontFamilyNames(Locale 1)
Parameters:
l - a Locale object that represents a particular geographical, political, or
cultural region. Specifying null is equivalent to specifying Locale.getDefault().
Or
String[ ] getAvailableFontFamilyNames( )
It will return an array of strings that contains the names of the available font families
Important Questions:-
4 Marks Questions:-
1) Write syntax and example of 1) drawString ( ) 2) drawRect ( ) ; 3) drawOval ( )
4) drawArc ( ).
2) Describe following states of applet life cycle : a) Initialization state. b) Running state.
c) Display state
3) State the use of font class. Describe any three methods of font class with their syntax
and example of each.
4) Differentiate applet and application with any four points.
5) State syntax and explain it with parameters for : i)drawRect ( ) ii) drawOral ( )
6) Design an Applet program which displays a rectangle filled with red color and
message as ―Hello Third year Students‖ in blue color.
7) Describe applet life cycle with suitable diagram.
8) Differentiate between applet and application (any 4 points).
9) Write a program to design an applet to display three circles filled with three different
colors on screen.
10) Explain all attributes available in < applet > tag.
1. What are stream classes ? List any two input stream classes from character stream
[S-15, S-16]
Definition:
The java. IO package contain a large number of stream classes that provide
capabilities for processing all types of data. These classes may be categorized into two
groups based on the data type on which they operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on
characters.
Character Stream Class can be used to read and write 16-bit Unicode
characters. There are two kinds of character stream classes, namely, reader stream classes
and writer stream classes
2. What are streams ? Write any two methods of character stream classes. [W-15]
Java programs perform I/O through streams. A stream is an abstraction that either
produces or consumes information (i.e it takes the input or gives the output). A stream is
linked to a physical device by the Java I/O system.
All streams behave in the same manner, even if the actual physical devices
to which they are linked differ. Thus, the same I/O classes and methods can be applied to
any type of device.
Java 2 defines two types of streams: byte and character.
Byte streams provide a convenient means for handling input and output of bytes.
Byte streams are used, for example, when reading or writing binary data.
Character streams provide a convenient means for handling input and output
of characters.
They use Unicode and, therefore, can be internationalized. Also, in some
cases, character streams are more efficient than byte streams.
Writer Class
Writer is an abstract class that defines streaming character output. All of the methods
in this class return a void value and throw an IOException in the case of error
2) abstract void flush( ) : Finalizes the output state so that any buffers are cleared. That
is, it flushes the output buffers.
3) void write(intch): Writes a single character to the invoking output stream. Note that the
parameter is an int, which allows you to call write with expressions without having to cast
them back to char.
5) abstract void write(char buffer[ ],int offset, int numChars) :- Writes a subrange of
numChars characters from the array buffer, beginning at buffer[offset] to the invoking output
stream.
7) void write(String str, int offset,int numChars): Writes a sub range of numChars
characters from the array str, beginning at the specified offset.
2. public int read(char[ ] cbuf, int offset, int length) throws IOException -
Reads characters into a portion of an array.
3. public void close()throws IOException - Closes the stream and releases any
system resources associated with it. Once the stream has been closed, further
read(), ready(), mark(), reset(), or skip() invocations will throw an IOException.
Closing a previously closed stream has no effect
6. public void reset()throws IOException - Resets the stream. If the stream has been
marked, then attempt to reposition it at the mark. If the stream has not
been marked, then attempt to reset it in some way appropriate to the particular
stream, for example by repositioning it to its starting point. Not all character-input
streams support the reset() operation, and some support reset() without supporting
mark().
4. Write any two methods of File and FileInputStream class each.[S-15, W-15]
1. int available( )- Returns the number of bytes of input currently available for
reading.
2. void close( )- Closes the input source. Further read attempts will generate an
IOException.
3. void mark(int numBytes) -Places a mark at the current point in the inputstream
that will remain valid until numBytes bytes are read.
4. boolean markSupported( ) -Returns true if mark( )/reset( ) are supported by the
invoking stream.
5. int read( )- Returns an integer representation of the next available byte of input. –1
is returned when the end of the file is encountered.
6. int read(byte buffer[ ])- Attempts to read up to buffer.length bytes into buffer and
returns the actual number of bytes that were successfully read. –1 is returned when the end of
the file is encountered.
Serialization is the process of writing the state of an object to a byte stream. This is
useful when you want to save the state of your program to a persistent storage area, such
as a file. At a later time, you may restore these objects by using the process of
deserialization.
Example:
Assume that an object to be serialized has references to other objects, which,
inturn, have references to still more objects. This set of objects and the
relationships among them form a directed graph. There may also be circular
references within this object graph. That is, object X may contain a reference to
object Y, and object Y may contain a reference back to object X. Objects may also
contain references to themselves. The object serialization and deserialization facilities
have been designed to work correctly in these scenarios. If you attempt to serialize an
object at the top of an object graph, all of the other referenced objects are recursively
located and serialized. Similarly, during the process of deserialization, all of these objects
and their references are correctly restored.
import java.io.*;
class CopyData
{
public static void main(String args[ ])
{
//Declare input and output file stream
byte byteRead;
try
{
// connect fis to in.dat
fis=new FileInputSream(―in.dat‖);
// connect fos to out.dat
fos= new FileOutputStream(―out.dat‖);
//reading bytes from in.dat and write to out.dat
do
{
byteRead =(byte)fis.read( );
fos.write(byteRead);
}
while(byteRead != -1);
}
Catch(FileNotFoundException e)
{
System.out.println(―file not found‖);
}
Catch(IOException e)
{
System.out.pritln(e.getMessage( ));
}
fis.close( );
fos.close( );
}
Catch(IOException e)
{ }
}
}
}
7. What is use of ArrayList Class ? State any three methods with their use from
ArrayList.[W-15, S-16]
1. void add(int index, Object element) Inserts the specified element at the specified
position index in this list. Throws IndexOutOfBoundsException if the specified index
is is out of range (index < 0 || index >size()).
2. boolean add(Object o) Appends the specified element to the end of this list.
9. Object get(int index) Returns the element at the specified position in this
list. Throws IndexOutOfBoundsException if the specified index is is out of range
(index <
0 || index >= size()).
10. intindexOf(Object o) Returns the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
11. intlastIndexOf(Object o) Returns the index in this list of the last occurrence of
the specified element, or -1 if the list does not contain this element.
12. Object remove(int index) Removes the element at the specified position in this
list. Throws IndexOutOfBoundsException if index out of range (index < 0 || index >=
size()).
14. Object set(int index, Object element) Replaces the element at the
specified position in this list with the specified element. Throws
IndexOutOfBoundsException if the specified index is is out of range (index < 0 ||
index >= size()).
16. Object[ ] toArray() Returns an array containing all of the elements in this list in
the correct order. Throws NullPointerException if the specified array is null.
18. void trimToSize() Trims the capacity of this ArrayList instance to be the
list's current size.
ii. getDate()
Syntax:
public int getDate()
Returns the day of the month. This method assigns days with the values of
1 to 31.
1. setTime():
2. getDay()
int getDay():
Returns the day of the week represented by this date.
The returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday, 4 =
Thursday, 5 = Friday, 6 = Saturday) represents the day of the week that contains or
begins with the instant in time represented by this Date object, as interpreted in the
local time zone.
2) max() :
Syntax: static int max(int a, int b)
Use: This method returns the greater of two int values.
3) sqrt()
Syntax: static double sqrt(double a)
Use : This method returns the correctly rounded positive square root of a double
4) pow() :
Syntax: static double pow(double a, double b)
Use : This method returns the value of the first argument raised to the power of the
second argument.
5) exp()
Syntax: static double exp(double a)
Use : This method returns Euler's number e raised to the power of a double value.
6) round() :
Syntax: static int round(float a)
Use : This method returns the closest int to the argument.
7) abs()
Syntax: static int abs(int a)
Use : This method returns the absolute value of an int value.
import java.util.*;
public class SetDemo
{
public static void main(String args[])
{
int count[] = {34, 22,10,60,30,22};
Set<Integer> set = new HashSet<Integer>();
try{
for(int i = 0; i<5; i++){
set.add(count[i]);
}
System.out.println(set);
TreeSet sortedSet = new TreeSet<Integer>(set);
System.out.println("The sorted list is:");
System.out.println(sortedSet);
System.out.println("The First element of the set is: "+ (Integer)sortedSet.first());
System.out.println("The last element of the set is: "+ (Integer)sortedSet.last());
}
catch(Exception e){}
}
}
12. State syntax and describe any two methods of map class.[S-16]
The Map Classes Several classes provide implementations of the map interfaces. A
map is an object that stores associations between keys and values, or key/value pairs.
Given a key, you can find its value. Both keys and values are objects. The keys must be
unique, but the values may be duplicated. Some maps can accept a null key and
null values, others cannot.
Methods:
void clear // removes all of the mapping from map
booleancontainsKey(Object key) //Returns true if this map contains a mapping for the
specified key.
Boolean conainsValue(Object value)// Returns true if this map maps one or more keys to
the specified value
Boolean equals(Object o) //Compares the specified object with this map for equality