OOPS Finale Assignment 1 Pre
-
Upload
dipak-zala -
Category
Documents
-
view
222 -
download
0
Transcript of OOPS Finale Assignment 1 Pre
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 1/35
GUJARAT TECHNOLOGICAL
UNIVERSITY
AHMEDABAD
&
C-DAC, PUNE
M.E
inIT Systems and Network Security
Semester-I, Year 2012-14
Module Name
Pre Assignment of OOPS
Date : 06 Aug 2012
Dipak Zala (ITSNS) 1 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 2/35
Lab Faculty Faculty
Course Coordinator
Index
S.No Name of The Program Page
No.
Date Signat
ure
1 Compiled & Interpreted languages. 3 4 06/08/201
2
2 Study of Object - Oriented features. 4 6 06/08/201
2
3 Challenges in memory management. 6 8 06/08/201
2
4 Different types of inheritance. 8 10 06/08/201
2
5 Study about UML diagrams. 10 14 06/08/201
2
6 List out Data types and Operators. 14 17 06/08/201
2
7 Java programs 17 19 06/08/201
2A) Prime Number
B) Fibonacci Series.
C) Power of a number.
8 Write some java programs 19 25 06/08/201
2A) Linear Search
B) Binary Search
Dipak Zala (ITSNS) 2 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 3/35
C) Bubble Sort
D) Matrix Addition &
Multiplication
9 Explore String, Math classes. 26 31 06/08/201
2
10 Create some web pages using simple
HTML32 34 06/08/201
2
1. Study the differences between compiled & interpreted languages, cons &
pros of each. How languages like java balance these factors.
Ans.
Programming languages generally fall into one of two categories: Compiled or Interpreted. With a
compiled language, code you enter is reduced to a set of machine-specific instructions before being saved
as an executable file. With interpreted languages, the code is saved in the same format that you entered.
Interpreted computing languages are languages whose source code is processed by a software
program called an interpreter that reads in the text and immediately acts upon the instructions defined by
the text. Compiled computing languages are languages whose source code is processed by a software
program called a compiler that converts the source code into a file which can then be run directly or indirectly by a computer operating system.
A compiled language is one where the program, once compiled, is expressed in the instructions of
the target machine. For example, an addition "+" operation in your source code could be translated directly
to the "ADD" instruction in machine code.
An interpreted language is one where the instructions are not directly executed by the target
machine, but instead read and executed by some other program (which normally is written in the language
of the native machine). For example, the same "+" operation would be recognized by the interpreter at run
time, which would then call its own "add(a,b)" function with the appropriate arguments, which would then
execute the machine code "ADD" instruction.
Compiled programs generally run faster than interpreted ones because interpreted programs must
be reduced to machine instructions at runtime. However, with an interpreted language you can do things
that cannot be done in a compiled language. For example, interpreted programs can modify themselves by
adding or changing functions at runtime. It is also usually easier to develop applications in an interpreted
environment because you don't have to recompile your application each time you want to test a small
section.
Dipak Zala (ITSNS) 3 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 4/35
A compiled language is written and then run through a compiler which checks its syntax and
compresses it into a binary executable. Since an interpreted language is not compiled, it must be checked
for errors at run-time, which makes it quite a bit slower than a compiled language (like C or Java).
There also exist hybrid languages, such as Java and Python, which have qualities of both compiledand interpreted languages. Java, for example, can be compiled into byte code which must then itself be run
by an interpreter referred to as a virtual machine. Since Java source code itself does not have an
interpreter, it's reasonable to consider Java to be a compiled language.
• Pros:
• No problem with cycles.
• Memory writes have no cost.
• Only touches live data.
• No fragmentation; automatically compacts
• Cons:
• Fragmentation
• Cost proportional to heap size
• Sweep phase needs to traverse whole heap
• Will probably increase locality
• Requires twice the memory space
• Like mark and sweep, need to stop the world
2. Study of object - oriented features and support from known languages (C++,
Java etc)
Ans.
Features of OOP
OOP stands for Object Oriented Programming and the language that support this Object Oriented
programming features is called Object oriented Programming Language. An example of a language thatsupport this Object oriented features are C++ and JAVA.
The Objects Oriented programming language supports all the features of normal programming
languages. In addition it supports some important concepts and terminology which has made it popular
among programming methodology.
The important features of Object Oriented programming are:
Dipak Zala (ITSNS) 4 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 5/35
Inheritance
Polymorphism
Data Hiding
Encapsulation
Overloading
Reusability
Let us see a brief overview of these important features of Object Oriented programming.
Inheritance:
Inheritance as the name suggests is the concept of inheriting or deriving properties of an existing class to
get new class or classes. In other words we may have common features or characteristics that may be
needed by number of classes. So those features can be placed in a common tree class called base class
and the other classes which have these characteristics can take the tree class and define only the new
things that they have on their own in their classes. These classes are called derived class. The main
advantage of using this concept of inheritance in Object oriented programming is it helps in reducing the
code size since the common characteristic is placed separately called as base class and it is just referred in
the derived class. This provide the users the important usage of terminology called as reusability
Polymorphism and Overloading:
Poly refers many. So Polymorphism as the name suggests is a certain item appearing in different forms or
ways. That is making a function or operator to act in different forms depending on the place they are
present is called Polymorphism. Overloading is a kind of polymorphism. In other words say for instance we
know that +, - operate on integer data type and is used to perform arithmetic additions and subtractions. But
operator overloading is one in which we define new operations to these operators and make them operate
on different data types in other words overloading the existing functionality with new one. This is a very
important feature of object oriented programming methodology which extended the handling of data type
and operations.
Data Hiding:
This concept is the main heart of an Object oriented programming. The data is hidden inside the class by
declaring it as private inside the class. When data or functions are defined as private it can be accessed
only by the class in which it is defined. When data or functions are defined as public then it can be
accessed anywhere outside the class. Object Oriented programming gives importance to protecting data
which in any system. This is done by declaring data as private and making it accessible only to the class in
which it is defined. This concept is called data hiding. But one can keep member functions as public.
Encapsulation
Dipak Zala (ITSNS) 5 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 6/35
Data encapsulation, sometimes referred to as data hiding, is the mechanism whereby the implementation
details of a class are kept hidden from the user. The user can only perform a restricted set of operations on
the hidden members of the class by executing special functions commonly called methods. The actions
performed by the methods are determined by the designer of the class, who must be careful not to make
the methods either overly flexible or too restrictive
The concept of data encapsulation is supported in C++ through the use of
the public, protected and private keywords which are placed in the declaration of the class. Anything in the
class placed after thepublic keyword is accessible to all the users of the class; elements placed after
the protected keyword are accessible only to the methods of the class or classes derived from that class;
elements placed after the private keyword are accessible only to the methods of the class.
Reusability
This usage is achieved by the above explained terminology called as inheritance. Reusability is nothing but
re- usage of structure without changing the existing one but adding new features or characteristics to it. It is
very much needed for any programmers in different situations. Reusability gives the following advantages tousers
It helps in reducing the code size since classes can be just derived from existing one and one need to add
only the new features and it helps users to save their time.
For instance if there is a class defined to draw different graphical figures say there is a user who want to
draw graphical figure and also add the features of adding color to the graphical figure. In this scenario
instead of defining a class to draw a graphical figure and coloring it what the user can do is make use of the
existing class for drawing graphical figure by deriving the class and add new feature to the derived class
namely add the feature of adding colors to the graphical figure.
Java is a object oriented programming and to understand the functionality of OOP in Java, we first
need to understand several fundamentals related to objects. These include class, method, inheritance,
encapsulation, abstraction, polymorphism etc.
Class - It is the central point of OOP and that contains data and codes with behavior. In Java everything
happens within class and it describes a set of objects with common behavior. The class definition describes
all the properties, behavior, and identity of objects present within that class. As far as types of classes are
concerned, there are predefined classes in languages like C++ and Pascal. But in Java one can define
his/her own types with data and code.
Object - Objects are the basic unit of object orientation with behavior, identity. As we mentioned above,
these are part of a class but are not the same. An object is expressed by the variable and methods within
the objects. Again these variables and methods are distinguished from each other as instant variables,
instant methods and class variable and class methods.
Dipak Zala (ITSNS) 6 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 7/35
Methods - We know that a class can define both attributes and behaviors. Again attributes are defined by
variables and behaviors are represented by methods. In other words, methods define the abilities of an
object.
3. What are the challenges in memory management - How garbage collection
features of java overcome these.
Ans.
In Object Oriented Programming, Objects typically reside on the Heap. In languages like C# and
Java you cannot create objects that reside on stack, so in these languages all objects reside on the heap
resulting in a distinction between Value and Reference Types. Languages like C++, Objective C, and Object
Pascal all provide a means of allocating objects either on the stack or on the heap. When your objects are
allocated on the heap you need a means of freeing the memory allocated to them when they are no longer
needed. There are a number of different approaches that object oriented programming languages take to
this problem.
Memory management is a simple concept, but is complicated by the interconnected nature of
object oriented programs. It may be difficult to determine when an object is safe to delete.
Freeing and Allocating Memory Manually
Languages like C++ and Object Pascal require that you manage memory yourself. These languages two
functions for memory management. One to allocate space on the heap, and another to free the space used.
Advantages: You are in complete control in this environment, and can provide fine control over when
objects are created and freed. This level of control is particularly helpful when working with devices that
have relatively small amount of RAM available for applications (for instance, a mobile phone or an
embedded engine controller within a car)
Disadvantages: Freeing objects adds complexity that programmers have to carefully manage. Failing to
free an object will result in a memory leak, while prematurely freeing an object has the potential to cause
significant runtime problems that may be hard to debug. When working in teams these problems become
even more of an issue as the memory management of your objects needs to be clearly understood by alldevelopers working on the program. The composite aggregation relationship in a UML class diagram can
be used to indicate that when thewhole is freed it frees its parts.
C++ uses obj = new class_name(params) to create an object, and delete obj to free the space
allocated to these objects. new (C++) on wikipedia
Object Pascal uses obj := class_name.Create(params) to create an object, and obj.Free() to free
the space allocated to the object.
Dipak Zala (ITSNS) 7 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 8/35
Reference Counting
Reference counting is one approach to overcoming the issues of manual memory management. With
reference counting each object maintains a count of the number of references that refer to it. When new
things refer to the object its reference count is increased, when a reference is removed the count isreduced. The object is then responsible for releasing itself when its reference count reaches 0.
Advantages: Objects are freed when their reference count reaches 0, meaning they are freed as soon as
they are no longer needed.
Disadvantages: Circular references mean that objects are never released. For example if A -> B -> C -> A
then the reference count of each is 1, and yet no other objects have references to any in this loop. This
issue can be avoided through specific loop detection code or by appropriate diligence from developers.
Garbage Collection
The latest evolution of memory management looks to address the issues of circular reference counts by
delegating memory management to the program runtime. With this kind of memory management there is
a Garbage Collector that is responsible for freeing objects when they are no longer accessed. This is done
by identifying those objects that cannot be reached from root links such as stack and global variables. Once
these objects are identified the garbage collector frees the memory they are using. This typically involves
calling a destructor or finaliser method to indicate that the object is about to be freed [3].
Advantages: The developers are released from having to deal with memory issues. This significantly
simplifies the process of developing software, regardless of the number of developers working in the team.
Disadvantages: Requires overhead in the runtime to check object links and objects are not freed until the
garbage collector runs, resulting in a larger memory footprint than is actually required.
Java, C#, and Visual Basic use garbage collectors.
Version 2 of Objective C has the option to use a garbage collector.
4. What is inheritance, different types of inheritance, support from known
languages (C++, Java etc)
Ans.
In object-oriented programming (OOP), inheritance is a way to reuse code of existing objects, or to
establish a subtype from an existing object, or both, depending upon programming language support.
In classical inheritance where objects are defined by classes, classes can inherit attributes and behavior
from pre-existing classes called base classes, superclasses, parent classes or ancestor classes. The
resulting classes are known as derived classes, subclasses or child classes. The relationships of classes
through inheritance gives rise to a hierarchy. In prototype-based programming, objects can be defined
directly from other objects without the need to define any classes, in which case this feature is
called differential inheritance.
Dipak Zala (ITSNS) 8 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 9/35
There are five types of inheritance namely:
1) Single Inheritance
2) Multi Level Inheritance
3) Multiple Inheritance
4) Hierarchical Inheritance
5) Hybrid Inheritance
1) Single Inheritance
Single inheritance enables a derived class to inherit properties and behavior from a single parent class. Itallows a derived class to inherit the properties and behavior of a base class, thus enabling code reusabilityas well as adding new features to the existing code. This makes the code much more elegant and less
repetitive. Inheritance is one of the key features of object-oriented programming (OOP).
2) Multi Level Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived class thenthis mechanism is known as the multilevel inheritance. The derived class is called the subclass or childclass for it's parent class and this parent class works as the child class for it's just above ( parent ) class.Multilevel inheritance can go up to any number of level.
3) Multiple Inheritance
Multiple inheritance is a feature of some object-oriented computer programming languages in whicha class can inherit behaviors and features from more than one super class. You can derive a class from anynumber of base classes. Deriving a class from more than one direct base class is called multipleinheritance.
Dipak Zala (ITSNS) 9 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 10/35
4) Hierarchical Inheritance
It is the process of deriving two or more classes from single base class. And in turn each of the derived
classes can further be inherited in the same way. Thus it forms hierarchy of classes or a tree of classeswhich is rooted at single class.
5) Hybrid Inheritance
In this type of inheritance, we can have combination of number of inheritances but this can produce an error of using same name function from no of classes, which will bother the compiler to how to use the functions.Therefore, it will generate errors in the program. This has known as ambiguity or duplicity.
Dipak Zala (ITSNS) 10 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 11/35
5. Study about UML diagrams, try to generate few (class diagrams, sequence
diagrams etc) using umbrello software.
Ans.
Unified Modeling Language (UML) is a standardized general-purpose modeling language in the
field of object-oriented software engineering. UML includes a set of graphic notation techniques to
create visual models of object-oriented software-intensive systems.
The UML is a tool for specifying software systems. Standardized diagram types to help you
describe and visually map a software system's design and structure. Using UML it is possible to model just
about any kind of application, both specifically and independently of a target platform. While UML is
naturally oriented towards Object-Oriented programming, but it is just as easy to model procedural
languages such as C, Visual Basic, Fortran etc.The use of UML as a tool for defining the structure of a system is avery useful way to manage
large, complex systems. Having a clearly visible structure makes it easy to introduce new people to an
existing project.
Class Diagram
The class diagram shows how the different entities (people, things, and data) relate to each other; in
other words, it shows the static structures of the system. Class diagrams can also be used to show
implementation classes, which are the things that programmers typically deal with. An implementation class
diagram will probably show some of the same classes as the logical classes diagram. The implementation
class diagram won't be drawn with the same attributes, however, because it will most likely have references
to things like Vectors and Hash Maps.
Dipak Zala (ITSNS) 11 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 12/35
A class is depicted on the class diagram as a rectangle with three horizontal sections, as shown in
Figure 2. The upper section shows the class's name; the middle section contains the class's attributes; and
the lower section contains the class's operations (or "methods").
Use-case diagram
A use case illustrates a unit of functionality provided by the system. The main purpose of the use-
case diagram is to help development teams visualize the functional requirements of a system, including the
relationship of "actors" (human beings who will interact with the system) to essential processes, as well as
the relationships among different use cases.
Use-case diagrams generally show groups of use cases — either all use cases for the complete
system, or a breakout of a particular group of use cases with related functionality (e.g., all security
administration-related use cases).
Dipak Zala (ITSNS) 12 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 13/35
Sequence Diagram
Sequence diagrams describe interactions among classes in terms of an exchange of messagesover time. Sequence diagrams show a detailed flow for a specific use case or even just part of a specific
use case. They are almost self explanatory; they show the calls between the different objects in their
sequence and can show, at a detailed level, different calls to different objects.
A sequence diagram has two dimensions: The vertical dimension shows the sequence of
messages/calls in the time order that they occur; the horizontal dimension shows the object instances to
which the messages are sent.
Dipak Zala (ITSNS) 13 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 14/35
Activity diagram
In UML, an activity diagram is used to display the sequence of activities. Activity diagrams show theworkflow from a start point to the finish point detailing the many decision paths that exist in the progression
of events contained in the activity. They may be used to detail situations where parallel processing may
occur in the execution of some activities. Activity diagrams are useful for business modeling where they are
used for detailing the processes involved in business activities.
An activity is the specification of a parameterized sequence of behavior. An activity is shown as a
round-cornered rectangle enclosing all the actions, control flows and other elements that make up the
activity. An activity diagram illustrates the dynamic nature of a system by modeling the flow of control from
activity to activity. An activity represents an operation on some class in the system that results in a change
in the state of the system.
Dipak Zala (ITSNS) 14 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 15/35
6. List out data types, operators available in java, try some simple programs to
make use of them.
Primitive Data Types
The primitive data types are predefined data types, which always hold the value of the same data type,
Dipak Zala (ITSNS) 15 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 16/35
and the values of a primitive data type don't share the state with other primitive values. These data types
are named by a reserved keyword in Java programming language.
There are eight primitive data types supported by Java programming language :
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127 (inclusive). This
type of data type is useful to save memory in large arrays.. We can also use byte instead of int to
increase the limit of the code. The syntax of declaring a byte type variable is shown as:
byte b = 5;
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to 32,767.short is
used to save memory in large arrays. The syntax of declaring a short type variable is shown as:
short s = 2;
int
The int data type is used to store the integer values not the fraction values. It is a 32-bit signed two's
complement integer data type. It ranges from -2,147,483,648 to 2,147,483,647 that is more enough to store
large number in your program. However for wider range of values use long. The syntax of declaring a int
type variable is shown as:
int num = 50;
long
The long data type is a 64-bit signed two's complement integer. It ranges from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807. Use this data type with larger range of values. The syntax of declaring a
long type variable is shown as:
long ln = 746;
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float (instead of
Dipak Zala (ITSNS) 16 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 17/35
double) to save memory in large arrays. We do not use this data type for the exact values such as currency.
For that we have to use java.math.BigDecimal class. The syntax of declaring a float type variable is:
float f = 105.65;
float f = -5000.12;
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from 4.94065645841246544e-
324d to 1.79769313486231570e+308d (positive or negative). This data type is generally the default choice
for decimal values. The syntax of declaring a double type variable is shown as:
double d = 6677.60;
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535. They are not
integral data type like int, short etc. i.e. the char data type can't hold the numeric values. The syntax of
declaring a char type variable is shown as:
char caps = 'c';
boolean
The boolean data type represents only two values: true and false and occupy is 1-bit in the
memory. These values are keywords in Java and represents the two boolean
states: on or off , yes or no. We use boolean data type for specifying conditional statements as if, while,
do, for . In Java, trueand false are not the same as True and False. They are defined constants of the
language. The syntax of declaring a boolean type variable is shown as:
boolean result = true;
Operators:
1. Simple Assignment Operator
Assignment operator is the most common operator almost used with all programming languages.
2. Arithmetic Operators
Arithmetic Operators are used to perform some mathematical operations like addition, subtraction,
Dipak Zala (ITSNS) 17 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 18/35
multiplication, division, and modulo (or remainder).
3. Unary Operators
The unary operators requires only one operand to perform different kind of operations
such as increasing/decreasing a value, negating an expression, or inverting a boolean
value.
4. Equality and Relational Operators
Whenever we need to compare the results of two expressions or operands in a program then
theequality and relational operators are used to know whether an operand is equal, not equal,
greater than, less than to another operand.
5. Conditional (Logical) Operators
Conditional operators return a true or a false value based on the state of the variables i.e. the
operations using conditional operators are performed between the two boolean expressions.
6. Bitwise and Bit Shift Operators
In Java the bitwise and bit shift operators are used to manipulate the contents of variables at a bit
level according to binary format.
7. Type Operators
Java provides a run-time operator instanceof to compare a class and an instance of that class.
This operator " instanceof " compares an object to a specified class type
8. Operator Precedence
In Java, Operator Precedence is an evaluation order in which the operators within an expression
are evaluated on the priority bases
7. Write some java programs to be comfortable with control structures.
Ans.
A) JAVA code for Prime Number.
class Prime
{
Dipak Zala (ITSNS) 18 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 19/35
public static void main(String s[])
{
int n=30;
int i,j,x=0;
for(i=1;x<=n-1;i++){
for(j=2;j<i-1;j++)
{
if(i%j==0)
break;
}
if(i%j!=0)
{
System.out.println(" "+i+" ");
x++;
}
}
}
}
B) JAVA code for Fibonacci Series.
class fibonacci
{
public static void main(String d[])
{
int i,a=0,b=1,c;
System.out.println("fibonacci series");
for(i=0;i<15;i++)
{
c=a+b;
System.out.print(" "+c);
b=a;
a=c;
}
}
}
C) JAVA code for Power of a number.
Dipak Zala (ITSNS) 19 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 20/35
class Power1
{
int ans;
public static void main(String s[])
{
Power1 p1 =new Power1();
int answer=p1.pow();
System.out.println("2 raised to 12="+answer);
}
Power1()
{
ans=1;
}
int pow()
{
int i;
for(i=0;i<12;i++)
{
ans=ans*2;
}
return(ans);
}
}
8. Write some java programs which can handle arrays.
a. Linear search
public class LinearSearch {
public int find(final int[] data, final int key) {
for (int i = 0; i < data.length; ++i) {
if (data[i] > key)
return -1;
else if (data[i] == key)
Dipak Zala (ITSNS) 20 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 21/35
return i;
}
return -1;
}
public static void main(String[] args) {
final int arr[] = new int[10];
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < arr.length; i++) {
arr[i] = input.nextInt();
}
LinearSearch search = new LinearSearch();
System.out.print("Enter the element to search: ");
int num=input.nextInt();
int n = search.find(arr, num);
if ((n >= 0) && (n < arr.length)) {
System.out.println("Found at index: " + n);
} else {
System.out.println("Not Found");
}
}
}
Output:
Enter 10 numbers:1
2
3
4
5
6
7
8
9
10
Enter the element to search:5
Found at index: 4
b. Binary search
public class BinarySearch {
public static void main(String[] args) {
int[] intArray = new int[10];
int searchValue = 0, index;
Dipak Zala (ITSNS) 21 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 22/35
System.out.println("Enter 10 numbers");
Scanner input = new Scanner(System.in);
for (int i = 0; i < intArray.length; i++) {
intArray[i] = input.nextInt();}
System.out.print("Enter a number to search for: ");
searchValue = input.nextInt();
index = binarySearch(intArray, searchValue);
if (index != -1) {
System.out.println("Found at index: " + index);
} else {
System.out.println("Not Found");
}
}
static int binarySearch(int[] search, int find) {
int start, end, midPt;
start = 0;
end = search.length - 1;
while (start <= end) {
midPt = (start + end) / 2;
if (search[midPt] == find) {
return midPt;
} else if (search[midPt] < find) {
start = midPt + 1;
} else {
end = midPt - 1;
}
}
return -1;
}
}
Output:
Enter 10 numbers:
1
2
3
Dipak Zala (ITSNS) 22 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 23/35
4
5
6
78
9
10
Enter a number to search for:5
Found at index: 4
c. Bubble sort
public class bubbleSort
{
public static void main(String a[])
{
int i;
int array[] = {12,9,4,99,120,1,3,10};
System.out.println("Values Before the sort:\n");
for(i = 0; i < array.length; i++)
System.out.print( array[i]+" ");
System.out.println();
bubble_srt(array, array.length);
System.out.print("Values after the sort:\n");
for(i = 0; i <array.length; i++)
{
System.out.print(array[i]+" ");
}
System.out.println();
}
public static void bubble_srt( int a[], int n )
{
int i, j,t=0;
for(i = 0; i < n; i++)
{
for(j = 1; j < (n-i); j++)
{
Dipak Zala (ITSNS) 23 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 24/35
if(a[j-1] > a[j]){
t = a[j-1];
a[j-1]=a[j];
a[j]=t;}
}
}
}
}
Output:
Values Before the sort:
12 9 4 99 120 1 3 10
Values after the sort:
1 3 4 9 10 12 99 120
d. Matrix addition
class MatrixSum
{
public static void main(String[] args){
int array[][]= {{4,5,6},{6,8,9}};
int array1[][]= {{5,4,6},{5,6,7};
System.out.println("Matrix 1 : ");
for(int i = 0; i < l; i++)
{
for(int j = 0; j <= l; j++)
{
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int m= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < m; i++)
Dipak Zala (ITSNS) 24 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 25/35
{
for(int j = 0; j <= m; j++)
{
System.out.print(" "+array1[i][j]);}
System.out.println();
}
System.out.println("Addition of both matrix : ");
for(int i = 0; i < m; i++)
{
for(int j = 0; j <= m; j++)
{
System.out.print(" "+(array[i][j]+array1[i][j]));
}
System.out.println();
}
}
}
Output:
Matrix 1 :
4 5 6
6 8 9
Matrix 2 :
5 4 6
5 6 7
Addition of both matrix :
9 9 12
11 14 16
e. Matrix addition
class MatrixMultiply
{
public static void main(String[] args)
Dipak Zala (ITSNS) 25 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 26/35
{
int array[][] = {{5,6,7},{4,8,9}};
int array1[][] = {{6,4},{5,7},{1,1}};
int array2[][] = new int[3][3];int x= array.length;
System.out.println("Matrix 1 : ");
for(int i = 0; i < x; i++)
{
for(int j = 0; j <= x; j++)
{
System.out.print(" "+ array[i][j]);
}
System.out.println();
}
int y= array1.length;
System.out.println("Matrix 2 : ");
for(int i = 0; i < y; i++)
{
for(int j = 0; j < y-1; j++)
{
System.out.print(" "+array1[i][j]);
}
System.out.println();
}
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y-1; j++)
{
for(int k = 0; k < y; k++)
{
array2[i][j] += array[i][k]*array1[k][j];
}
}
}
System.out.println("Multiply of both matrix : ");
Dipak Zala (ITSNS) 26 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 27/35
for(int i = 0; i < x; i++)
{
for(int j = 0; j < y-1; j++)
{System.out.print(" "+array2[i][j]);
}
System.out.println();
}
}
}
9. Explore String, Math classes available in java.lang package
Ans.
Strings in java
Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on
the same reference. A java.lang.String class is final which implies no class and extend it. The
java.lang.Stringclass differs from other classes, one difference being that the String objects can be used
with the += and + operators for concatenation.
Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for
testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected
portion of a String.
Creating Strings:
The most direct way to create a string is to write:
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String object with its valuing thiscase, "Hello world!'.
String Length:
Dipak Zala (ITSNS) 27 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 28/35
Methods used to obtain information about an object are known as accessor methods. One accessor method
that you can use with strings is the length() method, which returns the number of characters contained in
the string object.
public class StringDemo{
public static void main(String args[]){
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This would produce following result:
String Length is : 17
Other Useful String Methods:
1 char charAt(int index)
Returns the character at the specified index.
2 int compareTo(Object o)
Compares this String to another Object.
3 int compareTo(String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.
5 String concat(String str)
Concatenates the specified string to the end of this string.
6 boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.
7 static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array specified.
8 static String copyValueOf(char[] data, int offset, int count)
Returns a String that represents the character sequence in the array specified.
9 boolean endsWith(String suffix)
Tests if this string ends with the specified suffix.
Dipak Zala (ITSNS) 28 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 29/35
10 boolean equals(Object anObject)
Compares this string to the specified object.
11 boolean equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
12 byte getBytes()
Encodes this String into a sequence of bytes using the platform's default charset, storing the result into
a new byte array.
13 byte[] getBytes(String charsetName
Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte
array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
15 int hashCode()
Returns a hash code for this string.
16 int indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
17 int indexOf(int ch, int fromIndex)
Returns the index within this string of the first occurrence of the specified character, starting the search
at the specified index.
18 int indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
19 int indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the
specified index.
20 String intern()
Returns a canonical representation for the string object.
21 int lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
22 int lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward
starting at the specified index.
23 int lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
Dipak Zala (ITSNS) 29 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 30/35
24 int lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward
starting at the specified index.
25 int length()
Returns the length of this string.
26 boolean matches(String regex)
Tells whether or not this string matches the given regular expression.
27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
28 boolean regionMatches(int toffset, String other, int ooffset, int len)
Tests if two string regions are equal.
29 String replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
30 String replaceAll(String regex, String replacement
Replaces each substring of this string that matches the given regular expression with the given
replacement.
31 String replaceFirst(String regex, String replacement)
Replaces the first substring of this string that matches the given regular expression with the given
replacement.
32 String[] split(String regex)
Splits this string around matches of the given regular expression.
33 String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
34 boolean startsWith(String prefix)
Tests if this string starts with the specified prefix.
35 boolean startsWith(String prefix, int toffset)
Tests if this string starts with the specified prefix beginning a specified index.
36 CharSequence subSequence(int beginIndex, int endIndex)
Returns a new character sequence that is a subsequence of this sequence.
37 String substring(int beginIndex)
Returns a new string that is a substring of this string.
38 String substring(int beginIndex, int endIndex)
Dipak Zala (ITSNS) 30 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 31/35
Returns a new string that is a substring of this string.
39 char[] toCharArray()
Converts this string to a new character array.
40 String toLowerCase()
Converts all of the characters in this String to lower case using the rules of the default locale.
41 String toLowerCase(Locale locale)
Converts all of the characters in this String to lower case using the rules of the given Locale.
42 String toString()
This object (which is already a string!) is itself returned.
43 String toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
44 String toUpperCase(Locale locale)
Converts all of the characters in this String to upper case using the rules of the given Locale.
45 String trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
46 static String valueOf(primitive data type x)
Returns the string representation of the passed
Math Class:
Some basic math functions can be found in the Math class. The Math class is a wrapper
class for a set of useful mathematical functions and constants. All of the methods and fields
are static, and there is no public constructor.
Math ConstantsTwo common constants are defined in the Math class.doubleMath.E() : Value of e, 2.71828, base of the natural logarithms.doubleMath.PI() : Value of pi, 3.14159265
Math Methods
Trigonometric Methods All trigonometric method parameters are measured in radians, the normal mathematical system of angles,
and not in degrees, the normal human angular measurement system. Use the toRadians or toDegrees
methods to convert between these systems, or use the fact that there are 2*PI radians in 360 degrees. In
Dipak Zala (ITSNS) 31 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 32/35
addition to the methods below, the arc methods are also available.
double Math.sin(ar) Returns the sine of ar.double Math.cos(ar) Returns the cosine of ar.
double Math.tan(ar) Returns the tangent of ar.double Math.toRadians(d) Returns d (angle in degrees) converted to radians.double Math.toDegrees(ar) Returns ar (angle in radians) converted to degrees.
Exponential MethodsThe two basic functions for logarithms and power are available. These both use the base e (Math.E) as is
the usual case in mathematics.
double Math.exp(d) Returns e (2.71...) to the power d.double Math.pow(d1, d2) Returns d1d2.double Math.log(d) Returns the logarithm of d to base e.double Math.log10(d) Returns the logarithm of d to base 10.
Misc Methods
double Math.sqrt(d) Returns the square root of d.Math.abs(x) Returns absolute value of x with same type as the parameter: int,
long, float, or double.Math.max(x, y) Returns maximum of x and y with same type as the parameter: int,
long, float, or double.Math.min(x, y) Returns minimum of x and y with same type as the parameter: int,
long, float, or double.
Integer Related MethodsThe following methods translate floating point values to integer values, altho these values may still be stored
in a double.double Math.floor (d) Returns the closest integer-valued double which is equal to or less
than d.double Math.ceil(d) Returns the closest integer-valued double which is equal to or
greater than d.double Math.rint(d) Returns the closest integer-valued double to d.long Math.round(d) Returns the long which is closest in value to the double d.int Math.round(f) Returns the int which is closest in value to the float f.
Random Numbersdouble Math.random() Returns a number x in the range, 0.0 <= x < 1.0.
Dipak Zala (ITSNS) 32 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 33/35
10. Create some web pages using simple HTML by incorporating following
features
General Tags,Formatting ,Hyperlinking & Image handling, Tables, Forms.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE>Google</TITLE><META http-equiv=content-type content="text/html; charset=UTF-8"><STYLE>BODY {
FONT-FAMILY: arial,sans-serif }TD {
FONT-FAMILY: arial,sans-serif } A {
FONT-FAMILY: arial,sans-serif }P {
FONT-FAMILY: arial,sans-serif }.h {
FONT-FAMILY: arial,sans-serif }.h {
FONT-SIZE: 20px}
.q {COLOR: #0000cc
}</STYLE>
</HEAD>
<BODY text=#000000 vLink=#551a8b aLink=#ff0000 link=#0000cc bgColor=#ffffff
onload=sf()>
<CENTER>
<TABLE cellSpacing=0 cellPadding=0 border=0>
<TBODY>
<TR>
<TD><IMG height=110 alt=Google src="http://www.itsagadget.com/wordpress/wp-content/uploads/2012/02/Google-Logo.jpg"
Dipak Zala (ITSNS) 33 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 34/35
width=276></TD></TR></TBODY></TABLE><BR>
<FORM name=f action=/search>
<TABLE cellSpacing=0 cellPadding=4 border=0>
<TBODY>
<TR>
<TD class=q noWrap><FONT size=-1><B><FONT
color=#000000>Web</FONT></B> <A class=q id=1a
onclick="return c('www.google.com/imghp','wi',event);"
href="http://www.google.com/imghp?hl=en&tab=wi&ie=UTF-8&oe=UTF-
8">Images</A> <A
class=q id=2a onclick="return c('www.google.com/grphp','wg',event);"
href="http://www.google.com/grphp?hl=en&tab=wg&ie=UTF-8&oe=UTF-8">Groups</A> <A
class=q id=4a onclick="return c('www.google.com/nwshp','wn',event);"
href="http://www.google.com/nwshp?hl=en&tab=wn&ie=UTF-8&oe=UTF-8">News</A> <B><A
class=q
href="http://www.google.com/options/index.html">more »</A></B></FONT></TD></TR></TBODY></TABLE>
<TABLE cellSpacing=0 cellPadding=0>
<TBODY>
<TR>
<TD width=75> </TD>
<TD align=middle><INPUT type=hidden value=en name=hl><SPAN
id=hf></SPAN><INPUT type=hidden value=UTF-8 name=ie><INPUT type=hidden
value=UTF-8 name=oe><INPUT maxLength=256 size=55 name=q><BR><INPUT type=submitvalue="Google Search" name=btnG><INPUT type=submit value="I'm Feeling Lucky"name=btnI></TD>
<TD vAlign=top noWrap><FONT size=-2> <A
Dipak Zala (ITSNS) 34 | P a g e
7/31/2019 OOPS Finale Assignment 1 Pre
http://slidepdf.com/reader/full/oops-finale-assignment-1-pre 35/35
href="http://www.google.com/advanced_search?hl=en">Advanced Search</A><BR> <A
href="http://www.google.com/preferences?hl=en">Preferences</A><BR> <A
href="http://www.google.com/language_tools?hl=en">Language
Tools</A></FONT></TD></TR></TBODY></TABLE></FORM><BR><BR><FONT size=-1><SPAN id=hp
style="BEHAVIOR: url(#default#homepage)"></SPAN>
</FONT>
<P><FONT size=-2>©2012 Dipak Zala - Searching 4,285,199,774 web
pages</FONT></P></CENTER></BODY></HTML>