Download System.out.println("METHOD of A")

Document related concepts
no text concepts found
Transcript
Prince Pinto
13302A0033
PRACTICAL NO-01
Aim:-a) Design a Java Program for Type Casting Different types of variables.
Type casting:
 Type casting stores value of one type into a variable of another type.
 Syntax : Type variable=(type)variable2
 For egint x=10
byte y=(byte)x //casting into smaller type results into data loss
float z=(float)x // No loss of data
float a=2.56f
int b=(int)a
// loss of fractional part
Program:Typecasting.java
package typecasting;
import java.util.*;
public class Typecasting {
public static void main(String[] args) {
char c='x';
byte b=60;
int i=12345;
short s=1995;
float f=3145;
System.out.println ("VARIABLES BEFORE CASTING");
System.out.println ("f in float"+" " +f);
System.out.println ("b in byte "+" "+b);
System.out.println ("s in short "+" "+b);
short s1=(short)f;
float s2=(float)b;
int i1=(int)s;
System.out.println(" VARIABLE AFTER CASTING");
System.out.println ("f in short "+s1);
System.out.println ("b in float "+s2);
System.out.println ("s in int "+i1);
}
1
Prince Pinto
13302A0033
}
Output:
2
Prince Pinto
13302A0033
PRACTICAL NO-01
Aim:-b) Design a calculator class in java, and implement all the methods
required by calculator operations.
Methods: A Java method is a collection of statements that are grouped together
to perform an operation. When you call the System.out.println method,
for example, the system actually executes several statements in order
to display a message on the console.
Creating a Method:
 In general, a method has the following syntax:
modifier returnValueType methodName(list of
parameters) {
// Method body;
}
 A method definition consists of a method header and a method body.
Here are all the parts of a method:





Modifiers: The modifier, which is optional, tells the compiler how to call
the method. This defines the access type of the method.
Return Type: A method may return a value. The returnValueType is the
data type of the value the method returns. Some methods perform the
desired operations without returning a value. In this case, the
returnValueType is the keyword void.
Method Name: This is the actual name of the method. The method name
and the parameter list together constitute the method signature.
Parameters: A parameter is like a placeholder. When a method is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the type, order,
and number of the parameters of a method. Parameters are optional; that
is, a method may contain no parameters.
Method Body: The method body contains a collection of statements that
define what the method does.
3
Prince Pinto
13302A0033
Example:
 Here is the source code of the above defined method called max(). This
method takes two parameters num1 and num2 and returns the maximum
between the two:
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Calling a Method:
 In creating a method, you give a definition of what the method is to do.
To use a method, you have to call or invoke it. There are two ways to call
a method; the choice is based on whether the method returns a value or
not.
 When a program calls a method, program control is transferred to the
called method. A called method returns control to the caller when its
return statement is executed or when its method-ending closing brace is
reached.
 If the method returns a value, a call to the method is usually treated as a
value. For example:
int larger = max(30, 40);
4
Prince Pinto
13302A0033
 If the method returns void, a call to the method must be a statement. For
example, the method println returns void. The following call is a
statement:
System.out.println("Welcome to Java!");
Program:Calculator.java
package calculator;
import java.util.Scanner;
class Calcu {
float x,y;
float add(float x,float y)
{
return (x+y);
}
float sub(float x,float y)
{
return (x-y);
}
float mult(float x,float y)
{
return (x*y);
}
float div(float x,float y)
{
return (x/y);
}
}
public class Calculator{
public static void main(String[] args) {
Scanner in=new Scanner(System.in);
Calcu c=new Calcu();
System.out.println ("Enter any two numbers:");
float a=Integer.parseInt(in.nextLine());
float b=Integer.parseInt(in.nextLine());
System.out.println ("Addition of two numbers:"+c.add(a,b));
5
Prince Pinto
13302A0033
System.out.println("Subtraction of two numbers:"+c.sub(a,b));
System.out.println ("Multiplication of two numbers:"+c.mult(a,b));
System.out.println ("Division of two numbers:"+c.div(a,b));
}
}
Output:-
6
Prince Pinto
13302A0033
PRACTICAL NO-01
Aim:-c) Design a java class for method overloading and method overriding.
Method overloading & overriding: Overloading happens at compile-time while Overriding happens at runtime:
The binding of overloaded method call to its definition has happens at
compile-time however binding of overridden method call to its definition
happens at runtime.
 Static methods can be overloaded which means a class can have more than
one static method of same name. Static methods cannot be overridden, even
if you declare a same static method in child class it has nothing to do with
the same method of parent class.
 The most basic difference is that overloading is being done in the same class
while for overriding base and child classes are required. Overriding is all
about giving a specific implementation to the inherited method of parent
class.
 Static binding is being used for overloaded methods and dynamic binding is
being used for overridden/overriding methods.
 Performance: Overloading gives better performance compared to
overriding. The reason is that the binding of overridden methods is being
done at runtime.
 Private and final methods can be overloaded but they cannot be overridden.
It means a class can have more than one private/final methods of same name
but a child class cannot override the private/final methods of their base
class.
 Return type of overloaded methods should be same however in case of
method overriding the return type of overriding method can be different
from overridden method.
 Argument list should be different while doing method overloading.
Argument list should be same in method Overriding.
7
Prince Pinto
13302A0033
Program:Overloading.java
package overloading1;
import java.util.*;
class display2
{
public void disp(char c)
{
System.out.println(c);
}
public void disp(char c,int num)
{
System.out.println(c+" "+num);
}
}
class Overloading1 {
public static void main(String[] args) {
display2 obj=new display2();
obj.disp('a');
obj.disp('a',20);
}
}
Output:
8
Prince Pinto
13302A0033
Overriding.java
Program:
package overiding;
import java.util.*;
class carclass
{
public int speedlimit()
{
return 100;
}
}
class Overiding extends carclass
{
public int speedlimit()
{
return 150;
}
public static void main(String[] args) {
carclass obj= new Overiding();
int num=obj.speedlimit();
System.out.println("speed limit is"+""+num);
}
}
Output
9
Prince Pinto
13302A0033
PRACTICAL NO-02
Aim:-a) Design a java program for different types of inheritance.
Inheritance: The idea of inheritance is simple but powerful: When you want to create
a new class and there is already a class that includes some of the code that
you want, you can derive your new class from the existing class. In doing
this, you can reuse the fields and methods of the existing class without
having to write (and debug!) them yourself.
 A subclass inherits all the members (fields, methods, and nested classes)
