0% found this document useful (0 votes)
17 views36 pages

Java Pastpapers 20-14 Mahnoor Shoukat

The document contains solved past papers of Java from 2014 to 2020, covering various topics such as dynamic method dispatch, encapsulation, polymorphism, and features of Java programming. It includes code examples for concepts like factorial calculation, mean and variance, and inheritance types, along with explanations of abstract classes and packages. Additionally, it discusses the differences between print() and println() methods, symbolic constants, and the benefits and costs of inheritance.

Uploaded by

Mahnoor shoukat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
17 views36 pages

Java Pastpapers 20-14 Mahnoor Shoukat

The document contains solved past papers of Java from 2014 to 2020, covering various topics such as dynamic method dispatch, encapsulation, polymorphism, and features of Java programming. It includes code examples for concepts like factorial calculation, mean and variance, and inheritance types, along with explanations of abstract classes and packages. Additionally, it discusses the differences between print() and println() methods, symbolic constants, and the benefits and costs of inheritance.

Uploaded by

Mahnoor shoukat
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

12/9/2020 Solved Past

Papers Of JAVA
2020-2014

Mahnoor Shoukat
Instructor Ma’am Rida
BCS 6th Semester
Question 1:
a. The output is :
num1 != num2
num3 ==num4

b. The output is:


12

c. There is no output. Error will appear in line 4.

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;

while (ctr < 100) {


n++;
if (n % 2 != 0) {
// check if the number is even
if (is_Prime(n)) {
sum += n;
}
}
ctr++;
}
System.out.println("\nSum of the prime numbers till 100: "+sum);
}
public static boolean is_Prime(int n) {
for (int i = 3; i * i <= n; i+= 2) {
if (n % i == 0) {
return false;
}
}
return true;
}}
b. Not done yet!
c. Features of java programming
Platform Independent
Unlike many other programming languages including C and C++, when Java is compiled,
it is not compiled into platform specific machine, rather into platform-independent byte
code. This byte code is distributed over the web and interpreted by the Virtual Machine
(JVM) on whichever platform it is being run on.
Simple
Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it
would be easy to master.
Secure
With Java's secure feature it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
Architecture-neutral
Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime system.
Portable
Being architecture-neutral and having no implementation dependent aspects of the
specification makes Java portable. The compiler in Java is written in ANSI C with a clean
portability boundary, which is a POSIX subset.
Robust
Java makes an effort to eliminate error-prone situations by emphasizing mainly on
compile time error checking and runtime checking.
Multithreaded
With Java's multithreaded feature it is possible to write programs that can perform many
tasks simultaneously. This design feature allows the developers to construct interactive
applications that can run smoothly.
Interpreted
Java byte code is translated on the fly to native machine instructions and is not stored
anywhere. The development process is more rapid and analytical since the linking is an
incremental and light-weight process.
High Performance
With the use of Just-In-Time compilers, Java enables high performance.
Distributed
Java is designed for the distributed environment of the internet.
Dynamic
Java is considered to be more dynamic than C or C++ since it is designed to adapt to an
evolving environment. Java programs can carry an extensive amount of run-time
information that can be used to verify and resolve accesses to objects at run-time.

Difference between Abstract class and Interface

Question 4: Not done yet


Question 5:
a. Factorial Program
class Factorial{
public static void main(String[] args){
int n, cn, fact;
Scanner sc= new Scanner(System.in);
System.out.print(“Enter number”);
n=sc.nextInt();
System.out.println(“Factorial of number is” + n);
for(int i =1; i<=n; i++){
cn=i;
fact=1;
for(int j=1;j<=cn:j++){
fact =fact*j;
}
System.out.print(cn,fact);
}
}
}

b. There is no output, an error will appear in line 5


