You are on page 1of 53

Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:01
Title: Write a program for command line argument in java.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 1


Object Oriented Programming using JAVA Laboratory

Experiment No.: 01
Name of Experiment: Write a program for command line argument in
java.

Aim: program for command line argument in java

Equipments/Machines: Win XP OS, JDK

Theory:
Java contains two types of Command Line Arguments:-

The Java application can accept any number of arguments from the command line.
Command line arguments allow the user to affect the operation of an application. For
example, a program might allow the user to specify verbose mode--that is, specify that the
application display a lot of trace information--with the command line argument -verbose.

When invoking an application, the user types the command line arguments after the
application name. For example, suppose you had a Java application, called Sort, that sorted
lines in a file, and that the data you want sorted is in a file named ListOfFriends. If you were
using DOS, you would invoke the Sort application on your data file like this:

C :\> java Sort ListOfFriends

In the Java language, when you invoke an application, the runtime system passes the
command line arguments to the application's main method via an array of Strings. Each
String in the array contains one of the command line arguments. In the previous example, the
command line arguments passed to the Sort application is an array that contains a single
string: "ListOfFriends".

1. Echoing Command-Line Arguments.


This simple application displays each of its command line arguments on a line by
itself:

Algorithm:
1. define class Echo
2. declare main method public static void main (String args[]) {
3. for (int i = 0; i < args.length; i++)
4. Print args[i].
5. Stop

2. Parsing Numeric Command-Line arguments.


Algorithm:

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 2


Object Oriented Programming using JAVA Laboratory

1. public class Switch


2. public static void main(String key[])
3. int x=Integer.parseInt(key[0]);
4. switch(x)
5. case 1: System.out.println("Monday")
6. case 2: System.out.println("Tuesday")
7. case 3: System.out.println("Wednesday")
8. case 4: System.out.println("Thursday")
9. case 5: System.out.println("Friday");
10. case 6: System.out.println("Saturday")
11. case 7: System.out.println("Sunday")
12. End of switch
13. End of main.
14. End of class

Conclusion: Thus we have studied command line argument in java.

Sample Expert Viva-vice Questions:


1. What is Command line argument?
2. Explain disadvantage of command line arguments.
3. Why to use command line argument.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 3


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:02
Title: Write simple java programs.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 4


Object Oriented Programming using JAVA Laboratory

Experiment No.: 02
Name of Experiment: Write simple java programs.

Aim: Study of simple java programs.

a) WAP to calculate area & circumference of circle

b) WAP to swap given two strings

c) WAP to separate out digits of a number

d) WAP to convert temperature from Fahrenheit to Celsius

Equipments/Machines: Win XP OS, JDK

Theory:
Java contains two general categories of built in data-types:-

1.Primitive data-types:

At the core of Java are eight primitive (also called elemental or simple)
types of data. The term primitive is used here to indicate that these types
are not objects in an object-oriented sense, but rather, normal binary
values.

Integers: Java defines four integer types: byte, short, int, and long, which are shown here:
Type Width in Bits Range:

Type Width in bits Range

byte 8 –128 to 127

–32,768 to 32,767
short 16

int 32 –2,147,483,648 to 2,147,483,647

–9,223,372,036,854,775,808 to
long 64
9,223,372,036,854,775,807

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 5


Object Oriented Programming using JAVA Laboratory

All of the integer types are signed positive and negative values. Java does not support
unsigned (positive-only) integers. The most commonly used integer type is int.
Variables of type int are often employed to control loops, to index arrays, and to
perform general-purpose integer math.When you need an integer that has a range
greater than int, use long. The smallest integer type is byte. Variables of type byte are
especially useful when working. The short type creates a short integer that has its
high-order byte first.

Floating-Point Types:

The floating-point types can represent numbers that have fractional components.
There are two kinds of floating-point types, float and double, which represent single
and double-precision numbers, respectively. Type float is 32 bits wide and type
double is 64 bits wide.

Characters:

In Java, characters are not 8-bit quantities like they are in most other computer
languages. Instead Java uses Unicode. Unicode defines a character set that can
represent all of the characters found in all human languages. Thus, in Java, char

is an unsigned 16-bit type having a range of 0 to 65,536. The standard 8-bit ASCII
character set is a subset of Unicode and range from 0 to 127. Thus, the ASCII
characters are still valid Java characters. A character variable can be assigned a value
by enclosing the character in single quotes.

The Boolean Type:

The boolean type represents true/false values. Java defines the values true and false
using the reserved words true and false. Thus, a variable or expression of type
boolean will be one of these two values.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 6


Object Oriented Programming using JAVA Laboratory

2. Non primitive data-types

Composite, or reference, data types consist of more than a single element. Composite
data types are of two kinds: classes and arrays. Class and array names start with an
upper case letter and are camel-capitalized. Any class can be used as a data type once
it has been created and imported into the program. Because the String class is the class
most often used as a data type.

Algorithm :

1.Read radius of circle as r

Calculate area as 3.14*r*r

Calculate circumference as 2*3.14.r

Print area, circumference

2.Declare two strings as s1,s2,temp

Print original string s1,s2

Swap two string as temp=s1

S1=s2 , s2=temp

Print s1,s2

3.Read a number n1,declare an integer number d

Repeat until (n1!=0)

d=n1%10

print d

n1=n1/10

4.Read temperature t in Fahrenheit, declare c

Convert it into Celsius by formula

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 7