from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be
invoked from the subclass.
Private Members in a Superclass
 A subclass does not inherit the private members of its parent class.
However, if the superclass has public or protected methods for accessing
its private fields, these can also be used by the subclass.
 A nested class has access to all the private members of its enclosing
class—both fields and methods. Therefore, a public or protected nested
class inherited by a subclass has indirect access to all of the private
members of the superclass.
Casting Objects
 We have seen that an object is of the data type of the class from which it
was instantiated. For example, if we write
public MountainBike myBike = new MountainBike();
then myBike is of
type MountainBike.
 MountainBike is descended from Bicycle and Object. Therefore,
a MountainBike is a Bicycle and is also an Object, and it can be
used wherever Bicycle or Object objects are called for.
 The reverse is not necessarily true: a Bicycle may be a
MountainBike, but it isn't necessarily. Similarly, an Object may be
a Bicycle or a MountainBike, but it isn't necessarily.
10
Prince Pinto
13302A0033
 Casting shows the use of an object of one type in place of another type,
among the objects permitted by inheritance and implementations. For
example, if we write
Object obj = new MountainBike();
Types of Inheritance
 On the basis of class, there can be three types of inheritance: single,
multilevel and hierarchical.
 Multiple and Hybrid is supported through interface only. We will learn
about interfaces later.
Program:
Single inheritance
Singleinheritance.java
import java.util.*;
class vehicle
{
String color;
int speed;
int size;
void attributes(){
System.out.println("color"+color);
System.out.println("speed is"+speed);
System.out.println("size is"+size);
11
Prince Pinto
13302A0033
}
}
class car extends vehicle{
int cc;
int gears;
void attributes12(){
System.out.println("color of car:"+" "+color);
System.out.println("speed of car"+" "+speed);
System.out.println("size of car"+" "+size);
System.out.println("cc of car"+" "+cc);
System.out.println("no of gears"+" "+gears);
}
}
public class singleinherit {
public static void main(String[] args) {
car b1=new car();
b1.color="red";
b1.speed=200;
b1.size=22;
b1.cc=1000;
b1.gears=5;
b1.attributes12();
}
}
Output:
12
Prince Pinto
13302A0033
Multilevel inheritance:
Multilevel.java
Program:
package multilevel;
import java.util.*;
class car{
public car()
{
System.out.println("class car");
}
public void vehicletype()
{
System.out.println("vehicle type: car");
}
}
class maruti extends car{
public maruti()
{
System.out.println ("class maruti");
}
public void brand()
{
System.out.println("brand :maruti");
}
public void speed(){
System.out.println("Max:90kmph");
}
}
public class Multilevel extends maruti{
public Multilevel()
{
System.out.println("maruti model:800");
}
public void speed()
{
System.out.println("max:80kmph");
}
public static void main(String[] args) {
13
Prince Pinto
13302A0033
// TODO code application logic here
Multilevel obj=new Multilevel();
obj.vehicletype();
obj.brand();
obj.speed();
}
}
Output
Hierarchical inheritance
Program:
Heirarchical.java
package heirarcy;
import java.util.*;
class A
{
public void methodA()
{
System.out.println("METHOD of A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("methid of b");
}
14
Prince Pinto
13302A0033
}
class C extends A
{
public void methodC()
{
System.out.println("meyhod of c");
}
}
class D extends A
{
public void methodD()
{
System.out.println("METHOD of D");
}
}
public class Heirarcy {
public void methodB()
{
System.out.println("method of class B");
}
public static void main(String[] args) {
B obj=new B();
C obj1=new C();
D obj2=new D();
obj.methodA();
obj1.methodA();
obj2.methodA();
}
}
OUTPUT-
15
Prince Pinto
13302A0033
PRACTICAL NO-02
Aim:-b) Design a java class for the use of Interface
Interface:
 In the Java programming language, an interface is a reference type,
similar to a class, that can contain only constants, method signatures, and
nested types. There are no method bodies. Interfaces cannot be
instantiated—they can only be implemented by classes or extended by
other interfaces. Extension is discussed later in this lesson.
 Defining an interface is similar to creating a new class:
public interface OperateCar {
// constant declarations, if any
// method signatures
// An enum with values RIGHT, LEFT
int turn(Direction direction,
double radius,
double startSpeed,
double endSpeed);
int changeLanes(Direction direction,
double startSpeed,
double endSpeed);
int signalTurn(Direction direction,
boolean signalOn);
int getRadarFront(double distanceToCar,
double speedOfCar);
int getRadarRear(double distanceToCar,
double speedOfCar);
......
// more method signatures
}
16
Prince Pinto
13302A0033
Program:
Interface.java
package pkginterface;
import java.util.*;
import java.io.*;
interface area
{
float com_area(float b,float h);
}
interface perimeter
{
float com_peri(float a, float b,float c);
float com_perpal(float b, float c);
}
class traingle implements area,perimeter
{
public float com_area(float b,float h)
{
return((b*h)/2);
}
public float com_peri(float a,float b,float c)
{
return(a+b+c);
}
public float com_perpal(float b,float c)
{
return 0;
}
}
class parallelogram implements area,perimeter
{
public float com_area(float b,float h)
{
return(b*h);
}
17
Prince Pinto
13302A0033
public float com_peri(float a,float b,float c)
{
return 0;
}
public float com_perpal(float b,float c)
{
return((2*b)+(2*c));
}
}
public class Interface1 {
public static void main(String[] args) {
// TODO code application logic here
traingle t=new traingle();
parallelogram p=new parallelogram();
System.out.println("Arae of traingle is"+t.com_area(25, 10));
System.out.println("area of parallelogram"+p.com_area(25, 10));
System.out.println("perimter of traingle"+t.com_peri(25, 18, 5));
System.out.println("perimter of parrallelogram"+p.com_perpal(5, 10));
}
}
Output-
18
Prince Pinto
13302A0033
PRACTICAL NO-02
Aim:-c) Design a java class performing string operations
String class and String Operations: Strings, which are widely used in Java programming, are a sequence of
characters. In the Java programming language, strings are objects.
 The Java platform provides the String class to create and manipulate
