K Scheme Java IMP Questions by VJTech Academy
K Scheme Java IMP Questions by VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 1
VJTech Academy
1. Write a Java program to find out the even numbers from 1 to 100 using for loop.
class FindEvenNo
{
public static void main(String args[])
{
int i;
System.out.println("Even Number between 1 to 100:");
for(i=1;i<=100;i++)
{
if(i%2==0)
{
System.out.println(i);
}
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 2
VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 3
VJTech Academy
3) Object Oriented:
--------------------
- Java is true object-oriented language.
- Almost everything in java is an object.
- All program code and data reside within objects and classes.
- Java is a collection of rich set of predefined classes and packages, that we can use in our programs
by inheritance.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 4
VJTech Academy
8. Write the difference between vectors and arrays. (Any four points)
9. Explain exception handling mechanism. w.r.t. try, catch, throw and finally.
Exception may or may not be occur in program.
An Exception is an unwanted event that interrupts the normal flow of the program.
If an exception occurs, which has not been handled by programmer then program execution
gets terminated and a system generated error message is shown to the user.
By using Exception handling mechanism, we handle an Exception and then print a user-friendly
warning message to user.
The basic idea of exception handling mechanism is to find the exception, Throws the exception,
Catch the exception and handle the exception.
We use five keywords for exception handling i.e. try, catch, finally, throw, throws.
o try : try block contain those statements which may cause an exception.
o catch : catch block contain statements which handle the exception.
o finally : finally block always executed
o throw : if we wants to throw the exception manually then we use throw keyword.
o throws : we can list our multiple exceptions class which can occurs in method.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 5
VJTech Academy
Program:
class ExceptionDemo
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println("Value of c="+c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero exception occurred");
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 6
VJTech Academy
public:
-------
- Any variables and methods declared as public, it can be accessible everywhere in the class, outside
the class, outside the package, etc.
private:
--------
- Those members are declared as private, it can accessible within the class in which they are
declared.
- It cannot be inherited in its subclass.
protected:
----------
- Those members are declared as protected, it can accessible in same class and its immediate sub-
class.
Friendly Access:
---------------
- In the situation where no access modifier is specified then by default all members considered as
friendly access level.
- There is basic difference between public and friendly access is that public members accessible
anywhere but friendly access member available in same package not outside the package.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 7
VJTech Academy
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
1. Newborn state:
- When a thread object is created, the thread is born then called as thread is in Newborn state.
- A new thread begins its life cycle in this state.
- When thread is in Newborn state then you can pass to the Running state by invoking start()
- method or kill it by using stop() method.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 8
VJTech Academy
2. Runnable state:
3. Running state:
- The Running state means that the processor has given it’s time to thread for their execution
- When thread is executing, its state is changed to Running.
- A thread can change state to Runnable, Dead or Blocked from running state depends on time
slicing, thread completion of run() method or waiting for some resources.
4. Blocked state:
- A thread can be temporarily suspended or blocked from entering into runnable or running state.
- Thread can be blocked due to waiting for some resources to available.
- Thread can be blocked by using following thread methods:
I. suspended()
II. wait()
III. sleep()
- Following are the methods used to entering thread into Runnable state from Blocked state.
5. Dead state:
- The thread will move to the dead state after completion of its execution. It means thread is in
terminated or dead state when its run() method exits.
- Also Thread can be explicitly moved to the dead state by invoking stop() method.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 9
VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 10
VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 11
VJTech Academy
13. 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
500ms.
class ThreadA extends Thread
{
static int count=0;
public void run()
{
for(int i=1;i<=50;i++)
{
if(i%2==0)
{
System.out.println("Even Number="+i);
}
count++;
if(count==3)
{
try
{
sleep(500);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class ThreadB extends Thread
{
public void run()
{
for(int i=1;i<=50;i++)
{
if(i%2!=0)
{
System.out.println("Odd Number="+i);
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 12
VJTech Academy
}
}
class MainThread
{
public static void main(String args[])
{
ThreadA t1=new ThreadA();
ThreadB t2=new ThreadB();
t1.start();
t2.start();
}
}
14. What is constructor? List types of constructors. Explain parameterized constructor with suitable
example.
- write constructor explanation
- list types of constructors
class Addition
{
int a,b;
Addition(int x,int y)
{
a=x;
b=y;
}
void display()
{
System.out.println("Addition="+(a+b));
}
public static void main(String args[])
{
Addition a1=new Addition(100,200);
a1.display();
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 13
VJTech Academy
15. Explain the difference between string class and string buffer class. Explain any four methods of
string class.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 14
VJTech Academy
16. Write a java program to sort a 1-d array in ascending order using bubble-sort.
import java.util.*;
class SortArray
{
public static void main(String args[])
{
int a[]=new int[10];
int n,i,j,temp;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Size of Array:");
n=sc.nextInt();
System.out.println("Enter Array Elements:");
for(i=0;i<n;i++)
{
a[i]=sc.nextInt();
}
//sorting logic
for(i=1;i<n;i++)
{
for(j=0;j<n-i;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
System.out.println("Sorted Array elements:");
for(i=0;i<n;i++)
{
System.out.println(a[i]);
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 15
VJTech Academy
17. Explain switch case and conditional operator in java with suitable example. 6 Marks
Switch case:
- The switch expression is evaluated once.
- The value of the expression is compared with the values of each case.
- If there is a match, the associated block of code is executed.
- The break and default keywords are optional
- switch, case, break and default four keywords used.
- Syntax:
switch(expression/value)
{
case value-1: //block of statements
break;
case value-2: //block of statements
break;
case value-N: //block of statements
break;
default: //block of statements
}
- Example:
class SwitchCaseDemo
{
Public static void main(String args[])
{
int no=2;
switch(no)
{
case 1: System.out.println(“Number is ONE”);
break;
case 2: System.out.println(“Number is TWO”);
break;
case 3: System.out.println(“Number is THREE”);
break;
default: System.out.println(“Invalid input”);
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 16
VJTech Academy
conditional operator
- Conditional operator is called as Ternary operator.
- The symbol (?:) is used for conditional operator.
- Syntax:
Condition? Expression1: Expression2;
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 17
VJTech Academy
18. Explain single and multilevel inheritance with proper example 6 Marks
1) Single Inheritance:
----------------------
- This is one of the types of inheritance.
- To create new class from only one base class is known as single inheritance.
- Syntax:
class DerivedClassName extends BaseClassName
{
//body of Derived Class
}
- Program:
//Single Inheritance
import java.util.*;
class Student
{
int rollno;
String name;
void get_stud_info()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Roll No:");
rollno=sc.nextInt();
System.out.println("Enter Student Name:");
name=sc.next();
}
void disp_stud_info()
{
System.out.println("Student ROll No:"+rollno);
System.out.println("Student Name:"+name);
}
}
class Test extends Student
{
int marks1,marks2;
void get_stud_marks()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Test-1 Marks:");
marks1=sc.nextInt();
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 18
VJTech Academy
2) Multi-level Inheritance:
---------------------------------
- The mechanism of deriving the class from another derived class is known as multi-level inheritance.
- To create new class from another derived class is known as multi-level inheritance.
- It is one of the types of inheritance.
- Syntax:
class BaseClass1
{
//body of BaseClass1 Class
}
class DerivedClass1 extends BaseClass1
{
//body of DerivedClass1
}
class DerivedClass2 extends DerivedClass1
{
//body of DerivedClass2
}
-Example
//Multi-level Inheritance
import java.util.*;
class Student
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 19
VJTech Academy
{
int rollno;
String name;
void get_stud_info()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Roll No:");
rollno=sc.nextInt();
System.out.println("Enter Student Name:");
name=sc.next();
}
void disp_stud_info()
{
System.out.println("Student ROll No:"+rollno);
System.out.println("Student Name:"+name);
}
}
class Test extends Student
{
int marks1,marks2;
void get_stud_marks()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student Test-1 Marks:");
marks1=sc.nextInt();
System.out.println("Enter Student Test-2 Marks:");
marks2=sc.nextInt();
}
void disp_stud_marks()
{
System.out.println("Test-1 Marks:"+marks1);
System.out.println("Test-2 Marks:"+marks2);
}
}
class Result extends Test
{
int total_marks;
void get_total_marks()
{
total_marks=marks1+marks2;
}
void disp_total_marks()
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 20
VJTech Academy
{
System.out.println("Total Marks:"+total_marks);
}
}
class MultilevelInheritanceDemo
{
public static void main(String args[])
{
Result t1=new Result();
t1.get_stud_info();
t1.get_stud_marks();
t1.get_total_marks();
System.out.println("*******STUDENT INFORMATION SYSTEM********");
t1.disp_stud_info();
t1.disp_stud_marks();
t1.disp_total_marks();
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 21
VJTech Academy
2) Classes:
- It is a collection of similar types of objects.
- Class is a collection of data and functions, functions operate on data.
- You may create objects from the class.
- When you define the class then memory will not be allocated for the members.
- Class shows data abstraction and data encapsulation features.
- Example: Fruit mango
- In above example, mango is an object which is created from class Fruit.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 22
VJTech Academy
24. Define a class circle having data members Pi and radius. Initialize and display values of data
members also calculate area of circle and display it.
import java.util.*;
class Circle
{
float radius;
final static float PI=3.14f;
void getdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter radius of circle:");
radius=sc.nextFloat();
}
void putdata()
{
System.out.println("Radius of circle="+radius);
System.out.println("Value of PI="+PI);
System.out.println("Area of circle="+(PI*radius*radius));
}
public static void main(String args[])
{
Circle c1=new Circle();
c1.getdata();
c1.putdata();
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 23
VJTech Academy
class ExceptionDemo
{
public static void main(String args[])
{
int a=10,b=0,c;
try
{
c=a/b;
System.out.println("Value of c="+c);
}
catch(ArithmeticException e)
{
System.out.println("Divide by zero exception occurred");
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 24
VJTech Academy
27. Define type casting. Explain its types with syntax and example
Type Casting:
- The conversion of one data type value to another data type is knows as Type Casting.
- There are two types of data type conversion/Type Casting.
I) Implicit Type Casting
- The type casting which is done by the system is known as implicit type casting.
- Example:
int a=10;
float b;
b=a; //implicit type casting
b=10.000000
II) Explicit Type Casting
- The type casting which is done by the programmer is known as explicit type casting.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 25
VJTech Academy
- Example:
int a=10;
float b;
b=(float) a; //Explicit type casting
b=10.000000
28. Write a program to create vector with five elements as (5, 15, 25, 35, 45). Insert new element at
2nd position. Remove 1st and 4th element from vector.
import java.util.*;
class VectorDemo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Vector v1=new Vector();
v1.addElement(new Integer(5));
v1.addElement(new Integer(15));
v1.addElement(new Integer(25));
v1.addElement(new Integer(35));
v1.addElement(new Integer(45));
System.out.println("Enter element for insertion:");
int x=sc.nextInt();
v1.insertElementAt(x,2);
v1.removeElementAt(1);
v1.removeElementAt(4);
System.out.println("Vector Elements:"+v1);
}
}
OUTPUT
Enter element for insertion:
120
Vector Elements:[5, 120, 25, 35]
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 26
VJTech Academy
29. 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
}
}
class ThreadB extends Thread
{
public void run()
{
for(int i=1;i<=50;i++)
{
if(i%2!=0)
{
System.out.println("Odd Number="+i);
}
}
}
}
class MainThread
{
public static void main(String args[])
{
ThreadA t1=new ThreadA();
ThreadB t2=new ThreadB();
t1.start();
t2.start();
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 27
VJTech Academy
//Note: In this program, I assume 5%TA, 10% DA and 15% HRA of basic salary.
import java.util.*;
interface Salary
{
int Basic_Salary=1000;
void Basic_sal();
}
class Employee
{
String name;
int age;
void getdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Employee Name:");
name=sc.next();
System.out.println("Enter Employee Age:");
age=sc.nextInt();
}
void display()
{
System.out.println("Employee Name:"+name);
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 28
VJTech Academy
System.out.println("Employee Age:"+age);
}
}
class Gross_Salary extends Employee implements Salary
{
int TA,DA,HRA;
public void Basic_sal()
{
TA=(Basic_Salary*5)/100;
DA=(Basic_Salary*10)/100;
HRA=(Basic_Salary*15)/100;
}
void Total_Sal()
{
int total=(Basic_Salary+TA+DA+HRA);
System.out.println("Basic Salary:"+Basic_Salary);
System.out.println("TA:"+TA);
System.out.println("DA:"+DA);
System.out.println("HRA:"+HRA);
System.out.println("Total Salary:"+total);
}
public static void main(String args[])
{
Gross_Salary g1=new Gross_Salary();
g1.getdata();
g1.Basic_sal();
g1.display();
g1.Total_Sal();
}
}
OUTPUT
Enter Employee Name:
James
Enter Employee Age:
54
Employee Name:James
Employee Age:54
Basic Salary:1000
TA:50
DA:100
HRA:150
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 29
VJTech Academy
Total Salary:1300
33. Name the wrapper class methods for the following: (i) To convert string objects to primitive int.
(ii) To convert primitive int to string objects.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 30
VJTech Academy
- Single Inheritance
- Multilevel Inheritance
- Multiple Inheritance
- Hybrid Inheritance
- Hierarchical Inheritance
try
{
//statements that may cause an exception
}
catch(ExceptionClassName object)
{
//statements that handle the exception
}
finally
{
//statements that always executed
}
36. Explain the concept of platform independence and portability with respect to Java language.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 31
VJTech Academy
- Java program can be easily moved from one computer to another computer, anywhere and
anytime.
- It means, if we develop Java code on Windows machine then you can easily run that code on other
operating systems like Linux, Unix, etc.
- To move java code from one machine to another machine is known as portability.
- Following diagram will give more information about this feature.
1) Default constructor:
-----------------------
- When constructor does not take any parameters then it is called as default constructor.
- Syntax:
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 32
VJTech Academy
class ClassName
{
ClassName()
{
//body of constructor.
}
}
2) Parameterized constructor:
-----------------------
- When constructor takes any parameters then it is called as Parameterized constructor.
- Syntax:
class ClassName
{
ClassName(parameter_list)
{
//body of constructor.
}
}
2) Copy constructor:
--------------------
- To initialize data members of the object, we are passing another object as argument is called as
copy constructor.
- When constructor takes reference of its class as parameter then it is called as copy constructor.
- Syntax:
class ClassName
{
ClassName(ClassName ObjectName)
{
//body of constructor.
}
}
- Example:
class Item
{
int x;
Item()
{
x=100;
}
Item(Item m)
{
x=m.x;
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 33
VJTech Academy
}
void display()
{
System.out.println("Value of X : "+x);
}
public static void main(String args[])
{
Item i1=new Item();
Item i2=new Item(i1);
i1.display();
i2.display();
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 34
VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 35
VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 36
VJTech Academy
39. 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.
import java.util.*;
class Student
{
int id;
String name;
void SetData()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Student ID:");
id=sc.nextInt();
System.out.println("Enter Student Name:");
name=sc.next();
}
void display()
{
System.out.println("Student ID:"+id);
System.out.println("Student Name:"+name);
}
public static void main(String args[])
{
Student s[]=new Student[5];
System.out.println("Enter five students information");
for(int i=0;i<5;i++)
{
s[i]=new Student();
s[i].SetData();
}
for(int i=0;i<5;i++)
{
s[i].display();
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 37
VJTech Academy
40. Write a program to create two threads. One thread will display the numbers from 1 to 50
(ascending order) and other thread will display numbers from 50 to 1 (descending order).
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 38
VJTech Academy
- By using command line argument, we can pass input values to our java program.
- This is one of the way for giving inputs to our java program.
- While executing code we are passing list of values to our java program.
- Whatever the values we have passed that would be stored in command line argument i.e String
args[].
- Initially string object args is empty but when we send list of arguments that all values should be
stored in args of string array.
- This string array will grow automatically.
- Example: java filename java VJTech 100 200
- Program
class CommandLineArgsDemo
{
public static void main(String args[])
{
int a,b,c;
a=Integer.parseInt(args[0]);
b=Integer.parseInt(args[1]);
c=a+b;
System.out.println("Addition="+c);
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 39
VJTech Academy
42. Write a program to input name and salary of employee and throw user defined exception if
entered salary is negative.
import java.util.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class Employee
{
String name;
int salary;
void getdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter employee name:");
name=sc.next();
System.out.println("Enter employee salary:");
salary=sc.nextInt();
}
void putdata()
{
if(salary<0)
{
try
{
throw new MyException("Salary Negative Exception");
}
catch(MyException e)
{
System.out.println(e);
}
}
else
{
System.out.println("Employee Name:"+name);
System.out.println("Employee Salary:"+salary);
}
}
public static void main(String args[])
{
Employee e1=new Employee();
e1.getdata();
e1.putdata();
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 40
VJTech Academy
43. Describe the use of any methods of vector class with their syntax
- Vector is an extensible array.
- Vector is a collection of objects and it can be retrieved by using index number.
- Array is a collection of similar types of elements but its size is fixed.
- But vector is a collection of objects but its size is not fixed.
- Vector class provides array of variable size.
- The main difference between vector and array: Vector automatically grow when they run out of
space.
- Vectors class provides extra method for adding and removing elements.
- The class is used to create dynamic array known as Vector that can holds objects of any type and
any numbers.
- Vector is a predefined class which is present under java.util package.
- Vectors are created like array as follow:
1) Declaration of Vector without size.
Vector VectorName=new Vector():
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 41
VJTech Academy
Program:
import java.util.*;
class VectorDemo1
{
public static void main(String args[])
{
Vector v1=new Vector();
v1.addElement(new Integer(10));
v1.addElement(new Integer(30));
v1.addElement(new Integer(60));
v1.addElement(new Integer(70));
v1.addElement(new Integer(80));
v1.addElement(new Integer(100));
System.out.println("Initial Vector Elements = "+v1);
v1.removeElementAt(3);
v1.removeElementAt(4);
v1.insertElementAt(new Integer(150),3);
System.out.println("Final Vector Elements = "+v1);
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 42
VJTech Academy
44. Describe instance Of and dot (.) operators in Java with suitable example
Instanceof Operator:
- This operator returns true if the object on the left side is an instance of the class given on the right
side.
- Syntax:
if(object instanceof ClassName)
{
//body
}
- Example:
import java.util.*;
class InstanceOfOpDemo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
if(sc instanceof Scanner)
{
System.out.println("sc is an object of Scanner class");
}
}
}
Dot Operator:
- Example:
a1.a=100;
a1.b=200;
a1.getdata();
a1.display();
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 43
VJTech Academy
Method names are same but its arguments are Base class method and derived class method is
different is knowns as method overloading. same then base class method overridden by
derived class.
Method overloading is used to increase the Method overriding is used to provide the specific
readability of the program. implementation of the method that is already
provided by its super class.
Method overloading is performed within class. Method overriding occurs in two classes.
In case of method overloading, parameter must In case of method overriding, parameter must be
be different. same.
Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 44
VJTech Academy
46. WAP to accept a password from the user and throw “Authentication Failure” exception if the
password is incorrect.
import java.util.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class AuthenticationDemo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter your password:");
String psw=sc.next();
if(psw.equals("vjtech"))
{
System.out.println("Authentication Sucessful");
}
else
{
try
{
throw new MyException("Authentication Failure");
}
catch(MyException e)
{
System.out.println(e);
}
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 45
VJTech Academy
47. Write a program to input name and balance of customer and thread a user defined exception if
balance less than 1500.
import java.util.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class UserdefinedExeDemo
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter customer name:");
String name=sc.next();
System.out.println("Enter customer balance:");
int balance=sc.nextInt();
if(balance<1500)
{
try
{
throw new MyException("Balance less than 1500");
}
catch(MyException e)
{
System.out.println(e);
}
}
else
{
System.out.println("Balance greater than 1500");
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 46
VJTech Academy
48. Define an exception called ‘No match Exception’ that is thrown when a string is not equal to
“MSBTE”. Write program.
import java.util.*;
class MyException extends Exception
{
MyException(String msg)
{
super(msg);
}
}
class UserdefinedExeDemo1
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter any string:");
String str=sc.next();
if(str.equals("MSBTE"))
{
System.out.println("Given String match with MSBTE");
}
else
{
try
{
throw new MyException("No match exception");
}
catch(MyException e)
{
System.out.println(e);
}
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 47
VJTech Academy
49. Write a program to create package Math_s having two classes as addition and subtraction. Use
suitable methods in each class to perform basic operations.
package Math_s;
public class Subtraction
{
public void sub(int x,int y)
{
System.out.println("Subtraction="+(x-y));
}
}
import Math_s.*;
class AccessMathPkg
{
public static void main(String args[])
{
Addition a1=new Addition();
Subtraction s1=new Subtraction();
a1.add(100,50);
s1.sub(100,50);
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 48
VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 49
VJTech Academy
{
System.out.println("display method of derived class");
}
}
class AvoidMethodOverriding
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
}
}
/*
AvoidMethodOverriding.java:11: error: display() in Derived cannot override display() in Base
void display()
^
overridden method is final
1 error
*/
3) To avoid inheritance:
- To avoid inheritance then we can declare the base class using final keyword.
- If we declare base class using final keyword then we cannot create subclass from it.
- Example:
final class Base
{
void display()
{
System.out.println("display method of base class");
}
}
class Derived extends Base
{
void show()
{
System.out.println("show method of derived class");
}
}
class AvoidInheritance
{
public static void main(String args[])
{
Derived d1=new Derived();
d1.display();
d1.show();
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 50
VJTech Academy
}
/*
AvoidInheritance.java:9: error: cannot inherit from final Base
class Derived extends Base
^
1 error
*/
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 51
VJTech Academy
52. What is the multiple inheritance? Write a java program to implement multiple inheritance
OR
Explain how interface is used to achieve multiple Inheritances in Java.
- To inherit the properties of more than one base class into sub class is known as multiple
inheritances.
- In multiple inheritance we can combine the features of more than one existing classes into new
class.
- Below diagram shows the multiple inheritance concepts:
- Java classes cannot have more than one super class. But in most of the real time application
multiple inheritances is required. So, java provides an alternative approach is known as
interface.
- Interface is a collection of static final variables and abstract methods. It is used to achieve the
multiple inheritance in Java.
- Below diagram shows, how to achieve the multiple inheritance in Java language:
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 52
VJTech Academy
- In first diagram, class implementing more than one interface and in second diagram interface
extending more than one interfaces to achieve the multiple inheritance in Java.
- Program:
interface Abc
{
void display();
}
interface Xyz
{
void show();
}
53. Define class Student with suitable data members create two objects using two different
constructors of the class.
class Student
{
int rollno;
String name;
float marks;
Student()
{
rollno=1010;
name="Dennis";
marks=98.78f;
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 53
VJTech Academy
}
Student(int r,String n,float m)
{
rollno=r;
name=n;
marks=m;
}
void display()
{
System.out.println("Student Roll No:"+rollno);
System.out.println("Student Name:"+name);
System.out.println("Student Marks:"+marks);
}
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student(2020,"James",75.55f);
s1.display();
s2.display();
}
}
54. Write a program to define class Employee with members as id and salary. Accept data for five
employees and display details of employees getting highest salary.
import java.util.*;
class Employee
{
int id;
float salary;
void get_emp_info()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Employee ID:");
id=sc.nextInt();
System.out.println("Enter Employee Salary:");
salary=sc.nextFloat();
}
public static void main(String args[])
{
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 54
VJTech Academy
55. Define a class ‘Book’ with data members bookid, bookname and price. Accept data for seven
objects using Array of objects and display it.
import java.util.*;
class Book
{
int book_id;
String book_name;
float book_price;
void get_book_info()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Book ID:");
book_id=sc.nextInt();
System.out.println("Enter Book Name:");
book_name=sc.next();
System.out.println("Enter Book price:");
book_price=sc.nextFloat();
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 55
VJTech Academy
}
void disp_book_info()
{
System.out.println("Book ID:"+book_id);
System.out.println("Book Name:"+book_name);
System.out.println("Book Price:"+book_price);
}
public static void main(String args[])
{
Book b[]=new Book[7];
for(int i=0;i<7;i++)
{
b[i]=new Book();
b[i].get_book_info();
}
for(int i=1;i<5;i++)
{
b[i].disp_book_info();
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 56
VJTech Academy
- finalize() method: The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing.
- Syntax:
protected void finalize()
{
//body
}
- The Garbage collector of JVM collects only those objects that are created by new keyword. So if
you have created any object without new, you can use finalize method to perform cleanup
processing.
- gc() method: The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
- Syntax:
public static void gc()
{
//body
}
- Garbage collection is performed by a daemon thread called Garbage Collector(GC). This thread
calls the finalize() method before object is garbage collected.
- Program:
class TestGarbage
{
protected void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[])
{
TestGarbage s1=new TestGarbage();
s1=null;
System.gc();
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 57
VJTech Academy
2) Class Variables:
- Class variables are declared inside the class.
- They are the global to the class.
- It common between all objects.
- Only one memory location is created for each class variables.
3) Local Variables:
- Local Variables declared and used inside the functions.
- The variables which are declared inside the body of methods in known as local variables.
- They are not available outside the method.
- Local variables can be declared inside the body of methods which is starting from
opening curly braces ({} and closing braces(}).
Example:
class Student
{
int rollno; //instance variable
String name; //instance variable
float marks; //instance variable
static int college_code=1010; //class variable
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 58
VJTech Academy
void calc_marks()
{
int total; //local variable
}
}
58. Write all primitive data types available in Java with their storage sizes in bytes
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 59
VJTech Academy
59. Write a program to copy all elements of one array into another array.
import java.util.*;
class CopyArray
{
public static void main(String args[])
{
int a[]=new int[5];
int b[]=new int[5];
int i;
Scanner sc=new Scanner(System.in);
System.out.println("Enter Arry Elements:");
for(i=0;i<5;i++)
{
a[i]=sc.nextInt();
}
//copy one array into another array
for(i=0;i<5;i++)
{
b[i]=a[i];
}
System.out.println("Copied Array Elements:");
for(i=0;i<5;i++)
{
System.out.println(a[i]+"\t");
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 60
VJTech Academy
60. Write a program to print even and odd number using two threads with delay of 1000ms after each
number
class ThreadX extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
if(i%2==0)
{
System.out.println("Even Number:"+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class ThreadY extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
if(i%2!=0)
{
System.out.println("Odd Number:"+i);
try
{
sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
}
}
class MainThread
{
public static void main(String args[])
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 61
VJTech Academy
{
ThreadX t1=new ThreadX();
ThreadY t2=new ThreadY();
t1.start();
t2.start();
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 62
VJTech Academy
61. Write a program to print all the Armstrong numbers from 0 to 999.
class ArmstrongNumber
{
public static void main(String args[])
{
int i,no,sum,rem;
for(i=1;i<=999;i++)
{
no=i;
sum=0;
while(no>0)
{
rem=no%10;
sum=sum+(rem*rem*rem);
no=no/10;
}
if(i==sum)
{
System.out.println("Armstrong Number:"+i);
}
}
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 63
VJTech Academy
62. Develop and Interest Interface which contains Simple Interest and Compound Interest methods
and static final field of rate 25%. Write a class to implement those methods
-> Simple Interest formula: SI = P * R * T,
where P = Principal, R = Rate of Interest, T = Time period.
->I = (P*(1+(R/N))^(N*T))
Where I = Interest,P = Principle, the original amount,R = interest rate, N = number of times the
interest is compounded in a year, T = number of years
import java.util.*;
interface Interest
{
int R=25;
void Simple_Interest();
void Compound_Interest();
}
class InterestCalc implements Interest
{
int P,T,N;
public void Simple_Interest()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Principal Amount:");
P=sc.nextInt();
System.out.println("Enter no of years:");
T=sc.nextInt();
int SI=(P*R*T);
System.out.println("Simple Interest="+SI);
}
public void Compound_Interest()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter Principal Amount:");
P=sc.nextInt();
System.out.println("Enter no of years:");
T=sc.nextInt();
System.out.println("No of times compounded interest calculated:");
N=sc.nextInt();
float CI=(P*(1+(R/N))^(N*T));
System.out.println("Compound Interest="+CI);
}
public static void main(String args[])
{
InterestCalc c1=new InterestCalc();
c1.Simple_Interest();
c1.Compound_Interest();
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 64
VJTech Academy
}
}
63. Write a program to print the sum, difference and product of two complex numbers by creating a
class named "Complex" with separate methods for each operation whose real and imaginary parts
are entered by user.
import java.util.*;
class Complex
{
int real,imag;
void getdata()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter real number:");
real=sc.nextInt();
System.out.println("Enter Imaginary number:");
imag=sc.nextInt();
}
void sum(Complex m)
{
System.out.println("Sum="+(real+m.real)+"+i"+(imag+m.imag));
}
void difference(Complex m)
{
System.out.println("Difference="+(real-m.real)+"+i"+(imag-m.imag));
}
void product(Complex m)
{
System.out.println("Product="+(real*m.real)+"+i"+(imag*m.imag));
}
public static void main(String args[])
{
Complex c1=new Complex();
Complex c2=new Complex();
c1.getdata();
c2.getdata();
c1.sum(c2);
c1.difference(c2);
c1.product(c2);
}
}
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 65
VJTech Academy
JAVA IMP Questions by Mr. Vishal Jadhav Sir’s (VJTech Academy, contact us: +91-7743909870) 66