Object Oriented Programming using JAVA Laboratory

C= (5*((t-32)/9));

Print c

Conclusion: Thus we have studied the implementation of different simple


java programs.

Sample Expert Viva-vice Questions:


1. What is datatype?
2. State datatypes in java.
3. Give size in byte & example of java data types.
4. How to compile java program?
5. How to save java program?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 8


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:03
Title: Write program for different operators in java.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 9


Object Oriented Programming using JAVA Laboratory

Experiment No.: 03
Name of Experiment: Write program for different operators in java.

Aim: Program for command line argument in java

a) WAP to compare two numbers.

b) WAP to print truth table for java logical operators

c) WAP to read the number & shift left & right by 3 bits

Equipments/Machines: Win XP OS, JDK

Theory:
There are six basic kinds of operators(arithmetic, logical, assignment, comparison, bitwise,
and ternary), and operators affect one, two, or three operands, making them unary, binary, or
ternary operators. They have properties of precedence and associativity, which determine the
order they’re processed in. Operators are assigned numbers that establish their precedence.
The higher the number, the higher the order of precedence (that is, the more likely it is to be
evaluated sooner than others). An operator of precedence 1 (the lowest) will be evaluated last,
and an operator with a precedence of 15 (the highest) will be evaluated first. Operators with
same precedence are normally evaluated from left to right.

Arithmetic operators :

Java provides a full set of operators for mathematical calculations. Java, unlike some
languages, can perform mathematical functions on both integer and floating-point values.
You will probably find these operators familiar. Here are the arithmetic operators:
Operator Definition Preceden Associativity
ce

++/–– Auto-increment/decrement: Adds one to, orsubtracts one from, 1 Right


its single operand. If the value of i is 4, ++i is 5. A pre-
increment (+i ) increments the value by one and assigns the new
value to theoriginal variable i . A post-increment (+)increments
the value but leaves the originalvariable i with the original
value.

+/– Unary plus/minus: sets or changes thepositive/negative value of 2 Right


* Multiplication.
a single number. 4 Left

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 10


Object Oriented Programming using JAVA Laboratory

/ Division. 4 Left
% Modulus: Divides the first operand by the second operand and 4 Left
returns the remainder. See below for a brief mathematical
+/– review.
Addition/Subtraction 5 Left

Relational and Logical Operators:

In the terms relational operator and logical operator, relational refers to the relationships
that values can have with one another, and logical refers to the ways in which true and false
values can be connected together. Since the relational operators produce true or false results,
they often work with the logical operators. The relational operators are shown here:

Operator Meaning

== Equal to

!= Not equal to

< Less than

> Greater than

<= Less than or equal to

>= Greater than or equal to

The logical operators are shown next:

Operator Meaning

& AND

| OR

^ XOR (exclusive OR)

|| Short circuit OR

&& Short-circuit AND

! NOT

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 11


Object Oriented Programming using JAVA Laboratory

In Java, all objects can be compared for equality or inequality using = = and !=.
However, the comparison operators, <, >, <=, or >=, can be applied only to those types that
support an ordering relationship. Therefore, all of the relational operators can be applied to all
numeric types and to type char. However, values of type boolean can only be compared for
equality or inequality, since the true and false values are not ordered.For the logical
operators, the operands must be of type boolean, and the result of a logical operation is of
type boolean. The logical operators, &, |, ^,and!, support the basic logical operations AND,
OR, XOR, and NOT, The short-circuit AND operator is &&, and the short-circuit OR
operator is ||. Their normal counterparts are & and |. The only difference between the normal
and short- circuit versions is that the normal operands will always evaluate each operand, but
short-circuit versions will evaluate the second operand only when necessary.

The Assignment Operator:

Now it is time to take a formallook at it. The assignment operator is the single equal sign, =.
This operator works in Javamuch as it does in any other computer language. It has this
general form:

var = expression;

The Bitwise AND, OR, XOR, and NOT Operators:

The bitwise operators AND, OR, XOR, and NOT are &, |, ^, and ~. They perform the
same operations as their Boolean logical equivalents. The difference is that the bitwise
operators work on a bit-by-bit basis. In terms of its most common usage, you can think of the
bitwise AND as a way to turn bits off. That is, any bit that is 0 in either operand will cause the
corresponding bit in the outcome to be set to 0.

ALGORITHM : 1. Read two numbers n1 ,n2.

Compare using if as

If(n1>n2)

Print n1 greater

else if(n1==n2)

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 12


Object Oriented Programming using JAVA Laboratory

print n1 ,n2 are equal

else

print n2 is greater

2. Declare two Boolean variables b1,b2

Print(b1&b2)

Print(b1|b2)

Print(b1^b2)

Print(!b1)

3. Read a numbers a1

Declare two variable l, r

L=a1<<3, r=a1>>3

Print l, r

Conclusion: Thus we have studied the implementation of different


operators in java.

Sample Expert Viva-vice Questions:

1. List different operators in java.

2. What is ternary operator?

3. Explain shift operators.

4. Explain use of logical operators in if statement.

5. What are short circuit operators?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 13


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering

Department of Electronics & Telecommunication Engineering

Experiment No.:04
Title: Write a program for various ways of accepting data through
keyboard and display its content.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 14


Object Oriented Programming using JAVA Laboratory

Experiment No.: 04
Name of Experiment: Write a program for various ways of accepting data
through keyboard and display its content.

Aim: program for various ways of accepting data through keyboard and
display its content.