strings.
 Creating Strings:
 The most direct way to create a string is to write:
 String greeting = "Hello world!";
String Methods:
Methods with Description:-

char charAt(int index)
Returns the character at the specified index.

int compareTo(Object o)
Compares this String to another Object.

int compareTo(String anotherString)
Compares two strings lexicographically.

int compareToIgnoreCase(String str)
Compares two strings lexicographically, ignoring case differences.

String concat(String str)
Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb)
Returns true if and only if this String represents the same sequence of
characters as the specified StringBuffer.
19
Prince Pinto
13302A0033

static String copyValueOf(char[] data)
Returns a String that represents the character sequence in the array
specified.
boolean endsWith(String suffix)
Tests if this string ends with the specified suffix
Program:
String.java
package stringoperation;
import java.util.*;
public class Stringoperation {
public static void main(String[] args) {
String first="",second="";
Scanner sc=new Scanner(System.in);
System.out.print("String operation");
System.out.println();
System.out.print("enter the first string:");
first=sc.nextLine();
System.out.print("enter the second string:");
second=sc.nextLine();
System.out.println("ther strings are:"+first+","+second);
System.out.println("thelength of the first string is :"+first.length());
System.out.println("the length of second string is
"+second.length());
System.out.println("the concatination of first and second string is”
+first.concat(""+second));
System.out.println("the first character of "+first+"is"+"
"+first.charAt(0));
System.out.println("the uppercase of "+first+"is"+"
"+first.toUpperCase());
System.out.println("the lowercase of "+first+"is"+"
"+second.toLowerCase());
20
Prince Pinto
13302A0033
System.out.println("Enter the occurence of a character in"+"
"+first+":");
String str=sc.next();
char c=str.charAt(0);
System.out.println("the"+c+"occurs at
position"+first.indexOf(c)+"in"+first);
System.out.println("The Substring of "+first+" "+"starting from
index 3 and ending at 6 is:"+" "+first.substring(3,7));
System.out.println("Replacing 'a' with 'o' in"+" "+first+"is"+" "+"
"+first.replace('a','o'));
boolean check=first.equals(second);
if(!check)
System.out.println(first+"and"+second+" "+"are not same");
else
System.out.println(first+" "+" "+"and"+second+" "+"are same");
}
}
Output:
21
Prince Pinto
13302A0033
PRACTICAL NO-03
Aim:- a) Design a java class to add two complex numbers using
constructors
Constructors: A constructor initializes an object when it is created. It has the
same name as its class and is syntactically similar to a method.
However, constructors have no explicit return type.
 Typically, you will use a constructor to give initial values to the
instance variables defined by the class, or to perform any other
startup procedures required to create a fully formed object.
 All classes have constructors, whether you define one or not,
because Java automatically provides a default constructor that
initializes all member variables to zero. However, once you
define your own constructor, the default constructor is no longer
used.
Example:
 Here is a simple example that uses a constructor:
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass() {
x = 10;
}
}
 You would call constructor to initialize objects as follows:
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
System.out.println(t1.x + " " + t2.x);
22
Prince Pinto
13302A0033
}
}
 Most often, you will need a constructor that accepts one or more
parameters. Parameters are added to a constructor in the same
way that they are added to a method, just declare them inside the
parentheses after the constructor's name.
Example:
 Here is a simple example that uses a constructor:
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass(int i ) {
x = i;
}
}
 You would call constructor to initialize objects as follows:
public class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass( 10 );
MyClass t2 = new MyClass( 20 );
System.out.println(t1.x + " " + t2.x);
}
}
Program:
Complex.java
package complex;
import java.util.*;
class complex1
{
int real,img;
complex1(int r,int i)
23
Prince Pinto
13302A0033
{
real=r;
img=i;
}
complex1 add (complex1 c1,complex1 c2)
{
complex1 c3=new complex1(0,0);
c3.real=c1.real+c2.real;
c3.img=c1.img+c2.img;
System.out.println("ADDITION OF COMPLEX NO IS"+"
"+c3.real+"+"+c3.img+"i");
return(c3);
}
}
public class Complex {
public static void main(String[] args) {
complex1 c1=new complex1(5,7);
complex1 c2=new complex1(15,7);
complex1 c3=new complex1(0,0);
c3=c3.add(c1, c2);
}
}
OUTPUT:
24
Prince Pinto
13302A0033
PRACTICAL NO-03
Aim:-b) Design a java class for performing all the matrix operations
i.e. Addition, Multiplication, Transpose, Subtraction
Arrays: Java provides a data structure, the array, which stores a fixedsize sequential collection of elements of the same type. An array
is used to store a collection of data, but it is often more useful to
think of an array as a collection of variables of the same type.
 Instead of declaring individual variables, such as number0,
number1, ..., and number99, you declare one array variable such
as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables:
 To use an array in a program, you must declare a variable to
reference the array, and you must specify the type of array the
variable can reference. Here is the syntax for declaring an array
variable:
dataType[] arrayRefVar;
// preferred way.
or
dataType arrayRefVar[];
//
works but not
preferred way.
Example:
 The following code snippets are examples of this syntax:
double[] myList;
// preferred way.
or
double myList[];
// works but not
preferred way.
25
Prince Pinto
13302A0033
Creating Arrays:
 You can create an array by using the new operator with the
following syntax:
arrayRefVar = new dataType[arraySize];
 The above statement does two things:
 It creates an array using new dataType[arraySize];
 It assigns the reference of the newly created array to the variable
arrayRefVar.
 Declaring an array variable, creating an array, and assigning the
reference of the array to the variable can be combined in one
statement, as shown below:
dataType[] arrayRefVar = new
dataType[arraySize];
 Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ...,
valuek};
 Following statement declares an array variable, myList, creates
an array of 10 elements of double type and assigns its reference
to myList:
double[] myList = new double[10];
 Following picture represents array myList. Here, myList holds
