Java Pastpapers 20-14 Mahnoor Shoukat
Java Pastpapers 20-14 Mahnoor Shoukat
Papers Of JAVA
2020-2014
Mahnoor Shoukat
Instructor Ma’am Rida
BCS 6th Semester
Question 1:
a. The output is :
num1 != num2
num3 ==num4
Question 2:
a. Dynamic Method Dispatch:
Dynamic method dispatch is the mechanism by which a call to an overridden function is
resolved at run time, rather than compile time. Dynamic method dispatch is important
because this is how Java implements run-time polymorphism
For example:
class A {
void callme() {
System.out.println("Inside A's callme method");
}
}
class B extends A {
void callme() {
System.out.println("Inside B's callme method");
}
}
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
A r; // obtain a reference of type A
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
}}
b. Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keeps both safe from outside interference and misuse.
Polymorphism
Polymorphism (from the Greek, meaning "many forms") is a feature that allows one interface
to be used for a general class of actions. The specific action is determined by the exact nature
of the situation.
c. Java
Java is an Objected-Oriented Programming Language developed by James Gosling at Sun
Microsystems (now acquired by the Oracle Corporation). In 1995. Java is platform
independent language.
JVM & its purpose and operations:
Byte code is a highly optimize set of instructions design to be executed by Java run time
system which is called Java Virtual Machine (JVM). JVM is an interpreter for byte code. Java
Virtual Machine is used as an abstraction between the OS and the Java programs.
Question 3:
a.
Sum of first 100 prime numbers:
import java.util.*;
public class sum {
public static void main(String[] args)
{
int sum = 1;
int ctr = 0;
int n = 0;
}
mean=sum/(n-1);
double deviation=Math.sqrt(mean);
System.out.println("Variance :"+deviation);
}
}
c. Not done yet
Question 6: Not done yet
January 2019
Question 2:
a.
The following are the important differences between print() and println().
Nature The prints method simply While println adds new line after
print text on the console print text on console.
2
and does not add any new
line.
Arguments print method works only println method works both with
with input parameter and without parameter and do not
3 passed otherwise in case throw any type of exception.
no argument is passed it
throws syntax exception.
b. Symbolic Constants
Symbolic constants in Java are named constants.
We use the final keyword so they cannot be reassigned a new value after being declared as
final.
They are symbolic because they are named. Here are a couple examples of symbolic
constant variables.
final int MAX_THREADS = 20;
final int MAX_USERS = 40;
final int MAX_SESSIONS = 50;
b. Abstract Class
There are situations in which you will want to define a superclass that declares the
structure of a given abstraction without providing a complete implementation of every
method.
That is, sometimes you will want to create a superclass that only defines a generalized
form that will be shared by all of its subclasses, leaving it to each subclass to fill in the
details.
Such a class determines the nature of the methods that the subclasses must implement.
Java provide abstract method to override all the necessary methods.
Abstract classes cannot be used to instantiate objects, they can be used to create object
references.
It must be possible to create a reference to an abstract class so that it can be used to
point to a subclass object.
Example
// A Simple demonstration of abstract.
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
}
}
c. Package And Its Uses in Java
Packages are containers for classes that are used to keep the class name space
compartmentalized. For example, a package allows you to create a class named List, which
you can store in your own package without concern that it will collide with some other class
named List stored elsewhere. Packages are stored in a hierarchical manner and are explicitly
imported into new class definitions.
A package in Java is used to group related classes. Think of it as a folder in a file directory.
We use packages to avoid name conflicts, and to write a better maintainable code.
Question 6:
a. Forms of Inheritance in Java
The following are the different forms of inheritance in java.
Specialization
Specification
Construction
Extension
Limitation
Combination
Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent
class. It holds the principle of substitutability.
Specification
This is another commonly used form of inheritance. In this form of inheritance, the
parent class just specifies which methods should be available to the child class but
doesn't implement them. The java provides concepts like abstract and interfaces to
support this form of inheritance. It holds the principle of substitutability. This is
supported in java by interfaces and abstract methods.
Construction
This is another form of inheritance where the child class may change the behavior
defined by the parent class (overriding). It does not hold the principle of
substitutability. Example: defining Stack as a subclass of Vector. This is not clean --
better to define Stack as having a field that holds a vector.
Extension
This is another form of inheritance where the child class may add its new properties.
It holds the principle of substitutability. In short Subclass adds new methods, and
perhaps redefines inherited ones as well.
Limitation
This is another form of inheritance where the subclass restricts the inherited behavior.
It does not hold the principle of substitutability. Example: defining Queue as a subclass
of Dequeue.
Combination
This is another form of inheritance where the subclass inherits properties from
multiple parent classes. Java does not support multiple inheritance type.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Multilevel Inheritance: When there is a chain of inheritance, it is known as multilevel
inheritance. As you can see in the example given below, BabyDog class inherits the Dog
class which again inherits the Animal class, so there is a multilevel inheritance. Multiple
Inheritance is not supported in java.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Hybrid Inheritance: Any combination of above three inheritance (single, hierarchical and
multi level) is called as hybrid inheritance.
Multipath Inheritance: Multiple inheritance is a method of inheritance in which
one derived class can inherit properties of base class in different paths. This inheritance
is not supported in .NET Languages such as C#.
Hierarchical Inheritance: When two or more classes inherits a single class, it is known
as hierarchical inheritance. In the example given below, Dog and Cat classes inherits the
Animal class, so there is hierarchical inheritance.
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Q) Why multiple inheritance is not supported in java? (Extra Question)
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B
classes. If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error
if you inherit 2 classes. So whether you have same method or different, there will be
compile time error.
class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were
b.
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the parent class
without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived class.
An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be altered by
the derived class
Costs of Inheritance
Inheritance decreases the execution speed due to the increased time and effort it takes, the
program to jump through all the levels of overloaded classes.
Inheritance makes the two classes (base and inherited class) get tightly coupled. This means
one cannot be used independently of each other.
The changes made in the parent class will affect the behavior of child class too.
The overuse of inheritance makes the program more complex.
Question 3:
a. Principles of OOP:
There are 4 major principles that make a language Object Oriented. These are Encapsulation,
Data Abstraction, Polymorphism and Inheritance. These are also called as four pillars of
Object Oriented Programming.
Encapsulation: Encapsulation is the mechanism that binds together code and the data it
manipulates, and keeps both safe from outside interference and misuse.
Abstraction: Abstract means a concept or an Idea which is not associated with any particular
instance.
Polymorphism: Polymorphism (from the Greek, meaning "many forms") is a feature that
allows one interface to be used for a general class of actions.
Inheritance: Inheritance is the process by which one object acquires the properties of another
object.
b. Inheritance
Inheritance is the process by which one object acquires the properties of another object. It
allows the creation of hierarchical classifications. In the terminology of Java, a class that is
inherited is called a superclass. The class that does the inheriting is called a subclass.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.
c. Polymorphism & its Types
It means one name many forms. It is further of two types — static and dynamic. Static
polymorphism is achieved using method overloading and dynamic polymorphism using
method overriding. It is closely related to inheritance. We can write a code that works on the
superclass, and it will work with any subclass type as well.
d. Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as a
method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of the method defined
by the superclass will be hidden.
No, we cannot override static methods because method overriding is based on dynamic
binding at runtime and the static methods are bonded using static binding at compile time.
So, we cannot override static methods.
Local Variable: A variable declared inside the body of the method is called local
variable. You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists. A local variable cannot be defined
with "static" keyword.
Instance Variable: A variable declared inside the class but outside the body of the
method, is called instance variable. It is not declared as static. It is called instance
variable because its value is instance specific and is not shared among instances.
Static Variable: A variable which is declared as static is called static variable. It cannot
be local. You can create a single copy of static variable and share among all the
instances of the class. Memory allocation for static variable happens only once when
the class is loaded in the memory.
Example:
class A{
int data=50;//instance variable
static int m=100;//static variable
void method(){
int n=90;//local variable
}
}//end of class
b.
The main differences between static and non static variables are:
Question 3:
a. Done in Jan 2020
b. Not done yet.
c. Constructors
A constructor initializes an object immediately upon creation. It has the same
name as the class in which it resides and is syntactically similar to a method. Once
defined, the constructor is automatically called immediately after the object is
created, before the new operator completes. Constructors look a little strange
because they have no return type, not even void. This is because the implicit return
type of a class' constructor is the class type itself. It is the constructor's job to
initialize the internal state of an object so that the code creating an instance will
have a fully initialized, usable object immediately.
Box mybox1 = new Box();
Box mybox2 = new Box();
Constructor OverLoading
Constructor overloading is a concept of having more than one constructor with
different parameters list, in such a way so that each constructor performs a
different task.
/* Here, Box defines three constructors to initialize the dimensions of a box
various ways. */
class Box {
double width;
double height;
double depth;
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1;
// box }
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
// compute and return volume
double volume() {
return width * height * depth;
}}
class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}}
d. Package
Packages are containers for classes that are used to keep the class name space
compartmentalized.
Benefits
Java package is used to categorize the classes and interfaces so that they can be
easily maintained.
Java package provides access protection.
Java package removes naming collision.
Question 4:
a. Not done yet.
b. Not done yet.
c. Not done yet
d. Already done Repeat Question in previous year.
Question 5: Not done yet.
July 2016
Question 1:
a. Difference between JIT & JVM
Just-In-Time Java-virtual-machine
A JIT is a code generator that converts A Java virtual machine (JVM) is a
Java bytecode into native machine virtual machine that enables a computer
code. to run Java programs as well as
programs written in other languages and
compiled to Java bytecode
Objective of JIT is to improve Main goal of JVM is to provide
performance of JVM, by compiling platform independence
more code into machine language.
JIT actually get invented to improve JVM is older concept than JIT.
performance of JVM.
Private: Private variables or methods may be used only by an instance of the same class
that declares the variable or method, a private feature may only be accessed by the class
that owns the feature.
Protected: Is available to all classes in the same package and also available to all subclasses
of the class that owns the protected feature.
b.
i. Inheritance: Already defined in previous year.
ii. Polymorphism: Already defined in previous year.
iii. Superclass: It is a class which gives a method or methods to a Java subclass. A Java
class may be either a subclass, a superclass, both, or neither! The Cat class in the
following example is the subclass and the Animal class is the superclass.
iv. Subclass: It is a class which inherits a method or methods from a Java superclass. A
Java class may be either a subclass, a superclass, both, or neither! The Cat class in the
following example is the subclass and the Animal class is the superclass.
Show, tell, smile: These methods are inherited and accessible from FunClass because
MorefunClass extends FunClass, and because these are in public FunClass.
MorefunClass also includes all the methods of java.lang.object because all classes extends
object.
Question 4:
a. Not done yet
b. Already done in previous year.
c. Not done yet.
d. Program to check duplicate string
public class DupStr {
public static void main (String args[])
{
String str = "mahnoor";
int cnt = 0;
char[] inp = str.toCharArray();
System.out.println("Duplicate Characters are:");
for (int i = 0; i<str.length(); i++)
{
for (int j = i + 1; j <str.length(); j++)
{
if (inp[i] == inp[j]) {
System.out.println(inp[j]); cnt++; break;
}
}
}
}
}
December 2015
Question 1:
a. Not done yet.
b.
i. Program to convert lower case string to upper case
public class changeCase {
public static void main(String[] args) {
String str1="MaHnooR";
StringBuffer newStr=new StringBuffer(str1);
if(ob1.equals(ob2))
System.out.println("Equal");
else
System.out.println("Not Equal");
}
}
c. String Class
The String class represents character strings. All string literals in Java programs, such as
"abc", are implemented as instances of this class. Strings are constant; their values cannot be
changed after they are created. Because String objects are immutable they can be shared.
Question 2:
a. Done in previous year.
b. Fibonacci series using for loop
public class fibo {
December 2014
Question 25: Not done yet.
Question 26: Not done yet.
Question 27:
a. ByteCode: The output of a Java compiler is not executable code. Rather, it is bytecode.
Bytecode is a highly optimized set of instructions designed to be executed by the Java run-
time system, which is called the Java Virtual Machine (JVM). That is, in its standard form,
the JVM is an interpreter for bytecode. Translating a Java program into bytecode helps makes
it much easier to run a program in a wide variety of environments.
b. Type Conversion: If the two types are compatible, then Java will perform the
conversion automatically. For example, it is always possible to assign an int value to a long
variable. However, not all types are compatible, and thus, not all type conversions are
implicitly allowed. For instance, there is no conversion defined from double to byte.
Fortunately, it is still possible to obtain a conversion between incompatible types. To do so,
you must use a cast, which performs an explicit conversion between incompatible types.
(target-type) value
int a;
byte b;
// ...
b = (byte) a;
c. Two Jump Statement: Already done in a previous year
d. Not done yet.
Advantages of Function in Program
There are many advantages in using functions in a program they are:
It makes possible top down modular programming. In this style of programming, the high level logic
of the overall problem is solved first while the details of each lower level functions is
addressed later.
The length of the source program can be reduced by using functions at appropriate places.
It becomes uncomplicated to locate and separate a faulty function for further study.
A function may be used later by many other programs this means that a c programmer can use function
written by others, instead of starting over from scratch.
A function can be used to keep away from rewriting the same block of codes which we are going use two
or more locations in a program. This is especially useful if the code involved is long or complicated.