1. Read through DataInputstream.

2. Read input through Scanner.

3. Read input through BufferedReader.

Equipments/Machines: Win XP OS, JDK

Theory:
1. Read through DataInputstream.
The DataInputStream is used in the context of DataOutputStream and can be used to read
primitives.Following is the constructor to create an InputStream:

InputStream in = DataInputStream(InputStream in);

Once you have DataInputStream object in hand then there is a list of helper methods which can be
used to read the stream or to do other operations on the stream.

2. Read input through Scanner.

The Scanner class must be imported from java.util. It provides a wrapper class that encapsulates an
input stream, such as stdin, and it provides a number of convenience methods for reading lines and
then breaking a line into tokens.

3. Read input through BufferedReader.

The BufferedReader has a neat method called readLine() that reads all the input characters into a
string when the user hits the Enter button instead of reading byte by byte.

Algorithm:

1. Define class DifferentInputStream


2. Declare main method
3. DataInputStream in = new DataInputStream(System.in)
4. Print("Enter Name1: ")
5. String name1=in.readLine()
6. Print("Name1 is: "+name1)

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 15


Object Oriented Programming using JAVA Laboratory

7. Scanner input=new Scanner(System.in)


8. System.out.print("Enter integer: ")
9. int i=input.nextInt()
10. System.out.print("Enter double: ")
11. double d=input.nextDouble()
12. Print(i)
13. BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))
14. Print("Enter Name2: ")
15. String input = reader.readLine()
16. Print("Name2 is: "+name2)

Conclusion: Thus we have studied the various ways of accepting data


through keyboard and display its content.

Sample Expert Viva-vice Questions:

1. What is DataInputStream ?

2. What is Scanner?

3. What is BufferedReader?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 16


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering

Department of Electronics & Telecommunication Engineering

Experiment No.:05
Title: Write a program to study concepts of arrays.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 17


Object Oriented Programming using JAVA Laboratory

Experiment No.: 05
Name of Experiment: Write a program to study concepts of arrays.

Aim: Study the concepts of arrays:

Program for addition, subtraction and multiplication of two matrices.

Equipments/Machines: Win XP OS, JDK

Theory:
An array is a collection of variables of the same type, referred to by a common name.
In Java, arrays can have one or more dimensions, although the one-dimensional array is the
most common. Arrays are used for a variety of purposes because they offer a convenient
means of grouping together related variables. For example, you might use an array to hold a
record of the daily high temperature for a month, a list of stock price averages, or a list of
your collection of programming books. The principal advantage of an array is that it
organizes data in such a way that it can be easily manipulated. Also, arrays organize data in
such a way that it can be easily sorted. Arrays in java have one special attribute: they are
implemented as objects. By implementing arrays as objects, several important advantages are
gained, not the least of which is that unused arrays can be garbage collected.

One-Dimensional Arrays:

A one-dimensional array is a list of related variables. Such lists are common in programming.
To declare a one-dimensional array, you will use this general form:

type array-name[ ] = new type[size];

Here, type declares the base type of the array. The base type determines the data type
of each element contained in the array. The number of elements that the array will hold is
determined by size. Since arrays are implemented as objects, the creation of an array is a two-
step process. First, you declare an array reference variable. Second, you allocate memory for
the array, assigning a reference to that memory to the array variable. Thus, arrays in Java are
dynamically allocated using the new operator.The following creates an int array of 10
elements and links it to an array reference variable named sample.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 18


Object Oriented Programming using JAVA Laboratory

int sample[] = new int[10];

This declaration works just like an object declaration. The sample variable holds a
reference to the memory allocated by new. This memory is large enough to hold 10 elements
of type int. As with objects, it is possible to break the preceding declaration in two. For
example:

int sample[];

sample = new int[10];

In this case, when sample is first created, it is null, because it refers to no physical
object. It is only after the second statement executes that sample is linked with an array.

An individual element within an array is accessed by use of an index. An index describes the
position of an element within an array. In Java, all arrays have zero as the index of their first
element.

Multidimensional Arrays:

Although the one-dimensional array is the most commonly used array in programming,
multidimensional arrays (arrays of two or more dimensions) are certainly not rare. In Java, a
multidimensional array is an array of arrays. Two-Dimensional Arrays The simplest form of
the multidimensional array is the two-dimensional array. A two-dimensional array is, in
essence, a list of one-dimensional arrays. To declare a two-dimensional integer array table of
size 10, 20 you would write

int table[ ][ ] = new int[10][20];

In the case of multi-dimensional arrays, you must use an index for each dimension to access
an element. The first index is the row and the second index is the column.

ALGORITHM : Declare three matrices as A[] & B[] and c[]

Declare three integers i,j,k with initial value of 0.

Read the values for A[] & B[] using for loop.

Multiply the two matrices to have c[] as

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 19


Object Oriented Programming using JAVA Laboratory

Repeat until (i<=3)

Repeat until(j<=3)

Repeat until(k<=3)

C[i][j]=A[i][k] *B[k][j]

Add the two matrices to have add[]

Repeat until(i<=3)

Repeat until(j<=3)

add[i][j]=A[i][j] +B[i][j]

Subtract the two matrices to have sub[]

Repeat until(i<=3)

Repeat until(j<=3)

add[i][j]=A[i][j] -B[i][j]

Print c[i][j] , add[i][j] ,sub[i][j] using for loop.

Conclusion: Thus we have studied concepts of arrays