ten double values and the indices are from 0 to 9.
26
Prince Pinto
13302A0033
Program:
Matrix.java
package matrixoperation;
import java.util.*;
public class Matrixoperation {
public static void main(String[] args) {
int i,j,k;
int mat1 [][]={ {1,2,3}, {4,5,6}, {7,8,9} };
int mat2 [][]={ {10,11,12}, {13,14,15}, {16,17,18} };
//Matrix A
System.out.println("\nMatrix A:");
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
System.out.print("\t"+mat1[i][j]);
System.out.println("");
}
//Matrix B
System.out.println("\nMatrix B:");
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
System.out.print("\t"+mat2[i][j]);
System.out.println("");
}
System.out.println("\nOperation ON Matrices \n1.Addition \n");
int sum [][] = new int [3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
sum[i][j] = mat1[i][j] + mat2[i][j];
27
Prince Pinto
13302A0033
System.out.print("\t" + sum[i][j]);
}
System.out.println("");
}
System.out.println("2.Subtraction\n");
int diff[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
diff [i][j] = mat1[i][j] - mat2[i][j];
System.out.print("\t"+ diff[i][j]);
}
System.out.println("");
}
System.out.println("3. Transpose Of A\n");
int trans[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
trans [i][j] = mat1[j][i];
System.out.print("\t"+ trans[i][j]);
}
System.out.println("");
}
System.out.println ("4.Multiplication\n");
int prod[][] = new int[3][3];
for(i=0;i< 3;i++)
{
for(j=0;j< 3;j++)
{
prod[i][j] = 0;
{
for(k=0;k< 3;k++)
prod[i][j] = prod[i][j]+mat1[i][k]*mat2[k][j];
}
28
Prince Pinto
13302A0033
System.out.print("\t"+ prod[i][j]);
}
System.out.println("");
}
}
}
Output:
29
Prince Pinto
13302A0033
PRACTICAL NO-03
Aim:-c) Design a java class for implementing the packages
Packages: Package = directory. Java classes can be grouped together in packages. A
package name is the same as the directory (folder) name which contains
the .java files. You declare packages when you define your Java program,
and you name the packages you want to use from other libraries in an
import statement
Program:
package packages;
import java.util.*;
public class Packages {
public static void main(String[] args) {
int a=10;
int b=5;
int c=5;
int x,y;
try
{
x=a/(b-c);
}
catch(ArithmeticException e)
{
System.out.println("Division by zero");
}
y=a/(b+c);
System.out.println("Y:"+y);
}
}
Output:
30
Prince Pinto
13302A0033
PRACTICAL NO-04
Aim:-a) Design a java class for the concept of threading and
multithreading.
Threading and Multithreading
 Java provides built-in support for multithreaded programming. A
multithreaded program contains two or more parts that can run
concurrently. Each part of such a program is called a thread, and each
thread defines a separate path of execution.
 A multithreading is a specialized form of multitasking. Multithreading
requires less overhead than multitasking processing.
 I need to define another term related to threads: process: A process consists
of the memory space allocated by the operating system that can contain one
or more threads. A thread cannot exist on its own; it must be a part of a
process. A process remains running until all of the non-daemon threads are
done executing.
 Multithreading enables you to write very efficient programs that make
maximum use of the CPU, because idle time can be kept to a minimum.
Life Cycle of a Thread:
 A thread goes through various stages in its life cycle. For example, a thread
is born, started, runs, and then dies. Following diagram shows complete life
cycle of a thread.
 New: A new thread begins its life cycle in the new state. It remains in this
state until the program starts the thread. It is also referred to as a born
thread.
 Runnable: After a newly born thread is started, the thread becomes
runnable. A thread in this state is considered to be executing its task.
 Waiting: Sometimes, a thread transitions to the waiting state while the
thread waits for another thread to perform a task.A thread transitions back
31
Prince Pinto
13302A0033
to the runnable state only when another thread signals the waiting thread to
continue executing.
 Timed waiting: A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the
runnable state when that time interval expires or when the event it is
waiting for occurs.
 Terminated: A runnable thread enters the terminated state when it
completes its task or otherwise terminates.
Program:
Thread.java
package multithread;
import java.util.*;
class A extends Thread
{
public void run()
{
System.out.println("Thread A started");
for(int i=1;i<=4;i++)
{
System.out.println("\from Thread A: i="+i);
}
System.out.println("Exit from A");
}
}
class B extends Thread
{
public void run()
{
System.out.println("Thread B started");
32
Prince Pinto
13302A0033
for(int j=1;j<=4;j++)
{
System.out.println("\tFrom Thread B: j="+j);
}
System.out.println("Exit from B");
}
}
class C extends Thread
{
public void run()
{
System.out.println("Thread C started");
for(int k=1;k<=4;k++)
{
System.out.println("\tFrom Thread C: k="+k);
}
System.out.println("Exit from C");
}
}
public class Multithread {
public static void main(String[] args) {
A a= new A();
B b= new B();
C c= new C();
c.setPriority(Thread.MAX_PRIORITY);
b.setPriority(b.getPriority()+1);
33
Prince Pinto
13302A0033
a.setPriority(Thread.MIN_PRIORITY);
System.out.println("Thread A started");
a.start(); System.out.println("Thread B started");
b.start();
System.out.println("Thread C started");
c.start();
System.out.println("End of main thread");
}
}
Output:
34
Prince Pinto
13302A0033
PRACTICAL NO-04
Aim:-b) Design a java class for performing all the file operations
File-Operations
Reading and Writing Files:
 As described earlier, A stream can be defined as a sequence of data. The
InputStream is used to read data from a source and the OutputStream is
used for writing data to a destination.
 Here is a hierarchy of classes to deal with Input and Output streams.
 The two important streams are FileInputStream and FileOutputStream,
which would be discussed in this tutorial:
FileInputStream:
 This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors
available.
 Following constructor takes a file name as a string to create an input stream
object to read the file.:
 InputStream f = new FileInputStream("C:/java/hello");
