object oriented programming language - …cse.gecgudlavalleru.ac.in/pdf/manuals/oops.pdf · object...
TRANSCRIPT
Object Oriented Programming Language
II B.Tech Object Oriented Programming Language
P a g e | 2 Department of Computer Science & Engineering GEC
List of Experiments
ADD ON PROGRAMS
S.NO TITLE PAGE.NO
1 a)Add On Programs b)Open Programs c)Designing Programs
4
2 System Requirement
5
3 Lab Objectives 6
4 To Write a java program for generating printing Fibonacci sequence
7
5 To Write a java program to demonstrate wrapper class 8
6 To Write a java program for multiplication of three numbers using single inheritance
9
7 To Write a java program implementation of even number 10
8 To Write a java program to sorting the given list using bubble sort
11
9 To Write a java program for addition of two matrices 12
10 To Write a java program for perform all arithmetic operation using run time polymorphism
13
11 To Write a java program to calculate the square and cube of a given number using packages
14
12 To Write a java program to list out the no.of tokens and display all the tokens using string tokenizer
15
13 To Write a java program to display the list of files in a directory 16
14 To Write a java program using different file methods 17-18
15 To Write an applet to display a simple message 19
16 To Write a java program to key events 20
17 To Write a java program to creating a thread 21-23
18 To Write a java program that allows using graphics class
24-25
19 To Write a java program that for addition and subtraction of two numbers using interface
26-27
II B.Tech Object Oriented Programming Language
P a g e | 3 Department of Computer Science & Engineering GEC
OPEN PROGRAMS
DESIGN PROGRAMS
System Requirement
S.NO TITLE PAGE.NO 1 To Write a java program for display multiplication table
using do….while loop
28
2 To Write a java program to import a package for adding two number
29-30
S.NO TITLE PAGE.NO 1 Write a java program for string handling function to
length,uppercase,lowercase and concat 31
2 Write a program for string conversions 32
S.NO
TITLE
PAGE.NO
1 Implement write an java program by using different applets methods (draw Line, draw Arc, fill Arc, draw Oval , fill Oval)
33
2 To write a java program to draw rectangles by using Mouse Events
34,35
II B.Tech Object Oriented Programming Language
P a g e | 4 Department of Computer Science & Engineering GEC
1.Inter based desktop PC with minimum of 166 MHZ or with atleast 64 MB RAM and
100MB free disk space
2.JDK Kit. Recommended
II B.Tech Object Oriented Programming Language
P a g e | 5 Department of Computer Science & Engineering GEC
Lab Objective
1.To make the student learn a object oriented way of solving problems 2.To teach the student to write programs in java to solve the problems
EXPT NO.1
II B.Tech Object Oriented Programming Language
P a g e | 6 Department of Computer Science & Engineering GEC
Fibonacci series
Procedure:The Fibonacci numbers are the integer sequence 0, 1, 1, 2, 3, 5, 8, 13, 21, ..., in which each item
is formed by adding the previous two. The sequence can be defined recursively by
Fibonacci number programs that implement this definition directly are often used as introductory
examples of
recursion. However, many other algorithms for calculating (or making use of) Fibonacci numbers also
exist.
Algorithm Step1:Start
Step2:creating a class Fibonocci
Step3:define main method
Step4:declare variables t1,t2,t3,n,i.
Initialize t1 with 0 and t2 with 1
Step5:read variable n
Step6:print t1 and t2 values
Step7: t3=t1+t2
t1=t2
t2=t3
Step8: print t3
Step9:start at i=2 repeat step 5,6,7 and 8 till I is less than n value
Step10: stop
Output:
enter value for Fibonacci
8
Series is
0
1
1
2
3
5
8
13
EXPT NO.2
II B.Tech Object Oriented Programming Language
P a g e | 7 Department of Computer Science & Engineering GEC
wrapper class
Procedure: Wrapper classes are used to represent primitive values when an Object is required. The
wrapper classes are used extensively with Collection classes in the java.util package and with the
classes in the java.lang.reflect reflection package.
The primitive wrapper classes and their corresponding primitive types are:
Primitive type Wrapper class Constructor Arguments
byte Byte byte or String
short Short short or String
int Integer int or String
long Long long or String
float Float float, double or String
double Double double or String
char Character Char
boolean Boolean boolean or String
The Byte, Short, Integer, Long, Float, and Double wrapper classes are all subclasses of the Number class.
Algorithm
Step1: start
Step2:creating a class Wrapper
Step3:define main method
step4: take integer reference variable i
and integer variable j
Step5: define I as Integer class object with 100
Step6: define j with integer value of object i
Step7:print value of j
Step8:stop
Output:
100 100
EXPT NO.3
II B.Tech Object Oriented Programming Language
P a g e | 8 Department of Computer Science & Engineering GEC
multiplication of three numbers using single inheritance
Procedure: One way of resolving these problems has been to enforce single inheritance where a class can
only derive from one base class. Typically these languages allow classes to implement multiple protocols,
called interfaces in Java. These protocols define methods but do not provide concrete implementations. This
strategy has been used by ActionScript, C#, D, Java, Nemerle, Object Pascal (Delphi), Objective-C, Ruby
and Smalltalk. All but Smalltalk allow classes to implement multiple protocols
Algorithm
Step1: start
Step2: define a class Mul
Step3: declare integer variable a, b and d
Step4: define method get which takes 2 integers as arguments
For defining variables a and b
Step5: define another class b and extend mul class
Step6: declare a variable c
Step7: define method get1 which takes 3 arguments to initialize variables a,b,c
Step8: define method display to calculate multiplication of variables a,b,c which is stored in d
Step9:printing d value
Step10:define a class Data
Step11:define main method
Define object for class b and call method get1 with 3 parameters
Step12: now call method display to print multiplied value
Step13:stop
Output:
D=48
EXPT:4
II B.Tech Object Oriented Programming Language
P a g e | 9 Department of Computer Science & Engineering GEC
Even numbers
Procedure: Here you will learn to write a program for listing out all the even numbers between two
numbers. For this first create a class named AllEvenNum under the java.io package. Now use the try/catch
exception to avoid any kind of input error. After this create a buffer class in which all the input data are
stored and modified. Then give message as to "Enter number" in the System method
Algorithm
Step1: start
Step2: define class Even
Step3:define main method
Step4: declare and read value of n
Step5:start i=2 until i<n and check if(n%2==0)
Step6: Then print as even
Step7: print I value
Step8:repeat step 4,5 and 6 till I is less than n value
Step9: stop
Output:
Enter n value 10
Even numbers are
2 4 6 8
EXPT:5
II B.Tech Object Oriented Programming Language
P a g e | 10 Department of Computer Science & Engineering GEC
Sorting numbers using bubble sort Procedure:Bubble sort, sometimes incorrectly referred to as sinking sort, is a simple sorting algorithm that
works by repeatedly stepping through the list to be sorted, comparing each pair of adjacent items and
swapping them if they are in the wrong order
Algorithm
Step1: start
Step2:define main method
Step3: read an array of n integers and n,i,j,temp
Step4: start i at 0 and j at j+1 repeat steps 4,5 and 6 till a[i] greater than a[j]
Step5: temp=a[i]
a[i]=a[j]
a[j]=temp
Step6: print sorted array elements a[i]
Step7:stop
Output: Enter array size
8
Enter values for sorting
0 7 5 1 4 9 2 8
Sorting order is
0 1 2 4 5 7 8 9
II B.Tech Object Oriented Programming Language
P a g e | 11 Department of Computer Science & Engineering GEC
EXPT:6
Matrix addition using arrays
Procedure:The sum of two matrix. To make this program, we need to declare two dimensional array of type
integer. Firstly it calculates the length of the both the arrays. Now we need to make a matrix out of it. To
make the matrix we will use the for loop. By making use of the for loop the rows and column will get divide.
This process will be performed again for creating the second matrix.
After getting both the matrix with us, we need to sum both the matrix. The both matrix will be added by
using the for loop with array[i][j]+array1[i][j]. The output will be displayed by using the println() method
Algorithm
Step 1:start
Step2:define class Add
Step 3: define main method
Step4: declare variables i and j
Step5: define 3 arrays of 3*3 size a[][][],b[][][],c[][][]
Step6: read arrays values of two arrays
Step7: start I at 0 and j at 0 repeat steps 7 till I and j less than 3
Step8: c[i][j]=a[i][j]+b[i][j]
Step9: print array c[][][]
Step10: stop
Output:
Enter values for matrix a
2 6 7
5 8 7
0 2 1
Enter values for matrix b
4 5 8
0 0 3
3 2 1
Addition is:
6 11 15
5 8 12
3 4 2
EXPT:7
II B.Tech Object Oriented Programming Language
P a g e | 12 Department of Computer Science & Engineering GEC
Perform arithmetic operations using run time polymorphism
Procedure:polymorphism means ability to more tan form
Algorithm
Step1: start
Step2: define class Arop
Step3: define method display with 2 integer arguments to calculate addition of given 2
integers and printing the result
Step4:define class Sub which extends Arop class
Step5: define method display with 2 integer arguments to perform subtraction of given 2 parameters and
printing the result
Step6: define class Mul which extends Arop class
Step7: define method display with 2 integer arguments to perform multiplication of given 2 parameters and
printing the result
Step8: define class Div which extends Arop class
Step9: define method display with 2 integer arguments to perform division of given 2 parameters and
printing the result
Step10: define class P1
Step11:define main method
Step12: create 4 object references of Arop class
Step13: call display method of each class using object references
Step14:stop
Output: Add=7
Sub=2
Mul=18
Div=0
II B.Tech Object Oriented Programming Language
P a g e | 13 Department of Computer Science & Engineering GEC
EXPT:8
Square and cube of a given number using packages
Procedure:A package is a collection of classes and interfaces which provides a high level of
access protection and names space management.
Defining & creating package: Step1: Simply include a package command has the first
statement in java source file. Any class you declare within that file will belong to the
specified package.
Algorithm
Step1:start
Step2: define a package ram
Step2: define a class Sai
Step3: define a method square with one integer argument
To print square of a number
Step4: define a method cube with one integer argument
To print cube of a number
Step5: import package ram.sai and create a class Abc
Step6:define main method
Step7: create an object(n) reference of class Sai
Step8: call methods square and cube with object(n)
Step9: stop
Output: Square is 9
Cube is 125
EXPT:9
II B.Tech Object Oriented Programming Language
P a g e | 14 Department of Computer Science & Engineering GEC
To list out the tokens using String tokenizer class
Procedure:The processing of text often consists of parsing a formatted input string. Parsing is the division
of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning.
The StringTokenizer class provides the first step in this parsing process, often called the lexer (lexical
analyzer) or scanner. StringTokenizer implements the Enumeration interface. Therefore, given an input
string, you can enumerate the individual tokens contained in it using StringTokenizer
Algorithm
Step1:Start
Step2: define a class String4
Step3:define main method
Step4: define an object reference t for a String Tokenizer class with a string as aguement
Step5: print number of tokens using CountTokens() method
Step6: print each token using hasMoreTokens() and nextToken() methods
Step7: stop
Output: Tokens=2
Hai
Naren
EXPT:10
Display the list of files in a directory
II B.Tech Object Oriented Programming Language
P a g e | 15 Department of Computer Science & Engineering GEC
Procedure:In this section, you will study how to retrieve all the files and folders from the specified
directory. In the given example, we are providing the directory 'C:\\" to the constructor of class File.
file.listFiles()- This method returns an array of files and folders present in the specified directory with
their pathname.
file.length()- This method returns the length of the provided directory.
files[fileInList]. toString- This will display all the files of directory on the
Algorithm
Step1: start
Step2:import io package
Java.io.*;
Step3: define class Page
Step4:define main method
Step5: create object reference of class File having path of file
Step6: declare a string variable initialized with null
Step7: using methods is Directory() and list methods
Step8:using for loop list out the files in each directory
Step9: print each file name s[i]
Step10: stop
Output: Addmat.java
Alltags.html
Attr.html
Bl.html
II B.Tech Object Oriented Programming Language
P a g e | 16 Department of Computer Science & Engineering GEC
EXPT:11
File handling methods Procedure:using file handling we can perform operations on files
File handling methods are:
f.canRead()
f.canWrite()
f.exists()
f.getName()
f.getParent()
f.getPath()
f.isdirectory()
f.isFile()
f.length()
f.lastModified()
f.isHidden()
f.AbsolutePath()
Algorithm
Step1: Start
Step2:import the io package
java.io.*;
Step3:Create a class pg2
Step4:define main method
Step5:Create an object(f) for class file having path file
Step6:Print the file handling methods and call with an object(f)
f.canRead()
f.canWrite()
f.exists()
f.getName()
f.getParent()
f.getPath()
f.isdirectory()
f.isFile()
f.length()
f.lastModified()
f.isHidden()
f.AbsolutePath()
Step6: Stop.
II B.Tech Object Oriented Programming Language
P a g e | 17 Department of Computer Science & Engineering GEC
Output:
true
True
True
Chandu
D:/
True
False
0
1328840560015
II B.Tech Object Oriented Programming Language
P a g e | 18 Department of Computer Science & Engineering GEC
EXPT:12
Display a simple message using applet
Procedure: What is Applet
This section introduces you with the applet and describes the advantages and disadvantages of applet.
Applet versus Application
This section defines the various differences between the Applets and the Applications.
Understanding Applet Life Cycle In this section you will learn about the lifecycle of an applet. You will learn about the different methods of
an applet
Algorithm
Step1: Start
Step2:import the packages
Java.applet.*;
Java.awt.*;
Step3: Create a class App and extends with an applet class
Step4:Read a string as null string
Step5:Define init() method.
In this method add an string “Naren” with a null string and stored in msg
Step6:Define start method in this method add an string “reddy” with msg
Step7:Define paint method and create an object(g) for class Graphics
Step8:defining the method in the paint and call with an object
g.setColor(Color.green);
g.draw string(msg,5,10);
Step9:stop
Output:
Applet
narenreddy
II B.Tech Object Oriented Programming Language
P a g e | 19 Department of Computer Science & Engineering GEC
EXPT:13
Key Events
Procedure:This is the method of the KeyEvent class which determines the character that has been entered
by you. This method returns the character associated the KeyEvent
Algorithm
Step1:start
Step2:import the packages
Java.awt.*;
Java.awt.event;
Step3:m class (k)extends with applet and implement with key listeren interface
Step4:Declare astring msg with null start
Step5:Declare x=10,y=10
Step6:define init method,in that we can add key listener inter face public void int()
Step7:define a method key pres send key pres send ( key pres even r )
In that we define a method show start(“welcome”);
Step8:define a method key released key released (key Even r)
In that we define a method show tat (“key even”)
Step9:difine a method keytyped (key even r)
In that define a method showstart(“hai”)and define
Step10:define paint method and ccrete an object(g) for class Graphics in that define a method with
parameter and call with an object
g.draw string(msg x,y)
output:
EXPT:14
Applet
Abcde Welcome Hi Applet started
II B.Tech Object Oriented Programming Language
P a g e | 20 Department of Computer Science & Engineering GEC
A).Extending a thread
Procedure:In Java, an object of the Thread class can represent a thread. Thread can be implemented through
any one of two ways:
Extending the java.lang.Thread Class
Implementing the java.lang.Runnable Interface
II B.Tech Object Oriented Programming Language
P a g e | 21 Department of Computer Science & Engineering GEC
Algorithm Step1:start
Step2:create a class A and extends with thread class
Step3:definininy run method
Step4:read i=1 and contine till i<5
Step5:print(i)
Step6:create a.class b and entends&with thread class
Step7:defining run method
Step8:read j=l and continue till j<5
Step9:print(j)
Step10:crete a class T
Step11:define main method
Step12:crete an object(a)for class A
Step13:creat an object(b) for class B
Step14:call start method with an object(a)and object(b)
Step15:stop.
Output:
Thread A:i1
Thread A:i2
Thread A:i3
Thread A:i4
Thread B:j1
Thread B:j2
Thread B:j3
Thread B:j4
EXPT:14
II B.Tech Object Oriented Programming Language
P a g e | 22 Department of Computer Science & Engineering GEC
B).Implementing a thread
Algorithm Step1:start
Step2:import the languge packge
java.lang.*;
Step3:create as class b1 and implement with runnable interface
Step4:creat a run method
Step5:Read i=0 and contine till i<5
Step6:print(i)
Step7:create a class runnabletest
Step8:define main method
Step9:create an object(ob) for class b1
Step10:create an object(t) for class thread
Step11:call the start method with an object(e)
Step12:stop
Output:
Thread A:i1
Thread A:i2
Thread A:i3
Thread A:i4
Thread A:i5
EXPT:15
II B.Tech Object Oriented Programming Language
P a g e | 23 Department of Computer Science & Engineering GEC
Drawing a human face by using different Applet methods Procedure: drawLine():used to draw the line
g.drawLine(start x,start y,end x,end y)
drawOval():used to draw the Oval
g.drawOval(start x,start y,end x,end y)
fillOvalOval():used to fill the Oval by using some colour
g.fillOval(start x,start y,end x,end y)
drawArc():used to draw the Arc
g.drawArc (start x,start y,end x,end y)
drawRect():used to draw the rectangle
g.drawRect(int top,int bottom,int right,int left)
fillRect():used to fill the rectangle by using some colour
g.fillRect(int top,int bottom,int right,int left)
RoundRect():used to draw the Rounded rectangle
g.RoundRect(int top,int bottom,int right,int left)
Algorithm Step1:start
Step2:import the packages
Java.awt.*;
Java.applet.*;
Step3:create a class human and extende with an applet
Step4L:define paint method and create an object(g)for class graphics
Step5:call the methods with an object(g)
g.drawOval(40,40,120,150)
g.filloval(25,92,15,30)
g.drawArc(60,125,80,40,180,180)
g.fillArc(60,125,80,40,180,180)
g.drawline(25,92,15,30)
g.drawRect(30,30,30,30)
g.fillRect(30,30,30,30)
g.drawRoundRect(80,80,40,40,50,50)
g.fillRoundRect(80,80,40,40,50,50)
output:
II B.Tech Object Oriented Programming Language
P a g e | 24 Department of Computer Science & Engineering GEC
Apple view:……
Applet
II B.Tech Object Oriented Programming Language
P a g e | 25 Department of Computer Science & Engineering GEC
EXPT:16
Addition and subtraction of two numbers using interface Procedure:An interface in the Java programming language is an abstract type that is used to
specify an interface (in the generic sense of the term) that classes must implement. Interfaces
are declared using the interface keyword, and may only contain method signature and
constant declarations (variable declarations that are declared to be both static and final).
An interface may never contain method definitions
Syntax:access specifier interface interfacename
{
Type1 variable name=”value”
.
. Typen variable name=”value”
Retyrn _type method name1(parameter list)
.
.
Retyrn _type method namen(parameter list)
Algorithm
II B.Tech Object Oriented Programming Language
P a g e | 26 Department of Computer Science & Engineering GEC
Step1:start
Step2:create an interface using interface keyword
Step3:Read a=11 and b=10
Step4:define two methods add and sub with two parameters x and y
Step5:define add method with two parameters k and l
Step6:print (k+l)
Step7: define sub method with two parameters k and l
Step8:print (k-l)
Step9:define main method
Step10:create an object(b) for class It2
Step11:call the add method with an object(b)
Step12:print (b.a+b.b)
Step13:call the sub method with an object(b)
Step14:print (b.a-b.b)
Step15:stop
Output: Addition of k,l=30 Addition of a,b=21 Subtraction of k,l=10 Subtraction of a,b=1
DESIGN PROGRAM
II B.Tech Object Oriented Programming Language
P a g e | 27 Department of Computer Science & Engineering GEC
EXPT:1
Applets methods
Procedure:When an applet begins, the following methods are called:
init()
start()
paint()
When an applet is terminated, the following sequence of method calls take place:
stop()
destroy()
1) init( ): The init( ) method is the first method to be called. This is where you should initialize
variables...
2) start( ): The start( ) method is called after init( ). It is also called to restart an applet after it has
been stopped. Whereas init( ) is called once—the first time an applet is loaded—start( ) is called
each time an applet„s HTML document is displayed onscreen..
3) paint( ): The paint( ) method is called each time your applet„s output must be redrawn.. The paint( )
method has one parameter of type Graphics..
4) stop( ): The stop( ) method is called when a web browser leaves the HTML document containing the
applet.
5) destroy( ): The destroy( ) method is called when the environment determines that your applet needs
to be removed completely from memory. At this point, you should free up any resources the applet
may be using. The stop( ) method is always called before destroy( ).
OUTPUT
Applet viewer…
Applet
II B.Tech Object Oriented Programming Language
P a g e | 28 Department of Computer Science & Engineering GEC
EXPT:2
The Mouse Listener Interface
Procedure:This interface defines five methods. If the mouse is pressed and released at the same point, mouseClicked( ) is invoked. When the mouse enters a component, the method is called. mouseEntered( ).When it leaves, mouseExited( ) is called the mousePressed( ) mouseReleased( ) methods are invoked when the mouse is pressed and released, respectively. The general forms of these methods are shown here: void mouseClicked(MouseEvent me) void mouseEntered(MouseEvent me) void mouseExited(MouseEvent me) void mousePressed(MouseEvent me) void mouseReleased(MouseEvent me)
The MouseMotionListener Interface
This interface defines two methods. The mouseDragged( ) method is called multipletimes as the mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse
is moved. Their general forms are shown here: void mouseDragged(MouseEvent me) void mouseMoved(MouseEvent me)
The MouseWheelListener Interface
This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is moved. Its general form is shown here: void mouseWheelMoved(MouseWheelEvent mwe)
II B.Tech Object Oriented Programming Language
P a g e | 29 Department of Computer Science & Engineering GEC
Output:
EXPT:1
ADD ON PROGRAM
Applet viewer…
Applet Started
II B.Tech Object Oriented Programming Language
P a g e | 30 Department of Computer Science & Engineering GEC
Multiplication Table Procedure:In mathematics, matrix multiplication is a binary operation that takes a pair of matrices, and produces
another matrix. This term may refer to a number of different ways to multiply matrices, but most commonly refers to
the matrix product.[1][2]
This article will use the following notational conventions. Matrices are represented by capital letters in bold, vectors in
lowercase bold, and entries of vectors and matrices are italic (since they arescalars).
The scalar multiplication of a matrix A and a scalar λ gives another matrix λ A of the same size as A. The entries
of λ A are given by
Do while loop
- If the conditional expression controlling a while loop is initially false,then the body of the loop will
not be executed at all.
- However, sometimes it is desirableto execute the body of a loop at least once, even if the conditional
expression is false to begin with. In other words, there are times when you would like to test the
termination expression at the end of the loop rather than at the beginning.
- Fortunately, Java supplies a loop that does just that: the do-while.
- The do-while loop always executes its body at least once, because its conditional expression is at the
bottom of the loop.
Its general form is
do {
// body of loop
} while (condition);
Output: 5*1=5
5*2=10
5*3=15 5*4=20
5*5=25
5*6=30 5*7=35
5*8=40
5*9=45 5*10=50
II B.Tech Object Oriented Programming Language
P a g e | 31 Department of Computer Science & Engineering GEC
EXPT:2
Package:
Procedure:A package is a collection of classes and interfaces which provides a high level of
access protection and names space management.
1) Defining & creating package:
Step1: Simply include a package command has the first statement in java
source file. Any class you declare within that file will belong to the
specified package.
Syntax: package packagename; E.g.: package mypack;
Step 2: Next define the class that is to be put in the package and declare it as
public.
Step 3: Now store the classname.java file in the directory having name same
as package name.
Step 4: File is to be compiled, which creates .class file in the directory. Java
also supports the package hierarchy, which allows grouping related
classes into a package and then grouping related packages into a larger
package.
Accessing package:
A java system package can be accessed either using a fully qualified class name
or using import statement.
We generally use import statement.
Syntax: import pack1 [.pack2] [.pack3].classname; Or import pack1. [.pack2][.pack3].*;
Output: sum = 6
II B.Tech Object Oriented Programming Language
P a g e | 32 Department of Computer Science & Engineering GEC
EXPT:1
OPEN PROGRAM Procedure:
String conversions:
- When Java converts data into its string representation during concatenation, it does so by calling one of the overloaded versions of the string conversion method valueOf( ) defined by String.
- valueOf( ) is overloaded for all the simple types and for type Object. For the simple types, valueOf( ) returns a string that contains the human-readable equivalent.
- For objects,valueOf( ) calls the toString( ) method on the object. - Here, let's examine the toString( ) method, because it is the means by which you can
determine the string representation for objects of classes that you create. Every class implements toString( ) because it is defined by Object.
- However, the default implementation of toString( ) is seldom sufficient. For most important classes that you create, you will want to override toString( ) and provide your own string representations. Fortunately, this is easy to do. The toString( ) method has this general form:
String toString( )
To implement toString( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class.
- By overriding toString( ) for classes that you create, you allow the resulting strings to
be fully integrated into Java's programming environment
Output: 1111110 176 7e
II B.Tech Object Oriented Programming Language
P a g e | 33 Department of Computer Science & Engineering GEC
EXPT:2
String Handling:
Procedure:A string in C is a sequence of zero or more characters followed by a NULL ( )character:
- It is important to preserve the NULL terminating character as it is how C defines and manages
variable length strings.
- All the C standard library functions require this for successful operation.
- In general, apart from some length-restricted functions ( strncat(), strncmp,() and
strncpy()), unless you create strings by hand you should not encounter any such problems, .
Basic String Handling Functions
All the string handling functions are prototyped in:
#include <string.h>
The common functions are described below:
- char *stpcpy -- Copy one string into another.
- int strcmp - Compare string1 and string2 to determine alphabetic order.
- char *strcpy -- Copy string2 to stringl.
- char *strerror(int errnum) -- Get error message corresponding to specified error
number.
- int strlen -- Determine the length of a string.
- char *strncat -- Append n characters from string2 to stringl.
- int strncmp -- Compare first n characters of two strings.
- char *strncpy -- Copy first n characters of string2 to stringl .
- int strcasecmp-- case insensitive version of strcmp().
- int strncasecmp—compare the upper and lower cases
The strcmp() function lexically compares the two input strings and returns:
II B.Tech Object Oriented Programming Language
P a g e | 34 Department of Computer Science & Engineering GEC
Less than zero -- if string1 is lexically less than string2
Zero -- if string1 and string2 are lexically equal
Greater than zero -- if string1 is lexically greater than string2
The strncat(), strncmp,() and strncpy() copy functions are string restricted version of
their more general counterparts. They perform a similar task but only up to the first n characters.
char *str1 = "HELLO";
char *str2;
int length = 2;
(void) strcpy(str2,str1, length); /* str2 = "HE" */
str2 is NOT NULL TERMINATED!! -- BEWARE
Output:
the length of string 5
The upper case of string SCET
The lower case of string scet
The concat of string SCETscet