Sample Expert Viva-vice Questions:


1. What is array?
2. How will you define array in java?
3. How will you initialize arrays?
4. Explain need of multidimensional array.
5. Explain different methods of defining array.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 20


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:06
Title: Write a program for objects and classes in java.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 21


Object Oriented Programming using JAVA Laboratory

Experiment No.: 06
Name of Experiment: Write a program for objects and classes in java.

Aim: Study the objects and classes in java

a) Define a class to represent a bank account, include the following


members:

Data:

i. name of the depositor

ii. account number

iii. type of account

iv. balance amount in the account

Methods:

i. Ito assign initial values


ii. to deposit an amount
iii. to withdraw an amount after checking balance.
iv. to display the name & balance

b) Write a program using this keyword

Equipments/Machines: Win XP OS, JDK

Theory:
Classes and objects are not the same thing. A class is a type definition, where as an
object is a declaration of an instance of a class type. Once you create a class, you can create
as many objects based on that class as you want. The same relationship exists between classes
and objects as between cherry pie recipes and cherry pies; you can make as many cherry pies
as you want from a single recipe. The process of creating an object from a class is referred to
as instantiatin an object or creating an instance of a class.

Declaring and instantiating classes

A class in Java can be very simple. Here is a class definition for an empty class:

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 22


Object Oriented Programming using JAVA Laboratory

class MyClass { }

While this class is not yet useful, it is legal in Java. A more useful class would contain some
data members and methods.To create an instance of this class, use the new operator in
conjunction with the class name. You must declare an instance variable for the object:

MyClass myObject;

Just declaring an instance variable doesn’t allocate memory and other resources for the
object, however. Doing so creates a reference called myObject , but it doesn’t instantiate the
object. The new operator performs this task.

myObject =new MyClass();

Once you have created the object, you never have to worry about destroying it. Objects in
Java are automatically garbage collected.

Data members:

A class in Java can contain both data members and methods. A data member or member
variable is a variable declared within the class. A method is a function or routine that
performs some task. Here is a class that contains just data members:

public class DogClass

String name,eyeColor;

int age;

boolean hasTail;

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 23


Object Oriented Programming using JAVA Laboratory

Class methods:

You can also include methods in classes. In fact, there are no standalone functions or
procedures in Java. All subroutines are defined as methods of classes. Here is an example of
DogClass with a speak()method added:

public class DogClass

String name,eyeColor;

int age;

boolean hasTail;

public void speak(){

JOptionPane.showMessageDialog(null,"Woof!Woof!");

Notice that when you define methods, the implementation for the method appears directly
below the declaration. This is unlike some other object-oriented languages where the class is
defined in one location and the implementation code appears somewhere else. A method must
specify a return type and any parameters received by the method.

ALGORITHM : 1. Create a class Bank with data members

As name, acc type-String and balance as double.

Write the method to get the data.

Write the method to withdraw the amount

Write the method to deposit the amount

Create another class BankAccount

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 24


Object Oriented Programming using JAVA Laboratory

Create the objects of class Bank as b1.

Access the methods of Bank using b1.

Conclusion: Thus we have studied the implementation of objects and


classes in java.

Sample Expert Viva-vice Questions:


1. Why is main method assigned as public?
2. Why main method is assigned as static?
3. What is class and object?
4. What are the OOP Principles?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 25


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:07
Title: Write a program to study concepts of Strings.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 26


Object Oriented Programming using JAVA Laboratory

Experiment No.: 07
Name of Experiment: Write a program to study concepts of Strings.

Aim: Study concepts of Strings

Accept the two strings from user and do the following operations:

1. convert to lowercase

2. convert to uppercase

3. Replace all appearance of one character by another

4. Compare two strings

5. Derive the substring of a string

6. Derive the position of a character in a string

7. Calculate the length of a string

8. Derive the nth character of a string

Equipments/Machines: Win XP OS, JDK

Theory:
String defines and supports character strings. In many other programming languages a string is an
array of characters. This is not the case with Java. In Java, strings are objects.

Constructing Strings:

You can construct a String just like you construct any other type of object: by using new and calling
the String constructor. For example:

String str = new String("Hello");

This creates a String object called str that contains the character string "Hello". You can also
construct a String from another String.Another easy way to create a String is shown here:

String str = "Java strings are powerful.";

In this case, str is initialized to the character sequence "Java strings are powerful."

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 27


Object Oriented Programming using JAVA Laboratory

Operating on Strings The String class contains several methods that operate on strings.

Method Name Description

boolean equals(String str) Returns true if the invoking string contains the same character

sequence as str.

Char charAt(int index) Obtains the character at the index specified by index.

int compareTo(String str) Returns less than zero if the invoking string is less than str, greater

than zero if the invoking string is greater than str, and zero if the

strings are equal.

int indexOf(String str) Searches the invoking string for the substring specified by str. Returns

the index of the first match or .1 on failure.

int lastIndexOf(String str) Searches the invoking string for the substring specified by str. Returns

the index of the last match or .1 on failure.

int length( ) Obtains the length of a string.

The contents of a String object are immutable. That is, once created, the character sequence that
makes up the string cannot be altered. This restriction allows Java to implement strings more
efficiently. Java offers a class called StringBuffer, which creates string objects that can be changed.

ALGORITHM: Declare the two strings in a class.


Call the necessary functions to perform the operation.

Conclusion: Thus we have studied concepts of strings.

Sample Expert Viva-vice Questions:


1. What is a String in Java?
2. What is the difference between a String in Java and String in C/C++?
3. Name a few String methods.
4. Difference between string and array.
5. Can we access individual elements in string like a array?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 28


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:08
Title: Write a program to study different constructors in java.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 29


Object Oriented Programming using JAVA Laboratory

Experiment No.: 08
Name of Experiment: Write a program to study different constructors in
java.

Aim: study different constructors in java

a) Default constructor
b) Parameterized constructor