The program for mean and variance
class MeanAndVariance
{
public static void main(String args[])
{
double[] input={5,10,15,20,25};
double n=5,sum=0,mean;
for(int i=0;i<n;i++)
{
sum=sum+input[i];
}
mean=sum/n;
System.out.println("Mean :"+mean);
sum=0;
for(int i=0;i<n;i++)
{
sum+=Math.pow((input[i]-mean),2);

}
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().

Sr. Key print() println()


No.

Implementation print method is On the other hand, println


implemented as it prints method is implemented as prints
the text on the console the text on the console and the
1 and the cursor remains at cursor remains at the start of the
the end of the text at the next line at the console and the
console. next printing takes place from next
line.

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;

c. Not done yet


d. Not done yet
Question 3: Not done yet
Question 4:
a. Not done yet

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.

d. Not done yet.

Question 5: Not done yet.

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.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical. In java programming, multiple and hybrid inheritance is supported through
interface only.

 Single Inheritance: When a class inherits another class, it is known as a single


inheritance. In the example given below, Dog class inherits the Animal class, so there is
the single inheritance.

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

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}

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.

c. Not done yet.


d. Not done yet.
Question 7:
a. Not done yet.
b. Difference Between Multitasking and Multithreading
Multitasking Multithreading
In multitasking, several programs are In multi-threading multiple threads execute
executed concurrently e.g. Java compiler either same or different part of program
and a Java IDE like NetBeans or Eclipse. multiple times at the same time.

In multi-tasking, CPU switches between In multi-threading CPU switches between


multiple programs to complete their multiple threads of the same program
execution in real time

Process are heavyweight as compared to Inter-process communication is expensive


threads, they require their own address and limited and context switching from one
space, which means multi-tasking is heavy process to another is expensive and limited.
compared to multithreading.

c. Not done yet


d. Not done yet.
Question 2:
a. DataTypes in Java
Java defines eight simple (or elemental) types of data: byte, short, int, long, char, float,
double, and boolean. These can be put in four groups:
Integers:
Java defines four integer types: byte, short, int, and long. All of these are signed,
positive and negative values. Java does not support unsigned, positive-only integers.
i. Byte: Java defines four integer types: byte, short, int, and long. All of these are
signed, positive and negative values. Java does not support unsigned, positive-
only integers. Byte variables are declared by use of the byte keyword.
byte b,c;
ii. Short: short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is
probably the least-used Java type, since it is defined as having its high byte first
(called big-endian format).
Short a;
iii. Int: The most commonly used integer type is int. It is a signed 32-bit type that
has a range from –2,147,483,648 to 2,147,483,647. In addition to other uses,
variables of type int are commonly employed to control loops and to index
arrays. Any time you have an integer expression involving bytes, shorts, ints,
and literal numbers, the entire expression is promoted to int before the
calculation is done.
iv. Long: long is a signed 64-bit type and is useful for those occasions where an int
type is not large enough to hold the desired value. The range of a long is quite
large. This makes it useful when big, whole numbers are needed
Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
i. Float: The type float specifies a single-precision value that uses 32 bits of
storage. Single precision is faster on some processors and takes half as much
space as double precision, but will become imprecise when the values are either
very large or very small. Variables of type float are useful when you need a
fractional component, but don't require a large degree of precision.
ii. Double: Double precision, as denoted by the double keyword, uses 64 bits to
store a value. Double precision is actually faster than single precision on some
modern processors that have been optimized for high-speed mathematical
calculations.
Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean: This group includes boolean, which is a special type for representing
true/false values.
b. Break:
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third,
it can be used as a "civilized" form of goto.

c. Ways to define arrays:


i. type[ ] var-name;
ii. type var-name[ ];
iii. array-var = new type[size];
iv. array-var[] = { any element or data to be stored in array}
d. Difference between array and link list
Array Linklist
An array is the data structure that The Linked list is considered as a non-
contains a collection of similar type data primitive data structure contains a
elements collection of unordered linked elements
known as nodes.
In the array the elements belong to In a linked list though, you have to start
indexes, i.e., if you want to get into the from the head and work your way
fourth element you have to write the through until you get to the fourth
variable name with its index or location element
within the square bracket
Accessing an element in an array is fast Linked list takes linear time, so it is quite
a bit slower.
Operations like insertion and deletion in On the other hand, the performance of
arrays consume a lot of time these operations in Linked lists are fast.
Arrays are of fixed size Linked lists are dynamic and flexible and
can expand and contract its size.
In an array, memory is assigned during In a Linked list it is allocated during
compile time execution or runtime.
Elements are stored consecutively in Elements are stored randomly in Linked
arrays lists.
The requirement of memory is less due There is a need for more memory in
to actual data being stored within the Linked Lists due to storage of additional
index in the array next and previous referencing elements.
In addition memory utilization is Memory utilization is efficient in the
inefficient in the array. linked list

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.

Question 4: Not done yet.


Question 5: Not done yet.
Question 6: Not done yet.
Question 2:
a. Java Variables
There are three types of variable in java
i. Local variable
ii. Instance variable
iii. Static variable

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:

STATIC VARIABLE NON STATIC VARIABLE


Static variables can be accessed using Non static variables can be accessed using instance of
class name a class
Static variables can be accessed by Non static variables cannot be accessed inside a static
static and non static methods method.
Static variables reduce the amount of Non static variables do not reduce the amount of
memory used by a program. memory used by a program
STATIC VARIABLE NON STATIC VARIABLE
Static variables are shared among all Non static variables are specific to that instance of a
instances of a class. class.
Static variable is like a global variable Non static variable is like a local variable and they can
and is available to all methods. be accessed through only instance of a class.

c. Declaration and Initialization of array


Done in Jan 18
Convert a string into a character array
Step 1:Get the string.
Step 2:Create a character array of same length as of string.
Step 3:Store the array return by toCharArray() method.
Step 4:Return or perform operation on character array.

// Java program to Convert a String


// to a Character array using toCharArray()
import java.util.*;
public class GFG {
public static void main(String args[])
{
String str = "Mahnoor";
// Creating array and Storing the array
// returned by toCharArray()
char[] ch = str.toCharArray();
// Printing array
for (char c : ch) {
System.out.println(c);
}}}
d. Done in jan 18.

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.

b. Uses & Purpose of Garbage Collection


Every time you create an Object memory is allocated from your computers f to store that
object. If you never got rid of these objects then your program would use more and more
memory as the more it allocated objects.
Java therefore contains a garbage collector. This is an automatic memory management
system that detects when objects are no longer necessary and removes them. It does this
by checking if there is anyway the programmer could get a reference to that object. If
there are no accessible references to the object left the garbage collector marks the object
as trash and deallocates it at the next opportunity.
c. Significance of Public, Private & Protected
Public: Public class is visible in other packages, field is visible everywhere (class must be
public too)

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.

The effect of package relationships on declared items qualified by these modifiers


This access is provided even to subclasses that reside in a different package from the class
that owns the protected feature. What you get by default i.e., without any access modifier
(i.e. public private or protected). It means that it is visible to all within a particular
package.
Question 2:
a.
Question: Class Object
I. Department of computer University of Department of computer
science and university of Karachi. science.
Karachi.
II. Mickey Mouse and rodent. Rodent. Mickey Mouse.

III. Author and William Author. William Shakespeare.


Shakespeare.
IV. Sports and football. Sports. Football.

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.

v. Abstract Class: Already defined in previous year.

c. Two ways to create Polymorphism


Java supports 2 types of polymorphism:
1) Static or compile-time.
In Java, static polymorphism is achieved through method overloading. Method overloading
means there are several methods present in a class having the same name but different
types/order/number of parameters.
At compile time, Java knows which method to invoke by checking the method signatures.
So, this is called compile time polymorphism or static binding
2) Dynamic Method dispatch or run-time:
Dynamic Method Dispatch or Runtime Polymorphism in Java. Method overriding is one of
the ways in which Java supports Runtime Polymorphism. Dynamic method dispatch is the
mechanism by which a call to an overridden method is resolved at run time, rather than
compile time. Thus, this determination is made at run time.
Question 3:
a. The java Statement that creates the subclass by inheritance is:
Class MorefunClass extends FunClass{}

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.