Program:
package fileop;
import java.io.*;
public class Fileop {
public static void main(String[] args)throws IOException {
// TODO code application logic here
File f=new File("myfile.txt");
if(!f.exists())
{
f.createNewFile();
System.out.println("newfile\"myfile.txt\"has been created " + " to the
current directory");
}
FileWriter fstream=new FileWriter("first.txt");
BufferedWriter out=new BufferedWriter(fstream);
out.write("\n hello Zaid");
out.close();
FileReader fr=new FileReader("first.txt");
int ch;
do{
ch=fr.read();
if(ch!=-1)
System.out.print((char)ch);
}
35
Prince Pinto
13302A0033
while(ch!=-1);
fr.close();
int c;
FileInputStream fis=new FileInputStream("first.txt");
FileOutputStream fos =new FileOutputStream("MyFileOperations.txt");
while((c=fis.read())!=-1)
fos.write(c);
fis.close();
fos.close();
}
}
Output:
Output:
36
Prince Pinto
13302A0033
Program [2]package writefile;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class Writefile {
public static void main(String[] args) {
// TODO code application logic here
try
{
String content="this is the content to write into file";
File file=new File("second.txt");
if(!file.exists()){
file.createNewFile();
}
FileWriter fw=new FileWriter(file);
BufferedWriter bw =new BufferedWriter(fw);
bw.write(content);
bw.close();
System.out.println("Writing is done successfully");
}catch(IOException e)
{
System.out.println(e);
}
}
}
37
Prince Pinto
13302A0033
Output:
Output:
38
Prince Pinto
13302A0033
Practical No-04
Aim: c) Design a java class for operating the random file
Random Access Files