Equipments/Machines: Win XP OS, JDK

Theory:

In object-oriented programming, a constructor (sometimes shortened to ctor) in a class is a


special type of subroutine called to create an object. It prepares the new object for use, often
accepting parameters that the constructor uses to set member variables required for the object
to reach a valid state. It is called a constructor because it constructs the values of data
members of the class.

A constructor resembles an instance method, but it differs from a method in that it has no
explicit return type, it is not implicitly inherited and it usually has different rules for scope
modifiers. Constructors often have the same name as the declaring class. They have the task
of initializing the object's data members and of establishing the invariant of the class, failing
if the invariant is invalid. A properly written constructor leaves the resulting object in a valid
state. Immutable objects must be initialized in a constructor.

Programmers also use the term constructor to denote one of the tags that wraps data in an
algebraic data type. This is a different usage than in this article

Most languages allow overloading the constructor in that there can be more than one
constructor for a class, with differing parameters. Some languages take consideration of some
special types of constructors.

Default constructors

If the programmer does not supply a constructor for an instantiable class, a typical compiler will
provide a default constructor. The behavior of the default constructor is language dependent. It may
initialize data members to zero or other same values, or it may do nothing at all.

Copy constructors

Copy constructors define the actions performed by the compiler when copying class objects. A copy
constructor has one formal parameter that is the type of the class (the parameter may be a reference to
an object). It is used to create a copy of an existing object of the same class. Even though both classes
are the same, it counts as a conversion constructor. A constructor is a special type of method.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 30


Object Oriented Programming using JAVA Laboratory

Conversion constructors

Conversion constructors provide a means for a compiler to implicitly create an object belonging to
one class based on an object of a different type. These constructors are usually invoked implicitly to
convert arguments or operands to an appropriate type, but they may also be called explicitly.

Parameterized constructors
Constructors that can take arguments are termed as parameterized constructors.

RULES FOR CONSTRUCTOR:

1.A java constructor has the same name as the name of the class to which it belongs.
Constructor’s syntax does not include a return type, since constructors never return a value.

2.Constructors may include parameters of various types. When the constructor is invoked
using the new operator, the types must match those that are specified in the constructor
definition.

3.Java provides a default constructor which takes no arguments and performs no special
actions or initializations, when no explicit constructors are provided.

4.The only action taken by the implicit default constructor is to call the superclass constructor
using the super() call. Constructor arguments provide you with a way to provide parameters
for the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one
parameterized constructor).
Algorithm:
1.define class
2.define default constructor.
3.define parameterized constructor.
4.define main method.
5.stop

Note: If a class defines an explicit constructor, it no longer has a default constructor to set the
state of the objects. If such a class requires a default constructor, its implementation must be
provided. Any attempt to call the default constructor will be a compile time error if an explicit
default constructor is not provided in such a case.

Conclusion: Thus we have studied study different constructors in java

Sample Expert Viva-vice Questions:


1. State the rules for constructor.
2. Does constructor returns any value.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 31


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:09
Title: Write a program to study the interface in java.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 32


Object Oriented Programming using JAVA Laboratory

Experiment No.: 09
Name of Experiment: Write a program to study the interface in java.

Aim: study of interface in java.

Equipments/Machines: Win XP OS, JDK

Theory:
An interface is a collection of method names, without definitions, that can be added to classes
to provide additional behavior not included with those methods the class defined itself or
inherited from its superclasses. Although a single Java class can have only one superclass
(due to single inheritance), that class can also implement any number of interfaces. By
implementing an interface, a class provides method implementations (definitions) for the
method names defined by the interface. If two very disparate classes implement the same
interface, they can both respond to the same method calls (as defined by that interface),
although what each class actually does in response to those method calls may be very
different.

Using Interface:

public interface SoundInterface

public void speak();

Note that the interface keyword is used instead of class . All methods declared in an interface
are public by default, so there is no need to specify accessibility. A class can implement an
interface by using the implements keyword. Also, a class can extend only one other class, but
a class can implement as many interfaces as necessary.eg.

abstract public class MammalClass implements SoundInterface

//accessor methods for properties

//name

public String getName(){

return name;

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 33


Object Oriented Programming using JAVA Laboratory

ALGORITHM : Create an interface area with suitable variable(pi,n)

and methods (compute(float x,float y)).

Create class circle triangle and rectangle that


implements interface area.

Create class Itest to make the objects of triangle,circle &


rectangle.

Call the compute method by each object to print area of


the shape.

Conclusion: Thus we have studied the interface in java.

Sample Expert Viva-vice Questions:


1. Define an interface.
2. What is the need for an interface?
3. What are the properties of an interface?
4. Differentiate interface and inheritance?
5. What is significance of interface in java?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 34


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:10
Title: Write a program to study utility package in java.

Date Of Experiment Date Of Submission

Remark Signature

Experiment No.: 10

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 35


Object Oriented Programming using JAVA Laboratory

Name of Experiment: Write a program to study utility package in java.

Aim: Study of utility package in java

a) WAP to generate a year using random class and check whether it is


