Sunteți pe pagina 1din 34

Java Advanced Solved Assignments (3415) AIOU Spring 2018

ALLAMA IQBAL OPEN UNIVERSITY, ISLAMABAD


(Department of Computer Science)

SOLUTIONS
1. HEY THIS IS SOLUTIONS OF ASSIGNMENTS.
2. FEEL FREE SHARING THIS.
3. THE 4TH LINE IS FUNNY.
4. SUBMITTING ASSIGNMENT(S) BORROWED OR STOLEN FROM
OTHER(S) AS ONE’S OWN WILL BE NOT PENALIZED AS DEFINED IN
“AIOU STUDENTS PLAGIARISM POLICY”.
Course: Programming Language-III (3415) Semester: Spring, 2018
Level: Bachelor Pass Marks: 50

Assignment No.1
(Units 1-4)

Note: All Questions carry equal marks.

Q.1 (a)

Elaborate the principal concepts of application Java


programming.
Discuss the usage of comments in Java applications?

ANSWER
(A)
Java Application Programming

A Java program that runs stand-alone in a client or server. The


Java Virtual Machine interprets the instructions, and like any
programming language running in its native environment, Java
programs have full access to all the resources in the computer.

List of OOP Concepts in Java

There are four main OOP concepts in Java. These are:

1
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Abstraction. Abstraction means using simple things to represent


complexity. We all know how to turn the TV on, but we don’t
need to know how it works in order to enjoy it. In Java,
abstraction means simple things like objects, classes,
and variables represent more complex underlying code and
data. This is important because it lets avoid repeating the same
work multiple times.

Encapsulation. is the practice of keeping fields within a class


private, then providing access to them via public methods. It’s a
protective barrier that keeps the data and code safe within the
class itself. This way, we can re-use objects like code components
or variables without allowing open access to the data system-
wide.

Inheritance. This is a special feature of Object Oriented


Programming in Java. It lets programmers create new classes
that share some of the attributes of existing classes. This lets us
build on previous work without reinventing the wheel.

Polymorphism. This Java OOP concept lets programmers use


the same word to mean different things in different contexts. One
form of polymorphism in Java is method overloading. That’s
when different meanings are implied by the code itself. The other
form is method overriding. That’s when the different meanings
are implied by the values of the supplied variables.

Use of Comments in Java Applications

2
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

It's good practice to get into the habit of putting Java comments
into your source code to enhance its readability and clarity for
yourself and other programmers. It isn't always instantly clear
what a section of Java code is performing. A few explanatory lines
can drastically reduce the amount of time it takes to understand
the code.

Q.1 (b)
Describe the fundamentals of data types used in java with
examples.
ANSWER

Fundamentals of Data Types in Java

Data types specify the different sizes and values that can be
stored in the variable. There are two types of data types in Java:
1. Primitive data types: The primitive data types include
Integer, Character, Boolean, and Floating Point.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of


data manipulation. These are the most basic data types available
in Java language.

There are 8 types of primitive data types:

 Boolean data type


 byte data type
 char data type
 short data type

3
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

 int data type


 long data type
 float data type
 double data type

Java Non Primitive Data Types

Q.2 (a)

What is repetition control flow in programming? Also


explain different types of loops used in Java Language.

ANSWER:

4
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Repetition Control Flow

 Repetition control flows are called loops, and are used to


repeat the same code multiple times in succession.
 The number of repetitions is based on criteria defined in the
loop structure, usually a true/false expression.
 The three loop structures in Java are:
o while loops
o do-while loops
o for loops
 Three types of loops are not actually needed, but having the
different forms is convenient.

While Loop

A while loop statement in Java programming language


repeatedly executes a target statement as long as a given
condition is true.

Syntax
The syntax of a while loop is −

while (Boolean_expression) {
// Statements
}

Flow Diagram

5
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Do While Loop

The do...while loop is similar to while loop with one key difference.
The body of do...while loop is executed for once before the test
expression is checked.

Syntax

do {

// codes inside body of do while loop

} while (testExpression);

Flow Diagram

6
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

For Loop
A for loop is a repetition control structure that allows you to
efficiently write a loop that needs to be executed a specific
number of times.
A for loop is useful when you know how many times a task is to
be repeated.
Syntax
The syntax of a for loop is −

for (initialization; Boolean_expression; increment/decrement)


{
// Statements
}

Flow Diagram

7
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Q.2 (b)

Discuss the switch flow control repetition with examples.

ANSWER:

Switch Flow Control

A switch statement allows a variable to be tested for equality


