OOAD, General Interview Questions.: 1 By: Vishal Pachpute. Mob: 9960972016
OOAD, General Interview Questions.: 1 By: Vishal Pachpute. Mob: 9960972016
The process of obtaining the data members and methods from one class to another class is known
as inheritance. It is one of the fundamental features of object-oriented programming.
If we develop any application using concept of Inheritance than that application have following
advantages,
No, In Inheritance the scope of access modifier increasing is allow but decreasing is not allow.
Suppose in parent class method access modifier is default then it's present in child class with
default or public or protected access modifier but not private(it decreased scope).
Single inheritance
Multilevel inheritance
Hierarchical inheritance
Hybrid inheritance
Due to ambiguity problem java does not support multiple inheritance at class level.
Java can not support multiple inheritance at class level but you can achieve multiple inheritance
in java by using Interface concept.
Package keyword is always used for creating the undefined package and placing common classes
and interfaces.
import is a keyword which is used for referring or using the classes and interfaces of a specific
package.
The real life example of inheritance is child and parents, all the properties of father are inherited
by his son.
No memory is allocated at the time of Sufficient memory space will be allocated for all the
2
declaration variables of class at the time of declaration.
In real world many examples of object and class like dog, cat, and cow are belong to animal's
class. Each object has state and behaviors. For example a dog has state:- color, name, height, age
as well as behaviors:- barking, eating, and sleeping.
Interface
What is interface ?
Interface is similar to class which is collection of public static final variables (constants) and
abstract methods.
Whenever we compile any Interface program it generate .class file. That means the bytecode of
an interface appears in a .class file.
Because, constructor are used for eliminate the default values by user defined values, but in case
of interface all the data members are public static final that means all are constant so no need to
eliminate these values.
Other reason because constructor is like a method and it is concrete method and interface does
not have concrete method it have only abstract methods that's why interface have no constructor.
Why Method Overloading is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity.
Because, constructor are used for eliminate the default values by user defined values, but in case
of interface all the data members are public static final that means all are constant so no need to
eliminate these values.
Other reason because constructor is like a method and it is concrete method and interface does
not have concrete method it have only abstract methods that's why interface have no constructor.
In java, abstract and final both modifiers are not allowed for a class at a time the reason is
abstract and final are opposite keywords. If a class is an abstract, then that class must be
extended (inherited). If a class is final then that class can not be extended. So both keyword can
not be use at a time
Abstract class are used for fulfill common requirement. If we use concrete classes for fulfill
common requirements than such application will get the following limitations.
Concrete class containing fully defined methods or Abstract class have both undefined method and
implemented method. defined method.
Encapsulation is not provides fully security because we can access private member of the class
using reflation API, but in case of Abstraction we can't access static, abstract data member of
class.
There properties can be reused commonly in a There properties commonly usable in any
2
specific application. application of java environment.
5 Which may contain either variable or constants. Which should contains only constants.
The default access specifier of abstract class There default access specifier of interface method
6
methods are default. are public.
These class properties can be reused in other These properties can be reused in any other class
7
class using extend keyword. using implements keyword.
8 Inside abstract class we can take constructor. Inside interface we can not take any constructor.
For the abstract class there is no restriction like For the interface it should be compulsory to
9 initialization of variable at the time of variable initialization of variable at the time of variable
declaration. declaration.
Inside interface we can take instance and static Inside interface we can not take instance and static
10
block. block.
There are no any restriction for abstract class For the interface method can not declare method as
12 method modifier that means we can use any strictfp, protected, static, native, private, final,
modifiers. synchronized.
Abstraction shows only important things to the user and hides the internal details for example
when we ride a bike, we only know about how to ride bike but can not know about how it work ?
and also we do not know internal functionality of bike.
The common example of encapsulation is capsule. In capsule all medicine are encapsulated in
side capsule.
Encapsulation is not provides fully security because we can access private member of the class
using reflation API, but in case of Abstraction we can't access static, abstract data member of
class.
polymorphism
Give Real life example of polymorphism
Suppose if you are in class room that time you behave like a student, when you are in market at
that time you behave like a customer, when you at your home at that time you behave like a son
or daughter, Here one person present in different-different behaviors.
Whenever same method or Constructor is existing Whenever same method name is existing
multiple times within a class either with different multiple time in both base and derived class
1 number of parameter or with different type of with same number of parameter or same type
parameter or with different order of parameter is of parameter or same order of parameters is
known as Overloading. known as Overriding.
Arguments of method must be different at least Argument of method must be same including
2
arguments. order.
Also known as compile time polymorphism or static Also known as run time polymorphism or
6
polymorphism or early binding. dynamic polymorphism or late binding.
Overloading can be exhibited both are method and Overriding can be exhibited only at method
7
constructor level. leve.
Overloading can be done at both static and non- Overriding can be done only at non-static
9
static methods. method.
For overloading methods return type may or may For overriding method return type should be
10
not be same. same.
OOPs stands for Object Oriented Programming. The concepts in oops are similar to any other
programming languages.
2. What is polymorphism?
The ability to define a function in multiple forms is called Polymorphism. In java, c++ there are two types
of polymorphism: compile time polymorphism (overloading) and runtime polymorphism (overriding).
Overloading: Overloading is determined at the compile time. It occurs when several methods have
same names with:
1) First and important rule to overload a method in java is to change method signature. Method
signature is made of number of arguments, type of arguments and order of arguments if they
are of different types.
2) Return type of method is never part of method signature, so only changing the return type of
method does not amount to method overloading.
3) Thrown exceptions from methods are also not considered when overloading a method. So your
overloaded method throws the same exception, a different exception or it simply does no throw
any exception; no effect at all on method loading.
Example of Overloading
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
}
}
Output:30
40
******************************
Method overriding: Overriding occurs when a class method has the same name and signature as a
method in parent class. When you override methods, JVM determines the proper methods to call at the
program’s run time, not at the compile time.
If a class inherits a method from its super class, then there is a chance to override the method
provided that it is not marked final.
The benefit of overriding is: ability to define a behaviour that's specific to the subclass type
which means a subclass can implement a parent class method based on its requirement.
Example:
class Animal{
In the above example, you can see that the even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time, the check is made on the reference
type. However, in the runtime, JVM figures out the object type and would run the method that belongs
to that particular object.
Therefore, in the above example, the program will compile properly since Animal class has the
method move. Then, at the runtime, it runs the method specific for that object.
Inheritance allows a Child class to inherit properties from its parent class. In Java this is achieved by
using extends keyword. Only properties with access modifier public and protected can be accessed in
child class.
In above example the child has inherit its family name from the parent class just by inheriting the class.
When child object is created printMyName() present in child class is called.
Inheritance can be defined as the process where one class acquires the properties (methods and fields)
of another. With the use of inheritance the information is made manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).
Sample Code
Below given is an example demonstrating Java inheritance. In this example you can observe two classes
namely Calculation and My_Calculation.
Using extends keyword the My_Calculation inherits the methods addition() and Subtraction() of
Calculation class.
*****************
class Calculation
{
int z;
**********************
In the given program when an object to My_Calculation class is created, a copy of the contents of the
super class is made with in it. That is why, using the object of the subclass you can access the members
of a super class.
The Superclass reference variable can hold the subclass object, but using that variable you can access
only the members of the superclass, so to access the members of both classes it is recommended to
always create reference variable to the subclass.
If you consider the above program you can instantiate the class as given below as well. But using the
superclass reference variable ( cal in this case ) you cannot call the method multiplication(), which
belongs to the subclass My_Calculation.
Note − A subclass inherits all the members (fields, methods, and nested classes) from its superclass.
Constructors are not members, so they are not inherited by subclasses, but the constructor of the
superclass can be invoked from the subclass.
The super keyword is similar to this keyword following are the scenarios where the super keyword is
used.
It is used to differentiate the members of superclass from the members of subclass, if they have
same names.
It is used to invoke the superclass constructor from subclass.
Sample Code
This section provides you a program that demonstrates the usage of the super keyword.
In the given program you have two classes namely Sub_class and Super_class, both have a method
named display() with different implementations, and a variable named num with different values. We
are invoking display() method of both classes and printing the value of the variable num of both classes,
here you can observe that we have used super key word to differentiate the members of super class
from sub class.
class Super_class
{
//Instantiating subclass
Sub_class sub = new Sub_class();
}
}
IS-A Relationship
IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used
to achieve inheritance.
Now, based on the above example, In Object Oriented terms, the following are true −
With use of the extends keyword the subclasses will be able to inherit all the properties of the
superclass except for the private properties of the superclass.
Example
class Animal{
}
true
true
true
Since we have a good understanding of the extends keyword let us look into how the implements
keyword is used to get the IS-A relationship.
Generally, the implements keyword is used with classes to inherit the properties of an interface.
Interfaces can never be extended by a class.
Example
public interface Animal {
}
Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog
is actually an Animal
interface Animal{}
true
true
true
Types of inheritance
A very important fact to remember is that Java does not support multiple inheritance. This means that a
class cannot extend more than one class. Therefore following is illegal −
However, a class can implement one or more interfaces. This has made Java get rid of the impossibility
of multiple inheritance.
void barking()
{
}
void hungry()
{
}
void sleeping()
{
}
}
Local variables: Variables defined inside methods, constructors or blocks are called local
variables. The variable will be declared and initialized within the method and the variable will be
destroyed when the method has completed.
Instance variables: Instance variables are variables within a class but outside any method. These
variables are initialized when the class is instantiated. Instance variables can be accessed from
inside any method, constructor or blocks of that particular class.
Class variables: Class variables are variables declared with in a class, outside any method, with
the static keyword.
A class can have any number of methods to access the value of various kinds of methods. In the above
example, barking(), hungry() and sleeping() are methods.
class Test
{
16 By: Vishal Pachpute. Mob: 9960972016
int a,b;
void print(){
System.out.println("a="+a);
System.out.println("b="+b);
}
Output:
1. a=10
2. b=20
Software objects are conceptually similar to real-world objects: they too consist of state and related
behavior. An object stores its state in fields (variables in some programming languages) and exposes its
behavior through methods (functions in some programming languages). Methods operate on an object's
internal state and serve as the primary mechanism for object-to-object communication. Hiding internal
state and requiring all interaction to be performed through an object's methods is known as data
encapsulation — a fundamental principle of object-oriented programming.
By attributing state (current speed, current pedal cadence, and current gear) and providing methods for
changing that state, the object remains in control of how the outside world is allowed to use it. For
example, if the bicycle only has 6 gears, a method to change gears could reject any value that is less than
1 or greater than 6.
Bundling code into individual software objects provides a number of benefits, including:
Every class has a constructor. If we do not explicitly write a constructor for a class the Java compiler
builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked. The main rule of
constructors is that they should have the same name as the class. A class can have more than one
constructor.
1. Constructors can use any access modifier, including private. (A private constructor means only
code within the class itself can instantiate an object of that type, so if the private constructor
class wants to allow an instance of the class to be used, the class must provide a static method
or variable that allows access to an instance created from within the class.)
2. The constructor name must match the name of the class.
3. Constructors must not have a return type.
4. It’s legal (but stupid) to have a method with the same name as the class, but that doesn’t make
it a constructor. If you see a return type, it’s a method rather than a constructor. In fact, you
could have both a method and a constructor with the same namethe name of the classin the
same class, and that’s not a problem for Java. Be careful not to mistake a method for a
constructor, be sure to look for a return type.
5. If you don’t type a constructor into your class code, a default constructor will be automatically
generated by the compiler.
6. The default constructor is ALWAYS a no-arg constructor.
7. If you want a no-arg constructor and you’ve typed any other constructor(s) into your class code,
the compiler won’t provide the no-arg constructor for you. In other words, if you’ve typed in a
constructor with arguments, you won’t have a no-arg constructor unless you type it in yourself !
8. Every constructor has, as its first statement, either a call to an overloaded constructor (this()) or
a call to the superclass constructor (super()), although remember that this call can be inserted
by the compiler.
18 By: Vishal Pachpute. Mob: 9960972016
9. If you do type in a constructor (as opposed to relying on the compiler-generated default
constructor), and you do not type in the call to super() or a call to this(), the compiler will insert
a no-arg call to super() for you, as the very first statement in the constructor.
10. A call to super() can be either a no-arg call or can include arguments passed to the super
constructor.
11. A no-arg constructor is not necessarily the default (i.e., compiler-supplied) constructor, although
the default constructor is always a no-arg constructor. The default constructor is the one the
compiler provides! While the default constructor is always a no-arg constructor, you’re free to
put in your own noarg constructor.
12. You cannot make a call to an instance method, or access an instance variable, until after the
super constructor runs.
13. Only static variables and methods can be accessed as part of the call to super() or this().
(Example: super(Animal.NAME) is OK, because NAME is declared as a static variable.)
14. Abstract classes have constructors, and those constructors are always called when a concrete
subclass is instantiated.
15. Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.
8. What is abstraction
Abstraction is the quality of dealing with ideas rather than events. for example when you consider the
case of e-mail, complex details such as what happens soon you send an e-mail, the protocol your email
server uses are hidden from the user, therefore to send an e-mail you just need to type the content,
mention the address of the receiver and click send.
like wise in Object oriented programming Abstraction is a process process of hiding the implementation
details from the user, only the functionality will be provided to the user. In other words user will have
the information on what the object does instead of how it does it.
Abstract Class
A class which contains the abstract keyword in its declaration is known as abstract class.
Abstract classes may or may not contain abstract methods ie., methods with out body ( public
void get(); )
But, if a class have at least one abstract method, then the class must be declared abstract.
If a class is declared abstract it cannot be instantiated.
To use an abstract class you have to inherit it from another class, provide implementations to
the abstract methods in it.
If you inherit an abstract class you have to provide implementations to all the abstract methods
in it.
Example
This section provides you an example of the abstract class to create an abstract class just use the
abstract keyword before the class keyword, in the class declaration .
9. What is Encapsulation
Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance,
polymorphism, and abstraction.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data
(methods) together as as single unit. In encapsulation the variables of a class will be hidden from other
classes, and can be accessed only through the methods of their current class, therefore it is also known
as data hiding.
Example:
Below given is an example that demonstrates how to achieve Encapsulation in Java:
/* File name : EncapTest.java */
public class EncapTest{
The public setXXX() and getXXX() methods are the access points of the instance variables of the
EncapTest class. Normally, these methods are referred as getters and setters. Therefore any class that
wants to access the variables should access them through these getters and setters.
Benefits of Encapsulation:
An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods. A class
implements an interface, thereby inheriting the abstract methods of the interface.
Implementing Interfaces:
When a class implements an interface, you can think of the class as signing a contract, agreeing to
perform the specific behaviors of the interface. If a class does not perform all the behaviors of the
interface, the class must declare itself as abstract.
A class uses the implements keyword to implement an interface. The implements keyword appears in
the class declaration following the extends portion of the declaration.
Encapsulation
Encapsulation provides objects with the ability to hide their internal characteristics and behavior.
Each object provides a number of methods, which can be accessed by other objects and change
its internal data. In Java, there are three access modifiers: public, private and protected. Each
modifier imposes different access rights to other classes, either in the same or in external
packages. Some of the advantages of using encapsulation are listed below:
Polymorphism
Polymorphism is the ability of programming languages to present the same interface for differing
underlying data types. A polymorphic type is a type whose operations can also be applied to
values of some other type.
Inheritance
Inheritance provides an object with the ability to acquire the fields and methods of another class,
called base class. Inheritance provides re-usability of code and can be used to add additional
features to an existing class, without modifying it.
Abstraction
Abstraction is the process of separating ideas from specific instances and thus, develop
classes in terms of their own functionality, instead of their implementation details. Java
supports the creation and existence of abstract classes that expose interfaces, without
including the actual implementation of all methods. The abstraction technique aims to
separate the implementation details of a class from its behavior.
A Java virtual machine (JVM) is a process virtual machine that can execute Java
bytecode. Each Java source file is compiled into a bytecode file, which is executed by the
JVM. Java was designed to allow application programs to be built that could be run on
any platform, without having to be rewritten or recompiled by the programmer for each
separate platform. A Java virtual machine makes this possible, because it is aware of the
specific instruction lengths and other particularities of the underlying hardware platform.
The Java Runtime Environment (JRE) is basically the Java Virtual Machine (JVM) where
your Java programs are being executed. It also includes browser plugins for applet
execution. The Java Development Kit (JDK) is the full featured Software Development
Kit for Java, including the JRE, the compilers and tools (like JavaDoc, and Java
Debugger), in order for a user to develop, compile and execute Java applications.
3. What does the “static” keyword mean ? Can you override private or static method
in Java ?
The static keyword denotes that a member variable or method can be accessed, without
requiring an instantiation of the class to which it belongs. A user cannot override static
methods in Java, because method overriding is based upon dynamic binding at runtime
and static methods are statically binded at compile time. A static method is not associated
with any instance of a class so the concept is not applicable.
A static variable in Java belongs to its class and its value remains the same for all its
instances. A static variable is initialized when the class is loaded by the JVM. If your
code tries to access a non-static variable, without any instance, the compiler will
complain, because those variables are not created yet and they are not associated with any
instance.
No, Java does not support multiple inheritance. Each class is able to extend only on one
class, but is able to implement more than one interfaces.
All methods in an interface are implicitly abstract. On the other hand, an abstract class may
contain both abstract and non-abstract methods.
A class may implement a number of Interfaces, but can extend only one abstract class.
In order for a class to implement an interface, it must implement all its declared methods.
However, a class may not implement all declared methods of an abstract class. Though, in
this case, the sub-class must also be declared as abstract.
Abstract classes can implement interfaces without even providing the implementation of
interface methods.
Variables declared in a Java interface is by default final. An abstract class may contain non-
final variables.
Members of a Java interface are public by default. A member of an abstract class can either
be private, protected or public.
An interface is absolutely abstract and cannot be instantiated. An abstract class also cannot
be instantiated, but can be invoked if it contains a main method.
When an object is passed by value, this means that a copy of the object is passed. Thus,
even if changes are made to that object, it doesn’t affect the original value. When an
object is passed by reference, this means that the actual object is not passed, rather a
reference of the object is passed. Thus, any changes made by the external method, are
also reflected in all places.
A HashMap allows the existence of null keys and values, while a Hashtable doesn’t
allow neither null keys, nor null values.
A Hashtable is synchronized, while a HashMap is not. Thus, HashMap is preferred in
single-threaded environments, while a Hashtable is suitable for multi-threaded
environments.
A HashMap provides its set of keys and a Java application can iterate over them.
Thus, a HashMap is fail-fast. On the other hand, a Hashtable provides an
Enumeration of its keys.
The Hashtable class is considered to be a legacy class.
11. What are the two types of Exceptions in Java ? Which are the differences between
them ?
Java has two types of exceptions: checked exceptions and unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or a constructor’s throws
25 By: Vishal Pachpute. Mob: 9960972016
clause, if they can be thrown by the execution of the method or the constructor, and
propagate outside the method or constructor boundary. On the other hand, checked
exceptions must be declared in a method or a constructor’s throws clause. See here for
tips on Java exception handling.
Exception and Error classes are both subclasses of the Throwable class. The Exception
class is used for exceptional conditions that a user’s program should catch. The Error
class defines exceptions that are not excepted to be caught by the user program.
The throw keyword is used to explicitly raise a exception within the program. On the
contrary, the throws clause is used to indicate those exceptions that are not handled by a
method. Each method must explicitly specify which exceptions does not handle, so the
callers of that method can guard against possible exceptions. Finally, multiple exceptions
are separated by a comma.
A finally block will always be executed, whether or not an exception is actually thrown.
Even in the case where the catch statement is missing and an exception is thrown, the
finally block will still be executed. Last thing to mention is that the finally block is used
to release resources like I/O buffers, database connections, etc.
15. What will happen to the Exception object after exception handling ?
The Exception object will be garbage collected in the next garbage collection.
A finally block will be executed whether or not an exception is thrown and is used to
release those resources held by the application. Finalize is a protected method of the
Object class, which is called by the Java Virtual Machine (JVM) just before an object is
garbage collected.
A constructor is a member function of a class that is used to create objects of that class. It
has the same name as the class itself, has no return type, and is invoked using the new
operator. A method is an ordinary member function of a class. It has its own name, a
return type (which may be void), and is invoked using the dot operator.
Function is that piece of code that has name ( called function name) and data to operate
on ( called arguments) that is provided in the parenthesis adjacent to the function name.
All function arguments are explicit.
Method on the other had can be viewed as a function that acts on an Object. This object is
an instance of a class (blueprint of that instance). Method will always have an implicit
argument as a reference to self. For example in python you use self , or in Java you use
this.
package Programs;
import java.util.Scanner;
2. Factorial No:
package Programs;
import java.util.Scanner;
}
System.out.print("Factorial No is: " +prod);
}
3. Fibonacci Series:
package Programs;
}
System.out.println (sum);
}
}
//Method 2
public static void main(String args[])
{
int prev, next, sum, n;
prev=next=1;
for(n=1;n<=10;n++)
{
System.out.println(prev);
sum=prev+next;
prev=next;
next=sum;
}
}
}
4. Patterns:
package Programs;
}
}
5. Prime Numbers
package Programs;
import java.util.Scanner;
{
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int res =0;
boolean flag=true;
for (int i=2; i<n/2;i++)
{
res=n%i;
if(res ==0)
{
flag=false;
break;
}
}
if(flag)
System.out.println("No is prime");
else
import java.util.Scanner;
7. Reverse of Numbers
package Programs;
import java.util.Scanner;
8. Reverse of String
package Programs;
import java.util.Scanner;
}
System.out.println("After reverse " +reverse);
}
9. String Programs
package Programs;
import java.util.Scanner;
if (original.equals(reverse))
System.out.println("Entered string is a palindrome.");
else
System.out.println("Entered string is not a palindrome.");
import java.util.Scanner;
}
System.out.print("Sum of Numbers is " +sum);
}
import java.util.Scanner;
}
//Using Third variable
import java.util.Scanner;
Description Logic
for(i=2;i<=n/2;i++)
Prime Numbers - Prime Number are {
divisible by itself only. res=n%i;
if(res==0)
{
flag=false;
break;
}
}
if(flag)
for(n=1;n<=10;n++)
Fibonacci Series ( 1 1 2 3 5 8 13...) {
Sum of previous two numbers will System.out.println(prev);
give us next number sum=prev+next;
prev=next;
next=sum;
}
for(n=1;n<=10;n++)
Sum of 1st 10 Natural Numbers: Sum {
of previous two numbers will give sum+=n; //or sum=sum+n;
}
us next number. System.out.println(sum);
int n, sum=0;
Sum of Square of 1st 10 Natural for(n=1;n<=10;n++)
Numbers {
sum+=n;*n //or
sum=sum+n;*n
}
System.out.println(sum);
for(i=n;i>=1;i--)
Factorial : Factorial of 5 = 5 x 4 x 3 {
x2x1 prod*=i;
//prod=prod*i;
}
System.out.println("Factorial of " + n + " is " +
prod);
}
temp=n1;
Swap 2 Numbers using 3rd Variable n1=n2;
n2=temp;
System.out.println("First No: " +
n1);
System.out.println("Second No: " +
n2);
n1=n1+n2;
Swap 2 Numbers without using 3rd n2=n1-n2;
Variable n1=n1-n2
while(n>0)
Sum of Digits 513 -> 5+1+3=9 {
res=n%10;
n=n/10;
sum+=res;
//sum=sum+res;
}
System.out.println("Second No: " +
n2);
Data Definition Language (DDL) statements are used to define the database structure or
schema. Some examples:
DML
Data Manipulation Language (DML) statements are used for managing data within schema
objects. Some examples:
DCL
TCL
Transaction Control (TCL) statements are used to manage the changes made by DML
statements. It allows statements to be grouped together into logical transactions.
Table: Gardners
Table: Plantings
Inner Join
An inner join produces a result set that is limited to the rows where there is a match in both tables for
what we're looking for. If you don't know which kind of join you need, this will usually be your best bet.
Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
INNER JOIN Plantings
ON gid = gardener_id
A left outer join, or left join, results in a set where all of the rows from the first, or left hand side, table
are preserved. The rows from the second, or right hand side table only show up if they have a match
with the rows from the first table. Where there are values from the left table but not from the right, the
table will read null, which means that the value has not been set.
Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
LEFT OUTER JOIN Plantings
ON gid = gardener_id
A right outer join, or right join, is the same as a left join, except the roles are reversed. All of the rows
from the right hand side table show up in the result, but the rows from the table on the left are only
there if they match the table on the right. Empty spaces are null, just like with the the left join.
Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
RIGHT OUTER JOIN Plantings
ON gid = gardener_id
Cross Join
The cross join returns a table with a potentially very large number of rows. The row count of the result
is equal to the number of rows in the first table times the number of rows in the second table. Each row
is a combination of the rows of the first and second table.
Example:
SELECT gid, first_name, last_name, pid, gardener_id, plant_name
FROM Gardners
CROSS JOIN Plantings
You can join a single table to itself. In this case, you are using the same table twice.
Example:
SELECT G1.gid, G1.first_name, G1.last_name, G2.gid, G2.first_name, G2.last_name
FROM Gardners G1
INNER JOIN Gardners G2
ON G1.first_name = G2.first_name
Table: Dept
7) List dept no., Dept name for all the departments in which there are no employees in the department.
select * from dept where deptno not in (select deptno from emp);
alternate solution: select * from dept a where not exists (select * from emp b where a.deptno =
b.deptno);
altertnate solution: select empno,ename,b.deptno,dname from emp a, dept b where a.deptno(+) =
b.deptno and empno is null;
14) Suppose there is annual salary information provided by emp table. How to fetch monthly salary of
each and every employee?
select ename,sal/12 as monthlysal from emp;
15) Select all record from emp table where deptno =10 or 40.
select * from emp where deptno=30 or deptno=10;
16) Select all record from emp table where deptno=30 and sal>1500.
select * from emp where deptno=30 and sal>1500;
17) Select all record from emp where job not in SALESMAN or CLERK.
select * from emp where job not in ('SALESMAN','CLERK');
19) Select all records where ename starts with ‘S’ and its lenth is 6 char.
select * from emp where ename like'S____';
20) Select all records where ename may be any no of character but it should end with ‘R’.
select * from emp where ename like'%R';
25) Select all the employee group by deptno and sal in descending order.
select ename,deptno,sal from emp order by deptno,sal desc;
26) How can I create an empty table emp1 with same structure as emp?
Create table emp1 as select * from emp where 1=2;
28) Select all records where dept no of both emp and dept table matches.
select * from emp where exists(select * from dept where emp.deptno=dept.deptno)
30) How to fetch only common records from two tables emp and emp1?
(Select * from emp) Intersect (Select * from emp1)
31) How can I retrive all records of emp1 those should not present in emp2?
(Select * from emp) Minus (Select * from emp1)
32) Count the totalsa deptno wise where more than 2 employees exist.
SELECT deptno, sum(sal) As totalsal
FROM emp
GROUP BY deptno
HAVING COUNT(empno) > 2
6) Display the employee name and annual salary for all employees.
SQL>select ename, 12*(sal+nvl(comm,0)) as “annual Sal” from emp
7) Display the names of all the employees who are working in depart number 10.
SQL>select emame from emp where deptno=10;
8) Display the names of all the employees who are working as clerks and
drawing a salary more than 3000.
SQL>select ename from emp where job=’CLERK’ and sal>3000;
9) Display the employee number and name who are earning comm.
SQL>select empno,ename from emp where comm is not null;
10) Display the employee number and name who do not earn any comm.
SQL>select empno,ename from emp where comm is null;
12) Display the names of the employees who are working in the company for
the past 5 years;
SQL>select ename from emp where to_char(sysdate,’YYYY’)-to_char(hiredate,’YYYY’)>=5;
13) Display the list of employees who have joined the company before
30-JUN-90 or after 31-DEC-90.
a)select ename from emp where hiredate < ’30-JUN-1990′ or hiredate > ’31-DEC-90′;
15) Display the list of all users in your database(use catalog table).
SQL>select username from all_users;
19) Display the names of employees whose name starts with alaphabet S.
SQL>select ename from emp where ename like ‘S%’;
20) Display the Employee names for employees whose name ends with alaphabet S.
SQL>select ename from emp where ename like ‘%S’;
21) Display the names of employees whose names have second alphabet A in their names.
SQL>select ename from emp where ename like ‘_A%’;
22) select the names of the employee whose names is exactly five characters in length.
SQL>select ename from emp where length(ename)=5;
23) Display the names of the employee who are not working as MANAGERS.
SQL>select ename from emp where job not in(‘MANAGER’);
24) Display the names of the employee who are not working as SALESMAN OR
CLERK OR ANALYST.
SQL>select ename from emp where job not in(‘SALESMAN’,’CLERK’,’ANALYST’);
25) Display all rows from emp table.The system should wait after every screen full of
information.
SQL>set pause on
32) Display the maximum salary being paid to depart number 20.
SQL>select max(sal) from emp where deptno=20;
35) Display the total salary drawn by ANALYST working in depart number 40.
SQL>select sum(sal) from emp where job=’ANALYST’ and deptno=40;
36) Display the names of the employee in order of salary i.e the name of
the employee earning lowest salary should salary appear first.
SQL>select ename from emp order by sal;
39) Display empno,ename,deptno,sal sort the output first base on name and
within name by deptno and with in deptno by sal.
SQL>select empno,ename,deptno,sal from emp order by
40) Display the name of the employee along with their annual salary(sal*12).The name of the
employee earning highest annual salary should apper first.
SQL>select ename,sal*12 from emp order by sal desc;
42) Display depart numbers and total number of employees working in each department.
SQL>select deptno,count(deptno)from emp group by deptno;
44) Display the depart numbers and total salary for each department.
SQL>select deptno,sum(sal) from emp group by deptno;
45) Display the depart numbers and max salary for each department.
SQL>select deptno,max(sal) from emp group by deptno;
46) Display the various jobs and total salary for each job
SQL>select job,sum(sal) from emp group by job;
47) Display the various jobs and total salary for each job
SQL>select job,min(sal) from emp group by job;
48) Display the depart numbers with more than three employees in each dept.
SQL>select deptno,count(deptno) from emp group by deptno having count(*)>3;
49) Display the various jobs along with total salary for each of the jobs
where total salary is greater than 40000.
SQL>select job,sum(sal) from emp group by job having sum(sal)>40000;
50) Display the various jobs along with total number of employees in each
job.The output should contain only those jobs with more than three employees.
SQL>select job,count(empno) from emp group by job having count(job)>3
51) Display the name of the empployee who earns highest salary.
SQL>select ename from emp where sal=(select max(sal) from emp);
52) Display the employee number and name for employee working as clerk and
earning highest salary among clerks.
SQL>select empno,ename from emp where where job=’CLERK’
and sal=(select max(sal) from emp where job=’CLERK’);
53) Display the names of salesman who earns a salary more than the highest
salary of any clerk.
SQL>select ename,sal from emp where job=’SALESMAN’ and sal>(select
max(sal) from emp where job=’CLERK’);
54) Display the names of clerks who earn a salary more than the lowest
salary of any salesman.
SQL>select ename from emp where job=’CLERK’ and sal>(select min(sal)
from emp where job=’SALESMAN’);
55)Display the names of employees who earn a salary more than that of
Jones or that of salary grether than that of scott.
SQL>select ename,sal from emp where sal>
(select sal from emp where ename=’JONES’)and sal> (select sal from emp
where ename=’SCOTT’);
55) Display the names of the employees who earn highest salary in their respective departments.
SQL>select ename,sal,deptno from emp where sal in(select max(sal) from
emp group by deptno);
57) Display the employee names who are working in accounting department.
SQL>select ename from emp where deptno=(select deptno from dept where
dname=’ACCOUNTING’)
59) Display the Job groups having total salary greater than the maximum salary for managers.
SQL>SELECT JOB,SUM(SAL) FROM EMP GROUP BY JOB HAVING
SUM(SAL)>(SELECT
MAX(SAL) FROM EMP WHERE JOB=’MANAGER’);
60) Display the names of employees from department number 10 with salary
grether than that of any employee working in other department.
SQL>select ename from emp where deptno=10 and sal>any(select sal from emp where deptno
not in 10).
61) Display the names of the employees from department number 10 with salary greater than that
of all employee working in other departments.
SQL>select ename from emp where deptno=10 and sal>all(select sal from emp where deptno not
in 10).
69) Find the First occurance of character ‘a’ from the following string i.e
‘Computer Maintenance Corporation’.
SQL>SELECT INSTR(‘Computer Maintenance Corporation’,’a’,1) FROM DUAL
71) Display the informaction from emp table.Where job manager is found it
should be displayed as boos(Use replace function).
SQL>select replace(JOB,’MANAGER’,’BOSS’) FROM EMP;
75) Display the current date as 15th Augest Friday Nineteen Ninety Saven.
SQL>select to_char(sysdate,’ddth Month day year’) from dual
76) Display the following output for each row from emp table.
scott has joined the company on wednesday 13th August ninten nintey.
SQL>select ENAME||’ HAS JOINED THE COMPANY ON ‘||to_char(HIREDATE,’day
ddth Month year’) from EMP;
77) Find the date for nearest saturday after current date.
SQL>SELECT NEXT_DAY(SYSDATE,’SATURDAY’)FROM DUAL;
79) Display the date three months Before the current date.
SQL>select add_months(sysdate,3) from dual;
80) Display the common jobs from department number 10 and 20.
SQL>select job from emp where deptno=10 and job in(select job from emp
where deptno=20);
81) Display the jobs found in department 10 and 20 Eliminate duplicate jobs.
SQL>select distinct(job) from emp where deptno=10 or deptno=20 (or)
SQL>select distinct(job) from emp where deptno in(10,20);
83) Display the details of those who do not have any person working under them.
SQL>select e.ename from emp,emp e where emp.mgr=e.empno group by
e.ename having count(*)=1;
84) Display the details of those employees who are in sales department and
grade is 3.
85) Display those who are not managers and who are managers any one.
i)display the managers names
SQL>select distinct(m.ename) from emp e,emp m where m.empno=e.mgr;
86) Display those employee whose name contains not less than 4 characters.
SQL>select ename from emp where length(ename)>4;
87) Display those department whose name start with “S” while the location
name ends with “K”.
SQL>select dname from dept where dname like ‘S%’ and loc like ‘%K’;
89) Display those employees whose salary is more than 3000 after giving 20%
increment.
SQL>select ename,sal from emp where (sal+sal*.2)>3000;
92) Display employee name,deptname,salary and comm for those sal in between
2000 to 5000 while location is chicago.
SQL>select ename,dname,sal,comm from emp,dept where sal between 2000
and 5000
and loc=’CHICAGO’ and emp.deptno=dept.deptno;
93)Display those employees whose salary greter than his manager salary.
SQL>select p.ename from emp e,emp p where e.empno=p.mgr and p.sal>e.sal
94) Display those employees who are working in the same dept where his
manager is work.
SQL>select p.ename from emp e,emp p where e.empno=p.mgr and
p.deptno=e.deptno;
95) Display those employees who are not working under any manager.
SQL>select ename from emp where mgr is null
96) Display grade and employees name for the dept no 10 or 30 but grade is
not 4 while joined the company before 31-dec-82.
97) Update the salary of each employee by 10% increment who are not
eligiblw for commission.
SQL>update emp set sal=sal+sal*10/100 where comm is null;
98) SELECT those employee who joined the company before 31-dec-82 while
their dept location is newyork or Chicago.
SQL>SELECT EMPNO,ENAME,HIREDATE,DNAME,LOC FROM EMP,DEPT
WHERE (EMP.DEPTNO=DEPT.DEPTNO)AND
HIREDATE <’31-DEC-82′ AND DEPT.LOC IN(‘CHICAGO’,’NEW YORK’);
101) Display name and salary of ford if his salary is equal to hisal of his
grade
a)select ename,sal,grade from emp,salgrade where sal between losal and
hisal
and ename =’FORD’ AND HISAL=SAL;
102) Display employee name,job,depart name ,manager name,his grade and make
out an under department wise?
SQL>SELECT E.ENAME,E.JOB,DNAME,EMP.ENAME,GRADE FROM EMP,EMP
E,SALGRADE,DEPT
WHERE EMP.SAL BETWEEN LOSAL AND HISAL AND EMP.EMPNO=E.MGR
AND EMP.DEPTNO=DEPT.DEPTNO ORDER BY DNAME
103) List out all employees name,job,salary,grade and depart name for every
one in the company except ‘CLERK’.Sort on salary display the highest salary?
SQL>SELECT ENAME,JOB,DNAME,SAL,GRADE FROM EMP,SALGRADE,DEPT
WHERE
SAL BETWEEN LOSAL AND HISAL AND EMP.DEPTNO=DEPT.DEPTNO AND JOB
NOT IN(‘CLERK’)ORDER BY SAL ASC;
104) Display the employee name,job and his manager.Display also employee who
are without manager?
SQL>select e.ename,e.job,eMP.ename AS Manager from emp,emp e where
emp.empno(+)=e.mgr
107) Display those employee whose salary is equal to average of maximum and
minimum?
SQL>select ename from emp where sal=(select max(sal)+min(sal)/2 from
emp);
108) Select count of employee in each department where count greater than 3?
SQL>select count(*) from emp group by deptno having count(deptno)>3
109) Display dname where at least 3 are working and display only department
name?
SQL>select distinct d.dname from dept d,emp e where d.deptno=e.deptno
and 3>any
(select count(deptno) from emp group by deptno)
110) Display name of those managers name whose salary is more than average
salary of his company?
SQL>SELECT E.ENAME,EMP.ENAME FROM EMP,EMP E
WHERE EMP.EMPNO=E.MGR AND E.SAL>(SELECT AVG(SAL) FROM EMP);
111)Display those managers name whose salary is more than average salary of
his employee?
SQL>SELECT DISTINCT EMP.ENAME FROM EMP,EMP E WHERE
E.SAL <(SELECT AVG(EMP.SAL) FROM EMP
WHERE EMP.EMPNO=E.MGR GROUP BY EMP.ENAME) AND
EMP.EMPNO=E.MGR;
112) Display employee name,sal,comm and net pay for those employee
whose net pay is greter than or equal to any other employee salary of
the company?
SQL>select ename,sal,comm,sal+nvl(comm,0) as NetPay from emp
where sal+nvl(comm,0) >any (select sal from emp)
113) Display all employees names with total sal of company with each
employee name?
SQL>SELECT ENAME,(SELECT SUM(SAL) FROM EMP) FROM EMP;
115) Find out the number of employees whose salary is greater than their
manager salary?
SQL>SELECT E.ENAME FROM EMP ,EMP E WHERE EMP.EMPNO=E.MGR
AND EMP.SAL<E.SAL;
119) Display those employee who joined in the company in the month of Dec?
SQL>select ename from emp where to_char(hiredate,’MON’)=’DEC’;
122) Display those employee whose first 2 characters from hiredate -last 2
characters of salary?
SQL>select ename,SUBSTR(hiredate,1,2)||ENAME||substr(sal,-2,2) from emp
123) Display those employee whose 10% of salary is equal to the year of
joining?
SQL>select ename from emp where to_char(hiredate,’YY’)=sal*0.1;
126) Display those employees who joined the company before 15 of the month?
a)select ename from emp where to_char(hiredate,’DD’)<15;
127) Display those employee who has joined before 15th of the month.
a)select ename from emp where to_char(hiredate,’DD’)<15;
132) Print the details of all the employees who are Sub-ordinate to BLAKE?
SQL>select emp.ename from emp, emp e where emp.mgr=e.empno and
e.ename=’BLAKE’;
133) Display employee name and his salary whose salary is greater than
highest average of department number?
SQL>SELECT SAL FROM EMP WHERE SAL>(SELECT MAX(AVG(SAL)) FROM EMP
GROUP BY DEPTNO);
135) Display the half of the ename’s in upper case and remaining lowercase?
SQL>SELECT
SUBSTR(LOWER(ENAME),1,3)||SUBSTR(UPPER(ENAME),3,LENGTH(ENAME))
FROM EMP;
136) Display the 10th record of emp table without using group by and rowid?
SQL>SELECT * FROM EMP WHERE ROWNUM<11
MINUS
SELECT * FROM EMP WHERE ROWNUM<10
140) Display those employee whose joining of month and grade is equal.
SQL>SELECT ENAME FROM EMP WHERE SAL BETWEEN
(SELECT LOSAL FROM SALGRADE WHERE
GRADE=TO_CHAR(HIREDATE,’MM’)) AND
(SELECT HISAL FROM SALGRADE WHERE
GRADE=TO_CHAR(HIREDATE,’MM’));
146) Oops I forgot give the primary key constraint. Add in now.
SQL>alter table emp add primary key(empno);
149) I want to give a validation saying that salary cannot be greater 10,000
(note give a name to this constraint)
SQL>alter table emp add constraint chk_001 check(sal<=10000)
150) For the time being I have decided that I will not impose this validation.My boss has agreed
to pay more than 10,000.
SQL>again alter the table or drop constraint with alter table emp drop constraint chk_001
(or)Disable the constraint by using alter table emp modify constraint chk_001 disable;
151) My boss has changed his mind. Now he doesn’t want to pay more than
10,000.so revoke that salary constraint.
SQL>alter table emp modify constraint chk_001 enable;
153) Oh! This column should be related to empno. Give a command to add this
constraint.
SQL>ALTER TABLE EMP ADD CONSTRAINT MGR_DEPT FOREIGN KEY(MGR)
REFERENCES
EMP(EMPNO)
155) This deptno column should be related to deptno column of dept table;
SQL>alter table emp add constraint dept_001 foreign key(deptno)
reference dept(deptno)
[deptno should be primary key]
157) Create table called as newemp. Using single command create this table
as well as get data into this table(use create table as);
SQL>create table newemp as select * from emp;
SQL>Create table called as newemp. This table should contain only
empno,ename,dname.
SQL>create table newemp as select empno,ename,dname from emp,dept where
1=2;
158) Delete the rows of employees who are working in the company for more
than 2 years.
SQL>delete from emp where (sysdate-hiredate)/365>2;
159) Provide a commission(10% Comm Of Sal) to employees who are not earning
any commission.
SQL>select sal*0.1 from emp where comm is null
161) Display employee name and department name for each employee.
SQL>select empno,dname from emp,dept where emp.deptno=dept.deptno
165) Display the department name and total number of employees in each
department.
SQL>select dname,count(ename) from emp,dept where
emp.deptno=dept.deptno group by dname;
166)Display the department name along with total salary in each department.
SQL>select dname,sum(sal) from emp,dept where emp.deptno=dept.deptno
group by dname;
167) Display itemname and total sales amount for each item.
SQL>select itemname,sum(amount) from item group by itemname;