b. Program of positive & negative


import java.util.Scanner;
public class Postive_Negative
{
public static void main (String [] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter the number you want to check:");
n =s.nextInt();
if(n >0)
{ System.out.println("The given number "+n+" is Positive");
}
elseif(n <0)
{
System.out.println("The given number "+n+" is Negative");
}
else
{ System.out.println("The given number "+n+" is Zero ");} } }

c. Expression which represents the floating-point constant two thirds.

2/3 Or (double)2/3 Or 2.0/3.0

d. Java code for mathematical expression


(Math.pow(x,2) + 2) / (3*y - 5).

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);

for(int i = 0; i < str1.length(); i++) {

//Checks for lower case character


if(Character.isLowerCase(str1.charAt(i))) {
//Convert it into upper case using toUpperCase() function
newStr.setCharAt(i, Character.toUpperCase(str1.charAt(i)));
}
//Checks for upper case character
else if(Character.isUpperCase(str1.charAt(i))) {
//Convert it into upper case using toLowerCase() function
newStr.setCharAt(i, Character.toLowerCase(str1.charAt(i)));
}
}
System.out.println("String after case conversion : " + newStr);
}
}
ii. Program to compare two strings
public class CompareStrings {

public static void main(String[] args) {

String ob1 = "Mahnoor";


String ob2 = "Shoukat";

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 {

public static void main(String[] args) {

int count = 7, num1 = 0, num2 = 1;


System.out.print("Fibonacci Series of "+count+" numbers:");

for (int i = 1; i <= count; ++i)


{
System.out.print(num1+" ");

/* On each iteration, we are assigning second number


* to the first number and assigning the sum of last two
* numbers to the second number
*/
int sumOfPrevTwo = num1 + num2;
num1 = num2;
num2 = sumOfPrevTwo;
}
}
}
c. Break Statement:
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used
as a "civilized" form of goto.
Continue Statement:
Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue
running the loop, but stop processing the remainder of the code in its body for this particular
iteration. This is, in effect, a goto just past the body of the loop, to the loop's end. The
continue statement performs such an action.
Question 3:
a. Method Overloading
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the
methods are said to be overloaded, and the process is referred to as method overloading.
Method overloading is one of the ways that Java implements polymorphism.
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.
b. Not done yet.
c. Not done yet.

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.

You might also like