against a list of values. Each value is called a case, and the
variable being switched on is checked for each case.

Syntax

8
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

switch (expression) {
case value:
// Statements
break; // optional

case value:
// Statements
break; // optional

// You can have any number of case statements.


default: //optional
// Statements
}
Programming Example 1

9
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Output: Well done

Programming Example 2
class SwitchBoard{
public static void main(String args[]){
int iSwitch=4;
switch(iSwitch){
case 0:
System.out.println("ZERO");
break;

case 1:
System.out.println("ONE");
break;

case 2:
System.out.println("TWO");
break;

case 3:
System.out.println("THREE");
break;

case 4:
System.out.println("FOUR");
break;

default:
System.out.println("Not in the list");
break;
}
}
}

Output:
FOUR

10
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Q.3
Write Java statements to accomplish each of the following:

(a)
Display the value of the seventh element of character
array.

ANSWER
Statement:

System.out.println ("7th Element:"+a[6]);

(b)
Total the elements of floating-point array c of 100
elements.
ANSWER
Statements:
for (int k = 0; k < 100; k++)
{
total += c[k] ;
// assume total is declared and initialized // to 0

System.out.println ( + c[k] );
}
System.out.println ( "Total is " +total );

(c)

Copy 11-element array A into the first portion of array B,


containing 34 elements.

ANSWER

11
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Statements:
double[] a = new double[11];
double[] b = new double[34]; (d)
for (int i = 0; i <= 10; i++)
Determine and print
b[i] the smallest and largest values
= a[i];
contained in 99-element floating-point array w.

(d)

Determine and print the smallest and largest values


contained in 99-element floating-point array w.

ANSWER
Statement:

// assume all variables declared and initialized


// in particular, initialize smallest to w[0]

for (int j = 0; j < 99; j++)


{
if (w[j] < smallest)
smallest = w[j];
if (w[j] > largest)
largest = w[j];
}
System.out.println( "Largest value is " +largest );
System.out.println( "Smallest value is " +smallest );

Q No.4
The factorial of a non-negative integer n is written n!
(Pronounced “n factorial”) and is defined as follows:
n! = n (n-1) (n-2)… 1 (for values of n greater than or
equal to 1) and n! = 1 (for n = 0).
For example, 5! = 5.4.3.2.1, which is 120.

12
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

(a)
Write an application that reads a nonnegative integer from
an input dialog and computes and prints its factorial.

ANSWER
Program Code:

import java.util.Scanner;
public class Zee2
{
public static void main(String []args)
{
Scanner input = new Scanner(System.in);
int nonNegative;
int count = 1;
int factor = 1;
System.out.println("Input a nonnegative integer: ");
nonNegative = input.nextInt();

while (nonNegative < 0)


{
System.out.println("Enter a positive integer");
nonNegative = input.nextInt();
}
if (nonNegative > 0)

{
while (count <= nonNegative)
{
factor = factor * count;
count++;

}
System.out.println("The factorial of the nonnegative
number is " + factor);
}
}
} (b)
Write an application that estimates the value of the
mathematical constant e by using the formula
1 1 1
e  1    ...
1! 2! 3!

13
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

ANSWER
Program Code:

public class euler {


public static void main(String args[])
{
double e = 1;

for(int x = 1; x < 18; x++)


{
e = e + 1 / (double) factorial (x);
}
System.out.println("e: "+ e);

public static double factorial (int n) {


int x;

if(n < 1)
{
return 0;
}
else
{
if(n == 1)
{
return 1;
}
else if(n > 1)
{
return n * fictorial(n-1);
}
}
return 0;
}
}

Q No 5

Differentiate between following:

14
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

A) References and reference parameter

ANSWER
References

A reference is an address that indicates where an object's


variables and methods are stored.
Reference variables are used to refer to an object. They are
declared with a specific type which cannot be changed.

Reference in java means that you should only point any


variable. Memory is not allocated unless you define a object. It
only means pointing to something.

Reference Parameter

The "type" of data that a method can receive is referred to as


a "parameter".

The mechanism used to pass parameters to a procedure


(subroutine) or function. The most common methods are to
pass the value of the actual parameter (call by value), or to
pass the address of the memory location where the actual
parameter is stored (call by reference). The latter method
allows the procedure to change the value of the parameter,
whereas the former method guarantees that the procedure will
not change the value of the parameter.

(b)

Single subscripted array and multiple subscripted arrays

ANSWER

Single Subscripted Array

15
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

It is made out of a contiguous block of memory that is divided


into a number of “slots” or variable. Each slot can be accessed
by using its index (or subscript). An array that uses a single
subscript is called a one dimensional array. Each element is
accessed using single subscript.

Syntax:

int arr[]=new arr[2];

Multiple Subscripted Arrays

Arrays that require two subscripts to identify a particular


element are called double subscripted arrays. It requires two
pair of square brackets.

A multiple subscripted array can be initialized in its declaration


much like a single subscripted array.

Syntax:

int arr[][]=new arr[2][3];

(c)

Third element of array and array element 3.

ANSWER

Illustration:

Array element 3 means arr[0], arr[1], arr[2], arr[3] ----- 4th


index/element but array element number 3

3rd element of array means arr[0], arr[1], arr[2] ------ 3rd


index/element but array element number 2

(d)

16
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Applet and Application

End of 1 Assignment st

17
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

ASSIGNMENT NO.2
Question No 1

Distinguish between inheriting interface and inheriting


implementation. How do inheritance hierarchies designed
for inheriting interface differ from those designed for
inheriting implementation?

ANSWER

Inheriting Interface Vs Inheriting Implementation

Inheriting Interface