Random access files permit nonsequential, or random, access to a file's contents. To
access a file randomly, you open the file, seek a particular location, and read from or
write to that file.
This functionality is possible with the SeekableByteChannel interface. The
SeekableByteChannel interface extends channel I/O with the notion of a current
position. Methods enable you to set or query the position, and you can then read the
data from, or write the data to, that location. The API consists of a few, easy to use,
methods:
position – Returns the channel's current position
position(long) – Sets the channel's position
read(ByteBuffer) – Reads bytes into the buffer from the channel
write(ByteBuffer) – Writes bytes from the buffer to the channel
truncate(long) – Truncates the file (or other entity) connected to the channel
Program:
package randomfile;
import java.io.*;
public class Randomfile {
public static void main(String[] args) throws IOException{
// TODO code application logic here
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name : ");
String str = in.readLine();
File file = new File(str);
if(!file.exists())
{
System.out.println("File does not exist.");
39
Prince Pinto
13302A0033
System.exit(0);
}
try{
//Open the file for both reading and writing
RandomAccessFile rand = new RandomAccessFile(file,"r");
int i=(int)rand.length();
System.out.println("Length: " + i);
rand.seek(0); //Seek to start point of file
for(int ct = 0; ct < i; ct++){
byte b = rand.readByte();
System.out.print((char)b); //read the character
}
rand.close();
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
40
Prince Pinto
13302A0033
Output:
zaid.txt
Main Output:
41
Prince Pinto
13302A0033
Practical No-05
Aim: a) Design a class for sorting names or numbers in ascending and
descending order
Arrays:Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you
declare one array variable such as numbers and use numbers[0], numbers[1], and ...,
numbers[99] to represent individual variables.
Declaring Array Variables:
To use an array in a program, you must declare a variable to reference the array, and you
must specify the type of array the variable can reference. Here is the syntax for declaring an
array variable:
dataType[] arrayRefVar;
// preferred way.
or
dataType arrayRefVar[];
//
works but not preferred way.
Example:
The following code snippets are examples of this syntax:
double[] myList;
// preferred way.
or
double myList[];
//
works but not preferred way.
Creating Arrays:
You can create an array by using the new operator with the following syntax:
arrayRefVar = new dataType[arraySize];
The above statement does two things:


It creates an array using new dataType[arraySize];
It assigns the reference of the newly created array to the variable arrayRefVar.
Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:
42
Prince Pinto
13302A0033
dataType[] arrayRefVar = new dataType[arraySize];
Alternatively you can create arrays as follows:
dataType[] arrayRefVar = {value0, value1, ..., valuek};
ollowing statement declares an array variable, myList, creates an array of 10 elements of
double type and assigns its reference to myList:
double[] myList = new double[10];
Following picture represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Program:
package sorting;
import java.util.*;
import java.util.Arrays;
class ascdesc
{
Scanner scan;
int[] num;
int n;
void getVal() {
scan = new Scanner(System.in);
System.out.println("Sort an Array");
System.out.println ("\nEnter 'n' value :");
43
Prince Pinto
13302A0033
n = Integer.parseInt(scan.nextLine());
System.out.println("Enter the numbers :");
num = new int[n];
for(int i=0; i<n; i++) {
num[i] = Integer.parseInt(scan.nextLine());
}
}
void sort() {
System.out.println("\nBefore Sorting");
for(int i=0; i<n; i++) {
System.out.print(" " + num[i]);
}
Arrays.sort(num);
System.out.println("\n\nAfter Sorting");
System.out.println("\nAscending Order");
for(int i=0; i<n; i++) {
System.out.print(" " + num[i]);
}
System.out.println("\nDescending Order");
for(int i=n-1; i>=0; i--) {
System.out.print(" " + num[i]);
}
}
}
public class Sorting {
public static void main(String[] args) {
ascdesc a=new ascdesc();
a.getVal();
a.sort();
}
}
44
Prince Pinto
13302A0033
Output:
45
Prince Pinto
13302A0033
Practical No-05
Aim: b) Design a class for implementing the operations of stack
Stack:
A stack is a list in which all insertions and deletions are made at one end, called the top.
It is a collection of contiguous cells, stacked on top of each other. The last element to be
inserted into the stack will be the first to be removed. Thus stacks are sometimes referred to
as Last In First Out (LIFO) lists.
The operations that can be performed on a stack are push, pop and top. Push is to insert
an element at the top of the stack. Pop is deleting an element that is at the top most position in
the stack. Top simple examines and returns the top most value in the stack without deleting it.
Push on an already filled stack and pop on an empty stack results in serious errors. Before
any insertion, the value of the variable top is initialized to -1.
46
Prince Pinto
13302A0033
Algorithm:
1. Declare an array ahead of time called Array.
2. Declare a structure called Stack that contains the TopOfStack and the Capacity fields.
3. The variable called TopOfStack for the stack is initialized to -1.
4. To push an element into the stack, increment TopOfStack and then set
Array[TopOfStack]=X.
5. To pop an element from the array, set the return value to Array[TopOfStack] and then
decrement TopOfStack
program:
package stack12;
import java.util.Scanner;
import java.util.Stack;
public class Stack12 {
Scanner scan;
Stack<String> stack;
int n;
void push() {
scan = new Scanner(System.in);
47
Prince Pinto
13302A0033
stack = new Stack<String>();
System.out.println("Stack Push, Pop & Peek");
System.out.println("\nEnter 'n' value :");
n = scan.nextInt();
System.out.println("Enter the data - PUSH");
for(int i=0; i<n; i++) {
stack.push(scan.next());
}
}
void peek() {
System.out.println("\nTop Value of the Stack - PEEK");
if(stack.isEmpty())
System.out.println("The Stack is Empty..");
else
System.out.println(stack.peek());
}
void pop() {
System.out.println("\nThe Stack - POP");
while(!stack.empty()) {
System.out.println(stack.pop());
}
peek();
}
}
class Mainclass{
public static void main(String[] args) {
// TODO code application logic here
Stack12 obj = new Stack12();
obj.push();
obj.peek();
obj.pop();
48
Prince Pinto
13302A0033
}
}
Output:
49
Prince Pinto
13302A0033
Practical No-06
Aim: a) Design a class for implementing the operations of queue
(insert,delete,display,exit).
Queue:
A Queue is an ordered collection of items from which items may be deleted at one end
(called the front of the queue) and into which items may be inserted at the other end (the rear
of the queue). Queues remember things in first-in-first-out (FIFO) order. The basic
operations in a queue are: Enqueue - Adds an item to the end of queue. Dequeue - Removes
an item from the front
Array implementation of Queue ADT:
A queue is implemented using a one dimensional array. FRONT is an integer value,
which contains the array index of the front element of the array. REAR is an integer value,
which contains the array index of the rear element of the array. When an element is deleted
from the queue, the value of HEAD is increased by one. i.e. HEAD = HEAD + 1 When an
element is inserted into the queue, the value of TAIL is increased by one. i.e. TAIL = TAIL +
1
Linked List Implementation of a Queue:
We go for a linked list implementation of a queue rather than an array implementation
because of the run time memory allocation feature of linked lists. In this implementation we
make a head pointer and make it point to the first created node in the stack. Whenever an
50
Prince Pinto
13302A0033
element is enqueued into the queue, a new node is created at the end of the linked list and the
element is kept in that node. Whenever a dequeue operation is performed on the queue, the
head pointer is made to point to the node, next to the one that it is currently pointing to.
Algorithm:
INSERTING A VALUE
1.
2.
3.
4.
5.
6.
7.
8.
1.If (REAR == N) Then
[Check for overflow]
Print: Overflow
Else
If (FRONT and REAR == 0) Then
[Check if QUEUE is empty]
(a) Set FRONT = 1
(b) Set REAR = 1
Else
Set REAR = REAR + 1
[Increment REAR by 1]
[End of Step 4 If]
QUEUE[REAR] = ITEM
Print: ITEM inserted [End of Step 1 If]
Exit
9.
DELETING A VALUE
1. If (FRONT == 0)
Then [Check for underflow]
2. Print: Underflow
3. Else
4. ITEM = QUEUE[FRONT]
5. If (FRONT == REAR) Then
[Check if only one element is left]
(a) Set FRONT = 0
(b) Set REAR = 0
6. Else
7. Set FRONT = FRONT + 1
[Increment FRONT by 1]
[End of Step 5 If]
8. Print: ITEM deleted [End of Step 1 If]
9. Exit
51
Prince Pinto
13302A0033
Program:
package queue;
import java.io.*;
public class Queue {
public static void main(String args[])throws IOException {
BufferedReader br=new BufferedReader(
new InputStreamReader(System.in));
int ar[]=new int[5];
int rear,front,ch;
rear=front=-1;
do
{
System.out.println("1.Insert element");
System.out.println("2.Delete element");
System.out.println("3.Display element");
System.out.println("4.Exit");
System.out.print("Enter your choice :-");
ch=Integer.parseInt(br.readLine());
switch(ch)
{
case 1:
if((rear+1)>4)
System.out.println("Queue overflow...");
else
{
System.out.print("Enter element :-");
ar[++rear]=Integer.parseInt(br.readLine());
}
if(front == -1)
front=0;
break;
case 2:
if(front == -1)
System.out.println("Queue underflow....");
else
System.out.println("Poped element :-"+ar[front++]);
if(front>rear)
front=rear=-1;
break;
case 3:
if(front == -1)
System.out.println("Queue underflow....");
else
{
for(int i=front;i<=rear;i++)
{
System.out.print(ar[i]+"\t");
}
System.out.println();
52
Prince Pinto
13302A0033
}
break;
case 4:
System.out.println("Program end....");
break;
default:
System.out.println("Invalid choice enter....");
}
}while(ch != 4);
}
}
Output:
53
Prince Pinto
13302A0033
Practical-06
Aim: b) Design a class for implementing the operations of circular queue
INSERT INTO CIRCULAR QUEUE :
1. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then
2. Print: Overflow
3. Else
4. If (REAR == 0) Then
[Check if QUEUE is empty]
(a) Set FRONT = 1 (b) Set REAR = 1
5. Else If (REAR == N) Then
[If REAR reaches end if QUEUE]
6. Set REAR = 1
7. Else
8. Set REAR = REAR + 1
[Increment REAR by 1]
[End of Step 4 If]
9. Set QUEUE[REAR] = ITEM
10. Print: ITEM inserted [End of Step 1 If]
11. Exit
DELETE FROM CIRCULAR QUEUE:
1. If (FRONT == 0) Then
[Check for Underflow]
2. Print: Underflow
3. Else
4. ITEM = QUEUE[FRONT]
5. If (FRONT == REAR) Then
[If only element is left]
(a) Set FRONT = 0 (b) Set REAR = 0
6. Else If (FRONT == N) Then
[If FRONT reaches end if QUEUE]
7. Set FRONT = 1
8. Else
9. Set FRONT = FRONT + 1
[Increment FRONT by 1]
[End of Step 5 If]
10. Print: ITEM deleted [End of Step 1 If]
11. Exit
Program:
package cirqueue;
import java.io.*;
import java.lang.*;
class clrqueue
{
DataInputStream get=new DataInputStream(System.in);
int a[];
int i,front=0,rear=0,n,item,count=0;
void getdata()
{
try
54
Prince Pinto
13302A0033
{
System.out.println("Enter the limit");
n=Integer.parseInt(get.readLine());
a=new int[n];
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void enqueue()
{
try
{
if(count<n)
{
System.out.println("Enter the element to be added:");
item=Integer.parseInt(get.readLine());
a[rear]=item;
rear++;
count++;
}
else
System.out.println("QUEUE IS FULL");
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
void dequeue()
{
if(count!=0)
{
System.out.println("The item deleted is:"+a[front]);
front++;
count--;
}
else
System.out.println("QUEUE IS EMPTY");
if(rear==n)
rear=0;
}
void display()
{
int m=0;
if(count==0)
55
Prince Pinto
13302A0033
System.out.println("QUEUE IS EMPTY");
else
{
for(i=front;m<count;i++,m++)
System.out.println(" "+a[i%n]);
}
}
}
public class Cirqueue {
public static void main(String[] args) {
DataInputStream get=new DataInputStream(System.in);
int ch;
clrqueue obj=new clrqueue();
obj.getdata();
try
{
do
{
System.out.println(" 1.Enqueue 2.Dequeue 3.Display 4.Exit");
System.out.println("Enter the choice");
ch=Integer.parseInt(get.readLine());
switch (ch)
{
case 1:
obj.enqueue();
break;
case 2:
obj.dequeue();
break;
case 3:
obj.display();
break;
}
}
while(ch!=4);
}
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
}
56
Prince Pinto
13302A0033
OUTPUT:
57
Prince Pinto
13302A0033
PRACTICAL NO-07
Aim:-a) Design a class in Java for Bubble Sorting in Ascending and Descending
Bubble Sort:
• Idea:
– Repeatedly pass through the array
– Swaps adjacent elements that are out of order
• Easier to implement, but slower than Insertion sort
58
Prince Pinto
13302A0033
Bubble Sort Algorithm:
for i  1 to length[A]
do for j  length[A] downto i + 1
do if A[j] < A[j -1]
then exchange A[j]  A[j-1]
Program:
1. Ascending:
import java.io.*;
public class BubbleSort {
public static void main(String args[])
{
//Numbers which need to be sorted
int numbers[] = {23,5,23,1,7,12,3,34,0};
//Displaying the numbers before sorting
System.out.print("Before sorting, numbers are ");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
System.out.println();
//Sorting in ascending order using bubble sort
bubbleSortInAscendingOrder(numbers);
59
Prince Pinto
13302A0033
//Displaying the numbers after sorting
System.out.print("After sorting, numbers are ");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
}
//This method sorts the input array in asecnding order
public static void bubbleSortInAscendingOrder( int numbers[])
{
int temp;
for(int i = 0; i < numbers.length; i++)
{
for(int j = 1; j < (numbers.length -i); j++)
{
//if numbers[j-1] > numbers[j], swap the
elements
if(numbers[j-1] > numbers[j])
{
temp = numbers[j-1];
numbers[j-1]=numbers[j];
numbers[j]=temp;
}
}
}
}
}
60
Prince Pinto
13302A0033
2. Descending
import java.io.*;
public class BubbleSort {
public static void main(String a[])
{
//Numbers which need to be sorted
int numbers[] = {23,5,23,1,7,12,3,34,0};
//Displaying the numbers before sorting
System.out.print("Before sorting, numbers are ");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
System.out.println();
//Sorting in descending order using bubble sort
bubbleSortInDescendingOrder(numbers);
//Displaying the numbers after sorting
System.out.print("After sorting, numbers are in
descending order ");
for(int i = 0; i < numbers.length; i++)
{
System.out.print(numbers[i]+" ");
}
}
//This method sorts the input array in desecnding order
public static void bubbleSortInDescendingOrder(int
numbers[])
{
int temp;
61
Prince Pinto
13302A0033
for(int i = 0; i < numbers.length; i++)
{
for(int j = 1; j < (numbers.length-i); j++)
{
//if numbers[j-1] < numbers[j], swap the
elements
if(numbers[j-1] < numbers[j])
{
temp = numbers[j-1];
numbers[j-1]=numbers[j];
numbers[j]=temp;
}
}
}
}
}
62
Prince Pinto
13302A0033
PRACTICAL NO-07
Aim:-b) Design a class in java for implementing Insertion Sort
Insertion Sort:
• Idea: like sorting a hand of playing cards
– Start with an empty left hand and the cards facing down on the
table.
– Remove one card at a time from the table, and insert it into the
correct position in the left hand
• compare it with each of the cards already in the hand, from
right to left
– The cards held in the left hand are sorted
• these cards were originally the top cards of the pile on the
table
63
Prince Pinto
13302A0033
Algorithm:
INSERTION-SORT(A)
for j ← 2 to n
do key ← A[ j ]
Insert A[ j ] into the sorted sequence A[1 . . j -1]
i←j-1
while i > 0 and A[i] > key
do A[i + 1] ← A[i]
i←i–1
A[i + 1] ← key
• Insertion sort – sorts the elements in place
64
Prince Pinto
13302A0033
Program:
import java.util.*;
public class insertionsort {
public static void main(String[] args) {
int A[] = new int[10];
populateArray(A);
System.out.println("Before Insertion Sorting: ");
printArray(A);
// sort the array
insertionSort(A);
System.out.println("\nAfter Insertion Sorting: ");
printArray(A);
}
private static void insertionSort(int[] arr) {
for (int i = 1; i < arr.length; i++) {
int valueToSort = arr[i];
int j = i;
while (j > 0 && arr[j - 1] > valueToSort) {
65
Prince Pinto
13302A0033
arr[j] = arr[j - 1];
j--;
}
arr[j] = valueToSort;
}
}
public static void printArray(int[] B) {
System.out.println(Arrays.toString(B));
}public static void populateArray(int[] B) {
for (int i = 0; i < B.length; i++) {
B[i] = (int) (Math.random() * 100);
}
}
}
66
Prince Pinto
13302A0033
PRACTICAL NO-08
Aim:-a) Design a class in java for implementing Selection Sort
Selection Sort:
• Idea:
– Find the smallest element in the array
– Exchange it with the element in the first position
– Find the second smallest element and exchange it with the
element in the second position
– Continue until the array is sorted
• Disadvantage:
– Running time depends only slightly on the amount of order in the
file
Algorithm:
SELECTION-SORT(A)
n ← length[A]
for j ← 1 to n - 1
do smallest ← j
for i ← j + 1 to n
67
Prince Pinto
13302A0033
do if A[i] < A[smallest]
then smallest ← i
exchange A[j] ↔ A[smallest]
Program:
public class SelectionSort {
public static void main(String args[])
{
int x[]={2,4,6,3,8};
System.out.print("Before selection sort ");
for(int i = 0; i < x.length; i++)
{
System.out.print(x[i]+" ");
}
System.out.println();
for (int i=0; i<x.length-1; i++)
{
for (int j=i+1; j<x.length; j++)
{
if (x[i] > x[j])
68
Prince Pinto
13302A0033
{
int temp = x[i];
x[i] = x[j];
x[j] = temp;
}
}
}
System.out.print("Sorted Array after selection sort:");
for(int i=0;i<x.length;i++)
System.out.print(" " +x[i]);
}
}
69
Prince Pinto
13302A0033
PRACTICAL NO-08
Aim:-b) Design a class in Java for implementing Sequential search algorithm,
Binary search algorithm
1. Sequential or Linear Search:
Sequential search, also known as linear search, is the simplest of all searching
algorithms. It is a brute-force approach to locating a given element in a list. It
finds the element by starting at the first element of the list and examining each
subsequent element until the matching element is found or the list exhausts.
Sequential search is proved very useful in the context when you need to search
an element in a list quite frequently, and the list may or may not be ordered. In
that situation sequential search gets the job done in a brute-force manner.
Pros and Cons of Sequential or Linear Search
For small lists of unordered elements, sequential search is easy to implement
and reasonably efficient. The worst case is when we search for an item not in
the list, since we must inspect every element in the list. If the list is large enough
and does record frequent additions and deletions then it is better not to apply
sequential search on the list. Rather, sort the list once and use binary search.
We are discussing binary search in next section.
Program:
import java.util.Scanner;
class SequentialSearch
{
public static void main(String args[])
{
int c, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
70
Prince Pinto
13302A0033
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
for (c = 0; c < n; c++)
{
if (array[c] == search) /* Searching element is present */
{
System.out.println(search + " is present at location " + (c + 1) + ".");
break;
}
}
if (c == n) /* Searching element is absent */
System.out.println(search + " is not present in array.");
}
}
71
Prince Pinto
13302A0033
2. Binary Search:
Binary search delivers better performance than sequential search by sorting the
elements of the list ahead of searching.Binary search looks at the middle
element of the list and see if the element sought-foris found. If not, than it
compares the sought-for element with the middle element of the list and check
whether the middle element is larger than the element we are trying to find. If
so, we keep looking in the first half of the list; otherwise, we look in the second
half. It cuts the number of elements to be compared by half. We keep going in
the same way until the item is found or it is determined that the soughtfor element is not present in the list.
Pros and Cons of Binary Search
Binary search adds a small amount of complexity for large performance gains.
The complexity can increase when the collection is not stored in a simple inmemory data structure, such as an array. There must be a way to access
element A[i] for 0 <= i < n in the collection based upon the natural order of the
elements in the collection, as represented by the Comparable interface. A large
collection might need to be kept in secondary storage, such as a file on a disk. In
such a case, the ith element is accessed by its offset location within the file. Using
secondary storage, the time required to search for an element is dominated by
the costs to accessing the storage; other solutions related to binary search may
be appropriate.
Program:
import java.util.Scanner;
class BinarySearch
{
public static void main(String args[])
{
int c, first, last, middle, n, search, array[];
Scanner in = new Scanner(System.in);
System.out.println("Enter number of elements");
72
Prince Pinto
13302A0033
n = in.nextInt();
array = new int[n];
System.out.println("Enter " + n + " integers");
for (c = 0; c < n; c++)
array[c] = in.nextInt();
System.out.println("Enter value to find");
search = in.nextInt();
first = 0;
last = n - 1;
middle = (first + last)/2;
while( first <= last )
{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
73
Prince Pinto
13302A0033
last = middle - 1;
middle = (first + last)/2;
}
if ( first > last )
System.out.println(search + " is not present in the list.\n");
}
}
74
Prince Pinto
13302A0033
PRACTICAL NO-08
1. Aim:-c) Design a java class to copy the content from one file to another
file.
Program:
import java.io.*;
public class copyfile {
public static void main(String[] args)
throws Exception {
BufferedWriter out1 = new BufferedWriter
(new FileWriter("sourcefile"));
out1.write("we have copied the strings content from sourcefile to the
destinationfile\n");
out1.close();
InputStream in = new FileInputStream
(new File("sourcefile"));
OutputStream out = new FileOutputStream
(new File("destinationfile"));
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
BufferedReader in1 = new BufferedReader
(new FileReader("destinationfile"));
75
Prince Pinto
13302A0033
String str;
while ((str = in1.readLine()) != null) {
System.out.println(str);
}
in.close();
}}
Output:
76
Prince Pinto
13302A0033
2. Aim:-c) Design a java class to read the content from a file.
Program:
import java.io.FileReader;
import java.io.IOException;
public class read1{
public static void main(String[] args) {
try {
FileReader reader = new FileReader("MyFile.txt");
int character;
while ((character = reader.read()) != -1) {
System.out.print((char) character);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output:
77
Prince Pinto
13302A0033
3. Aim:-c) Design a java class to write the content from a file.
Program:
import java.io.FileWriter;
import java.io.IOException;
public class write {
public static void main(String[] args) {
try {
78
Prince Pinto
13302A0033
FileWriter writer = new FileWriter("MyFile1.txt", true);
writer.write("Hello World");
writer.write("\r\n"); // write new line
writer.write("Good Bye!");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}}}
Output:
79
Prince Pinto
13302A0033
80