leap or not.

b) Write a program to display current date. Also display Time in hours


and Minutes using Date class.

Equipments/Machines: Win XP OS, JDK

Theory:

The Random class creates objects that manage independent sequences of pseudorandom numbers.
You can gain more control over the sequence (for example, the ability to set the seed) by creating a
Random object and getting values from it.

public Random() Creates a new random number generator. Its seed will be initialized to a value
based on the current time.

public Random(long seed) Creates a new random number generator using the specified seed. Two
Random objects created with the same initial seed will return the same sequence of pseudorandom
numbers.

public void setSeed(long seed) Sets the seed of the random number generator to seed. This method
can be invoked at any time and resets the sequence to start with the given seed.

public boolean nextBoolean() Returns a pseudorandom uniformly distributed boolean value.

public int nextInt() Returns a pseudorandom uniformly distributed int value between the two values
Integer.MIN_VALUE and Integer.MAX_VALUE, inclusive.

public int nextInt(int ceiling) Like nextInt(), but returns a value that is at least zero and is less than
the value ceiling. Use this instead of using nextInt() and % to get a range. If ceiling is negative, an
IllegalArgumentException is thrown.

public long nextLong() Returns a pseudorandom uniformly distributed long value between
Long.MIN_VALUE and Long.MAX_VALUE, inclusive.

public void nextBytes(byte[] buf) Fills the array buf with random bytes.

public float nextFloat() Returns a pseudorandom uniformly distributed float value between 0.0f
(inclusive) and 1.0f (exclusive).

public double nextdouble() Returns a pseudorandom uniformly distributed double value between 0.0
(inclusive) and 1.0 (exclusive).

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 36


Object Oriented Programming using JAVA Laboratory

public double nextGaussian() Returns a pseudorandom Gaussian-distributed double value with mean
of 0.0 and standard deviation of 1.0.

All the nextType methods use the protected method next. The next method takes an int that represents
the number of random bits to produce (between 1 and 32) and returns an int with that many bits. These
random bits are then converted to the requested type. For example, nextInt simply returns next(32),
while nextBoolean returns True if next(1) is not zero, else it returns false. We can safely use Random
from multiple threads.

Time is represented as a long integer measured in milliseconds since midnight Greenwich Mean Time
(GMT) January 1, 1970. This starting point for time measurement is known as the epoch. This value is
signed, so negative values signify time before the beginning of the epoch. The
System.currentTimeMillis method returns the current time. This value will express dates into the year
A.D. 292,280,995, which should suffice for most purposes.

We can use java.util.Date to hold a time and perform some simple time-related operations. When a
new Date object is created, you can specify a long value for its time. If we use the no-arg
constructor, the Date object will mark the time of its creation. A Date object can be used for simple
operations. For example, the simplest program to print the current time is

Algorithm:
1. import java.util.Date;
2. class Date2
3. public static void main(String[] args)
4. Date now = new Date();
5. System.out.println(now);

Note that this is not localized output. No matter what the default locale, the date will be in this format,
adjusted for the current time zone.

You can compare two dates with the before and after methods, which return True if the object on
which they are invoked is before or after the other date. Or you can compare the long values you get
from invoking getTime on the two objects. The method setTime lets you change the time to a different
long.

Conclusion: Thus we have studied utility package in java.

Sample Expert Viva-vice Questions:


1. What are different utility packages in java?
2. What is constructor?
3. What is destructor?
4. Why main() is public?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 37


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:11
Title: Write a program to study concepts of inheritance.

Date Of Experiment Date Of Submission

Remark Signature

Experiment No.: 11

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 38


Object Oriented Programming using JAVA Laboratory

Name of Experiment: Write a program to study concepts of inheritance.

Aim: study concepts of inheritance

Implement above class hierarchy by adding suitable variables and methods

Equipments/Machines: Win XP OS, JDK

Theory:
Inheritance is one of the three foundation principles of object-oriented programming because it allows
the creation of hierarchical classifications.

Inheritance Basics:
Java supports inheritance by allowing one class to incorporate another class into its declaration. This
is done by using the extends keyword. Thus, the subclass adds to (extends) the superclass. When a
class inherits from another class, the child class automatically inherits all the characteristics (member
variables) and behavior (methods) from the parent class. Inheritance is always additive; there is no
way to inherit from a class and get less than what the parent class has. Inheritance in Java is handled
through the keyword extends . When one class inherits from another class, the child class extends the
parent class. For example,

public class DogClass extends MammalClass

...

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 39


Object Oriented Programming using JAVA Laboratory

The items that men and dogs have in common could be said to be common to all mammals; therefore,
you can create a MammalClass to handle these similarities.

Access modifiers:
It’s important to understand when members (both variables and methods)

in the class are accessible.

Access from within class’s package

Access Modifier Inherited Accessible


default (no modifier) Yes Yes

Public Yes Yes

Protected Yes Yes

Private No No

Access outside of a package

The rules change if you access code outside of your class’s package:

Access Modifier Inherited Accessible