 Interface Inheritance is called Type Inheritance also


called as sub typing.
 Interfaces can contain only constants and method
signatures, but no implementation.
 Interface Inheritance is achieved in Java by using
the implements keyword.
 Interfaces cannot be instantiated. They can only be
implemented by an implementing class or extended by
another interface.
 Interface inheritance promotes the design concept
of program to interfaces not to implementations.
 A class that implements an interface must provide
implementation to all the methods that are declared in the
interface.
 Interface inheritance reduces coupling and implementation
dependencies. You can use inheritance between unrelated
classes but has set of common methods.

18
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

 Interfaces can be used as reference type for the object of an


implementing class.
 An interface can be extended by another interface.

Inheriting Implementation

 Implementation Inheritance is called Class Inheritance.


 Implementation Inheritance is achieved in Java by using
the extends keyword.
 The class whose features are inherited is known as super
class (or a base class or a parent class).
 The class that inherits the other class is known as sub class
(or a derived class, extended class, or child class). The
subclass can add its own fields and methods in addition to
the superclass fields and methods.
 Inheritance supports the concept of “reusability”, i.e. when
we want to create a new class and there is already a class
that includes some of the code that we want, we can derive
our new class from the existing class. By doing this, we are
reusing the fields and methods of the existing class.
 In this inheritance, the subclass is tightly coupled with
superclass.
 Any changes to superclass will break the whole
relationship. Make sure that the subclasses depend only on
the behavior of the superclass, not on the actual
implementation.

Inheriting Interface Hierarchy Vs Inheriting


Implementation Hierarchy

Hierarchies designed for implementation inheritance tend to


define their functionality high in the hierarchy—each new derived
class inherits one or more methods that were declared in a base

19
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

class, and the derived class uses the base class implementations
(sometimes overriding the base class methods and calling them
as part of the derived class implementations). Hierarchies
designed for interface inheritance tend to have their functionality
defined lower in the hierarchy—a base class specifies one or more
abstract methods that must be declared for each class in the
hierarchy, and the individual derived classes override these
methods to provide derived-class-specific implementations.

Q.2 (a)
What are packages in Java? Briefly describe the Java API
packages.
ANSWER
Packages in Java

A package as the name suggests is a pack (group) of classes,


interfaces and other packages. In java we use packages to
organize our classes and interfaces. We have two types of
packages in Java: built-in packages and the packages we can
create (also known as user defined package).

There are many built-in packages such as java, lang, awt, javax,
swing, net, io, util, sql etc.

20
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Java API packages

Java APl (Application Program Interface) provides a large


numbers of classes grouped into different packages according to
functionality. Most of the time we use the packages available with
the Java API. Following figure shows the system packages that
are frequently used in the programs.

Java System Packages and Their Classes

java.lang Language support classes. They include classes for


primitive types, string, math functions, thread and exceptions.

java.util Language utility classes such as vectors, hash tables,


random numbers, data, etc.

java.io Input/output support classes. They provide facilities for


the input and output of data.

java.applet Classes for creating and implementing applets.

java.net Classes for networking. They include classes for


communicating with local computers as well as with internet
servers.

java.awt Set of classes for implementing graphical user


interface. They include classes for windows, buttons, lists, menus
and so on.

21
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Q.2 (b)

Discuss why casting a super class reference to a subclass


reference is potentially dangerous?

ANSWER

Casting is there to tell the compiler “I know what I’m doing, you
can trust me!” But if your code does something invalid as a
result, you risk blowing something up at runtime instead of
catching it as an error during compilation, which is a safer time to
find your problems.

So let’s think for a minute about what it means to cast a parent


class reference to one of its subclasses. Subclasses are there to
inherit all of the state and behaviors of the parents, but they add
additional state and behavior through more variables and
methods than what the parent provided. So to use a common
example, all Vehicles may have a move() method, but only a Car
knows how to drive(). (Bicycles can only pedal()). So when I cast
my Vehicle to a Car, I’m telling the compiler “It’s OK, don’t barf
when I call the drive() method on this Vehicle.” And the compiler
says, “OK, sure, hope you know what you’re doing…”. When you
run your program, the method call to drive() comes around on
your casted object, and one of two things will happen- either
you’re lucky and the Vehicle actually is a Car and the method call
succeeds, or the Vehicle is actually a Bicycle, or just a Vehicle, or
maybe a Rocket. Then the program has no choice but to crash,
because the method doesn’t exist on that object and has nowhere
to go: Invalid Cast Exception.

22
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Q.3 (a)

Distinguish between non-abstract methods and abstract


methods.
ANSWER
Abstract Methods

A method without body (no implementation) is known as abstract


method. A method must always be declared in an abstract class.

1. Abstract methods don’t have body, they just have method


signature as shown above.
2. If a class has an abstract method it should be declared
abstract, the vice versa is not true, which means an abstract
class doesn’t need to have an abstract method compulsory.
3. If a regular class extends an abstract class, then the class
must have to implement all the abstract methods of abstract
parent class or it has to be declared abstract as well.

Non-Abstract Methods

Non abstract methods are also known as Concrete method.


Concrete method is also a method that is common in many
objects but this method has same implementation for all the
objects.

When a non-abstract class implements an abstract class, all the


non-abstract members of the abstract class are simply inherited
and these methods can be accessed as of any child class would
access the parent class methods.

Q.3 (b)

Create a class Rectangle. The class has attributes length


and width, each of which defaults to 1. It has method that
calculates the perimeter and the area of the rectangle. It

23
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

has set and get methods for both length and width. The set
methods should verify that length and width are each
floating-point number larger than 0.0 and less than 20.0.

ANSWER

Program Code:

Rectangle1 Class:
package rectangle1;

public class Rectangle1

private double length = 1;

private double width = 1;

public float perimeter;

public float area;

public Rectangle1()

setLength(1);

setWidth(1);

public Rectangle1(double iLen, double iWid)

setLength(iLen);

setWidth(iWid);

24
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

public void setLength(double len)

if(len > 0 && len < 20)

length = len;

public void setWidth(double wid)

if(wid > 0 && wid < 20)

width = wid;

public void Perimeter(float perimeter){

perimeter = (float) ((float) (length *2) + (width *2));

public float getPerimeter(){

perimeter = (float) ((float) (length *2) + (width *2));

return perimeter;

public void setArea(float area){

area = (float) (length * width);

public float getArea(){

area = (float) (length * width);

25
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

return area;

public double getLength()

return length;

public double getWidth()

return width;

RectangleTest (Main Class):

package rectangle1;

public class RectangleTest

public static void main(String[] args)

Rectangle1 r1 = new Rectangle1(15, 19);

System.out.println("Rectangle 1");

System.out.printf("Length: %.2f\n", r1.getLength());

System.out.printf("Width: %.2f\n", r1.getWidth());

System.out.printf("Perimeter: %.2f\n",r1.getPerimeter());

System.out.printf("Area: %.2f\n",r1.getArea());

26
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

System.out.println();

System.out.println();

Rectangle1 r2 = new Rectangle1(2, 8);

System.out.println("Rectangle 2");

System.out.printf("Length: %.2f\n", r2.getLength());

System.out.printf("Width: %.2f\n", r2.getWidth());

System.out.printf("Perimeter: %.2f\n",r2.getPerimeter());

System.out.printf("Area: %.2f\n",r2.getArea());

System.out.println();

System.out.println();

Rectangle1 r3 = new Rectangle1();

System.out.println("Rectangle 3");

System.out.printf("Length: %.2f\n", r3.getLength());

System.out.printf("Width: %.2f\n", r3.getWidth());

System.out.printf("Perimeter: %.2f\n",r3.getPerimeter());

System.out.printf("Area: %.2f\n",r3.getArea());

Output:

Rectangle 1

Length: 15.00

Width: 19.00

Perimeter: 68.00

27
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Area: 285.00

Rectangle 2

Length: 2.00

Width: 8.00

Perimeter: 20.00

Area: 16.00

Rectangle 3

Length: 1.00

Width: 1.00

Perimeter: 4.00

Area: 1.00

Q.4 (a)

What is polymorphism? Describe the role of dynamic


method binding in polymorphism.

ANSWER

Polymorphism

The word ‘polymorphism’ literally means ‘a state of having many


shapes’ or ‘the capacity to take on different forms’. When applied
to object oriented programming languages like Java, it describes

28
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

a language’s ability to process objects of various types and


classes through a single, uniform interface.

Polymorphism in Java has two types: Compile time polymorphism


(static binding) and Runtime polymorphism (dynamic binding).
Method overloading is an example of static polymorphism, while
method overriding is an example of dynamic polymorphism.

Role of dynamic method binding in Polymorphism

Dynamic Polymorphism (Runtime Polymorphism)

 Dynamic Polymorphism decides which method to execute in


runtime.
 Method Overriding is an example of dynamic polymorphism,
and it is required to happen dynamic polymorphism.
 Dynamic Polymorphism achieved through dynamic binding.
 Dynamic Polymorphism happens between different classes.
 It is required where a subclass object is assigned to super
class object for dynamic polymorphism.
 Inheritance involved for dynamic polymorphism.

At run time, Java waits until runtime to determine which


object is actually being pointed to by the reference. Method
resolution was taken at runtime, due to that we call as run
time polymorphism.

Q.4 (b)

Write an application that uses String method compareTo to


compare two strings input by the user. Output whether the
first string is less than, equal to or greater than the
second.

Program Code

29
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

30
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Q.5

Write a note on each of the following

a) This Reference

b) Protected Members

c) Dynamic Method Binding

d) Exception Types

ANSWER

This Reference

Keyword THIS is a reference variable in Java that refers to the


current object.

The various usages of 'THIS' keyword in Java are as follows:

 It can be used to refer instance variable of current class


 It can be used to invoke or initiate current class constructor
 It can be passed as an argument in the method call
 It can be passed as argument in the constructor call
 It can be used to return the current class instance

Protected Members

Protected is one of the access modifiers keyword in Java;


applicable to variables, methods in a class. Accessible within the
same class it is declared inside. Accessible to the sub classes
regardless of the package; also to the non-subclass (es) within
the same package, but not to the non-subclass (s) of the other
package (s).

A protected variable is a variable that can be accessed in 3 ways:

31
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

1. Internally to the class

2. A sub class of the class declaring the protected variable

3. A class in the same package as the class with the class with
declared variable.

Dynamic Method Binding

When compiler is not able to resolve the call/binding at compile


time, such binding is known as Dynamic or late binding. Method
Overriding is a perfect example of dynamic binding as in
overriding both parent and child classes have same method and
in this case the type of the object determines which method is
to be executed. The type of object is determined at the run time
so this is known as dynamic binding.

Exception Types

There are two types of exceptions in Java:

1) Built-in Exceptions

2) User defined Exceptions

Built-in Exceptions

Built-in exceptions are the exceptions which are available in Java


libraries. These exceptions are suitable to explain certain error
situations. Below is the list of important built-in exceptions in
Java.

 Arithmetic Exception
 ArrayIndexOutOfBoundException
 ClassNotFoundException
 FileNotFoundException
 IOException
 InterruptedException

32
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

 NoSuchFieldException
 NoSuchMethodException
 NullPointerException
 NumberFormatException
 RuntimeException
 StringIndexOutOfBoundsException
User Defined Exceptions

In Java, we can create our own exception class specific to our


application or program. Such kinds of exceptions are known as
user defined exception or custom exception. To create our own
exception class, we must inherit exception class so that our
exception class becomes the part of exception hierarchy.

User Defined Exception by extending Exception class

class myException1 extends Exception


{

public String toString()


{
return "User-Defined Exception";
}

public static void main(String... ar)


{
myException1 ob = new myException1();

try
{
throw new myException1();
}
catch(myException1 e)
{
System.out.println ("Exception handled - "+ e);
}

33
Prepared By: Zee K
Java Advanced Solved Assignments (3415) AIOU Spring 2018

Any suggestions…

Feel free to contact

E-mail: zeeshanalikhan98@gmail.com

(‫)خوند واخلئ‬
https://translate.google.com/#en/ps/enjoy

34
Prepared By: Zee K

S-ar putea să vă placă și