default (no modifier No No

Public Yes Yes

Protected Yes No

Private No No

ALGORITHM : Create class Staff with appropriate member variables


(code , name address) & methods.

Create classes Teacher, officer, Typist Staff

Create classes Regular, Causal which extends

Typist.

Create objects of Teacher, typist, Officer.


Display the values using display method.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 40


Object Oriented Programming using JAVA Laboratory

Conclusion: Thus we have studied the concepts of inheritance.

Sample Expert Viva-vice Questions:


1. What is Inheritance?
2. Define Inheritance.
3. What are the types of inheritance?
4. How is multiple inheritances achieved in java?
5. What are access modifiers?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 41


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:12
Title: Write a program to study concept of exception handling in java.

Date Of Experiment Date Of Submission

Remark Signature

Experiment No.: 12

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 42


Object Oriented Programming using JAVA Laboratory

Name of Experiment: Write a program to study concept of exception


handling in java.

Aim: study concept of exception handling in java.

Equipments/Machines: Win XP OS, JDK

Theory:
An exception is an error that occurs at run time.Using Java’s exception handling subsystem you can,
in a structured and controlled manner, handle run-time errors. Although most modern programming
languages offer some form of exception handling, Java’s support for it is cleaner and more flexible
than most others.

The Exception Hierarchy:


In Java, all exceptions are represented by classes. All exception classes are derived from a class called
Throwable. Thus, when an exception occurs in a program, an object of some type of exception class is
generated. There are two direct subclasses of Throwable: Exception and Error. Exceptions of type
Error are related to errors that occur in the Java virtual machine itself, and not in your program. These
types of exceptions are beyond your control, and your program will not usually deal with them. Thus
Errors that result from program activity are represented by subclasses of Exception. For example,
divide-by-zero, array boundary, and file errors fall into this category.

Exception Handling Fundamentals:


Java exception handling is managed via five keywords: try, catch, throw, throws and finally. They
form an interrelated subsystem in which the use of one implies the use of another. Program statements
that you want to monitor for exceptions are contained within a try block. If an exception occurs within
the try block, it is thrown. Your code can catch this exception using catch and handle it in some
rational manner. System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw. In some cases, an exception that is thrown
out of a method must be specified as such by a throws clause. Any code that absolutely must be
executed upon exiting from a try block is put in a finally block.

Using try and catch


At the core of exception handling are try and catch. These keywords work together; you can’t have a
try without a catch, or a catch without a try. Here is the general form of the try/catch exception
handling blocks:

try {

// block of code to monitor for errors

catch (ExcepType1 exOb) {

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 43


Object Oriented Programming using JAVA Laboratory

// handler for ExcepType1

catch (ExcepType2 exOb) {

// handler for ExcepType2

Using throw:
It is possible to manually throw an exception by using the throw statement. Its

general form is shown here.

throw exceptOb;

Here, exceptOb must be an object of an exception class derived from Throwable.

Using finally:
To specify a block of code to execute when a try/catch block is exited, include a finally block at the
end of a try/catch sequence. The general form of a try/catch that includes finally is shown here.

try {

// block of code to monitor for errors

catch (ExcepType1 exOb) {

// handler for ExcepType1

finally {

// finally code

Using throws:
In some cases, if a method generates an exception that it does not handle, it must declare that
exception in a throws clause. Here is the general form of a method that includes a throws clause.

ret-type methName(param-list) throws except-list

{// body

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 44


Object Oriented Programming using JAVA Laboratory

Conclusion: Thus we have studied the concept of exception handling in


java.

Sample Expert Viva-vice Questions:

1. What are Checked and UnChecked Exception?


2. What are checked exceptions?
3. What are runtime exceptions?
4. What is the difference between error and an exception?
5. What classes of exceptions may be caught by a catch clause?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 45


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:13
Title: Write a program to study the concept of multithreading.

Date Of Experiment Date Of Submission

Remark Signature

Experiment No.: 13

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 46


Object Oriented Programming using JAVA Laboratory

Name of Experiment: Write a program to study the concept of


multithreading.

Aim: Study the concept of multithreading

To create three threads as A,B,C. Thrad A has maximum priority, thread B


has minimum priority, thread C has normal priority. Thread B strats first,
then thread C then thread A.

Equipments/Machines: Win XP OS, JDK

Theory:

In a thread-based multitasking environment, the thread is the smallest unit of dispatchable


code. This means that a single program can perform two or more tasks at once. The principal
advantage of multithreading is that it enables you to write very efficient programs because it
lets you utilize the idle time that is present in most programs. A thread can be in one of
several states. It can be running. It can be ready to run as soon as it gets CPU time. A running
thread can be suspended, which is a temporary halt to its execution. It can later be resumed. A
thread can be blocked when waiting for a resource. A thread can be terminated, in which case
its execution ends and cannot be resumed. Along with thread-based multitasking comes the
need for a special type of feature called synchronization, which allows the execution of
threads to be coordinated in certain well-defined ways. Java has a complete subsystem
devoted to synchronization, and its key features are also described here.

The Thread Class and Runnable Interface

Java’s multithreading system is built upon the Thread class and its companion interface,

Runnable. Thread encapsulates a thread of execution. To create a new thread, your program
will either extend Thread or implement the Runnable interface. The Thread class defines
several methods that help manage threads. Here are some of the more commonly used ones
(we will be looking at these more closely as they are used):

Method Meaning

final String getName( ) Obtains a thread’s name.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 47


Object Oriented Programming using JAVA Laboratory

final int getPriority( ) Obtains a thread’s priority.

final void setPriority(int level) set the thread priority.

final boolean isAlive( ) Determines whether a thread is still running.

final void join( ) Waits for a thread to terminate.

void run( ) Entry point for the thread.

static void sleep(long milliseconds) Suspends a thread for a specified period of


milliseconds.

void start( ) Starts a thread by calling its run( ) method.

All processes have at least one thread of execution, which is usually called the main thread,
because it is the one that is executed when your program begins. Thus, the main thread is the
thread that all of the preceding example programs in the book have been using. From the
main thread, you can create other threads.

Creating a Thread:

You create a thread by instantiating an object of type Thread. The Thread class encapsulates
an object that is runnable. As mentioned, Java defines two ways in which you can create a
runnable object:

 .You can implement the Runnable interface.


 .You can extend the Thread class.
Thread defines several constructors. The one that we will use first is shown here:

Thread(Runnable threadOb)

In this constructor, threadOb is an instance of a class that implements the Runnable


interface. This defines where execution of the thread will begin.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 48


Object Oriented Programming using JAVA Laboratory

Conclusion: Thus we have studied the concept of multithreading

Sample Expert Viva-vice Questions:


1. What is thread?
2. Explain different way of using thread?
3. When a thread is created and started, what is its initial state?
4. What are the states of a thread?
5. What are synchronized methods and synchronized statements?
6. What is multithreading?

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 49


Object Oriented Programming using JAVA Laboratory

Bharati Vidyapeeth College of Engineering


Department of Electronics & Telecommunication Engineering

Experiment No.:14
Title: Write a program to study graphics using applet.

Date Of Experiment Date Of Submission

Remark Signature

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 50


Object Oriented Programming using JAVA Laboratory

Experiment No.: 14

Name of Experiment: Write a program to study graphics using applet.

Aim: Program to draw all geometric shapes and fill them with different
colors.

Equipments/Machines: Win XP OS, JDK

Theory:
One of Java’s design goals is to create applets, which are little programs that run inside a Web
browser. Because they must be safe, applets are limited in what they can accomplish. However,
applets are powerful tools that support client-side programming, a major issue for the Web.

Application frameworks:

Applets are built using an application framework. You inherit from class Applet and override the
appropriate methods. There are a few methods that control the creation and execution of an applet on a
Web page:

Method Operation

init( ) Automatically called to perform first-time initialization

of the applet, including component layout. You’ll always


override this method.

start( ) Called every time the applet moves into sight on the

Web browser to allow the applet to start up its normal


operations (especially those that are shut off by stop( )).Also
called after init( ).

stop( ) Called every time the applet moves out of sight on the

Web browser to allow the applet to shut off expensive

operations. Also called right before destroy( ).

destroy( ) Called when the applet is being unloaded from the page to
perform final release of resources when the applet is no
longer used.

import java.awt.*;

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 51


Object Oriented Programming using JAVA Laboratory

import java.applet.*;

public class SimpleApplet extends Applet

public void paint(Graphics g)

g.drawString("Java makes applets easy.", 20, 20);

This applet begins with two import statements. The first imports the Abstract Window Toolkit
(AWT) classes. Applets interact with the user through the AWT, not through the console-based I/O
classes. The AWT contains support for a window-based, graphical interface.. The next import
statement imports the applet package. This package contains the class Applet. Every applet that you
create must be a subclass of Applet. The next line in the program declares the class SimpleApplet.
This class must be declared as public because it will be accessed by outside code. Inside
SimpleApplet, paint( ) is declared. This method is defined by the AWT Component class (which is a
superclass of Applet) and must be overridden by the applet. paint( ) is called each time the applet
must redisplay its output.

The paint( ) method has one parameter of type Graphics.This parameter will contain the graphics
context, which describes the graphics environment in which the applet is running. This context is used
whenever output to the applet is required. Inside paint( ), there is a call to drawString( ), which is a
member of the Graphics class. This method outputs a string beginning at the specified X,Y location.
It has the following general form:

void drawString(String message, int x, int y)

Here, message is the string to be output beginning at x,y. In a Java window, the upper-left corner is
location 0,0. The call to drawString( ) in the applet causes the message to be displayed beginning at
location 20,20. Notice that the applet does not have a main( ) method.

After you have entered the source code for SimpleApplet, you compile in the same way that you have
been compiling programs. However, running SimpleApplet involves a differentprocess. There are
two ways in which you can run an applet: inside a browser or with a special development tool that

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 52


Object Oriented Programming using JAVA Laboratory

displays applets. The tool provided with the standard Java JDK is called appletviewer, and we will
use it to run the applets developed in this module. Of course, you can also run them in your browser,
but the appletviewer is much easier to use during development. To execute an applet (in either a Web
browser or the appletviewer), you need to write a short HTML text file that contains the appropriate
APPLET tag. (You can also use the newer OBJECT tag, but this book will use APPLET because this
is the traditional approach.) Here is the HTML file that will execute SimpleApplet:

<applet code="SimpleApplet" width=200 height=60>

</applet>

The width and height statements specify the dimensions of the display area used by the applet.

To execute SimpleApplet with an applet viewer, you will execute this HTML file. For

example, if the preceding HTML file is called StartApp.html, then the following command line will
run SimpleApplet:

C:\>appletviewer StartApp.html

Conclusion: Thus we have studied the graphics using applet.

Sample Expert Viva-vice Questions:


1. What is an applet program?
2. What is applet viewer?
3. Compare Application and Applet.
4. List various stages of applet.
5. Explain import statement.

Department of Electronics & Telecommunication Engineering, B.V.C.O.E., NAVI MUMBAI 53

You might also like