Download Prepared by Allaudin “Hemat”

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
1
2


A combination of characters is a string.
String may be declared and created as follows:
◦ String firstName=new String(“Ahmad”);

You can concatenate the Java strings as follows:
◦ String city="Kabul"+"Afghanistan";
◦ String fullName=firstName+lastName;
◦ Where firstName and lastName are the Java strings containing string constants.

We can also create empty strings.
◦ String s=new String();

String Arrays
 We can also create an use string arrays.
String myArray[]=new String[3];
This will create a string array which can hold 3 string constants.
We can also directly initialize the string array as follows:
String myArray[]={"Ahmad","Tahir","Akbar"};
3
Method
Uses
s2=s1.toLowerCase
Converts the string s1 to all lowercase.
s2=s1.toUpperCase
Converts the string s1 to all uppercase.
s2=s1.replace(‘x’,’y’);
Replace all appearnces of x with y.
s2=s1.trim();
Removes white spaces at the beginning ad end of the
string s1.
s1.equals(s2)
Returns true if s1=s2
s1.equalsIgnoreCase(s2)
Returns true if s1=s2, ignoring the case of characters
s1.length()
Gives the length of s1.
s1.CharAt(n)
Gives nth character of s1.
s1.compareTo(s2)
Returns negative if s1<s2, positive if s1>s2 and Zero if
s1=s2
4
Method
Uses
s1.concat(s2)
Concatenates s1 and s2
s1.substring(n)
Gives substring starting from nth
character.
s1.substring (n , m) Gives substring starting from nth
character up to nth
s1.indexOf(‘x’)
Gives the position of first occurrences
of ‘x’ I the string s1
5
public class StrMthd
{
public static void main(String args[])
{
String s1=" Hello Java";
String s2="Heloo";
String s3="Bye Bye ...";
Output
System.out.println(s1);
System.out.println(s1.trim());
System.out.println(s1.substring(3,8));
System.out.println(s2.concat(" world"));
System.out.println(s2.replace('e', 'k'));
System.out.println(s3.toLowerCase());
Hello Java
Hello Java
llo J
Heloo world
Hkloo
bye bye ...
}
}
6
public class StrMthd
{
static String name[]={"Java","C++","C Programming","VB","XML"};
public static void main(String args[])
{
int size=name.length;
String temp=null;
for(int i=0;i<size;i++)
{
for(int j=i+1;j<size;j++)
{
if(name[j].compareTo(name[i])<0)
{
//swap the strings
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for(int i=0;i<size;i++)
{
System.out.println(name[i]);
}
}
}
Output
C Programming
C++
Java
VB
XML
7
Strings only create strings of fixed length but StringBuffer creates
Strings of flexible length and can be modified.
Method
Uses
s1.setChartAt(n,’x’)
Modfifies the nth character to x.
s1.append(x2)
Appends the strings s2 to s1 at the end.
s1.insert(n,s2)
Inserts the string s2 at the position n of the string s1.
s1.setLenth(n)
Sets the length of the string s1 to n.
int lenth()
Returns the current length of the StringBuffer object.
int capacity()
Returns the total allocated capacity
void ensureCapacity()
Ensures that the object has capacity of size chars after
the object has been constructed.
8
public class StrBufferMthd {
public static void main(String args[])
{
StringBuffer str=new StringBuffer("Have Java");
System.out.println("Original string :"+str);
//Obtaining strig lenth
System.out.println("Length of string:"+str.length());
//accessing characters in a string
for(int i=0;i<str.length();i++)
{
int p=i+1;
System.out.println("Character at position:"+p+" is"+str.charAt(i));
Output
Original string :Have Java
Length of string:9
Character at position:1 isH
Character at position:2 isa
Character at position:3 isv
Character at position:4 ise
Character at position:5 is
Character at position:6 isJ
Character at position:7 isa
Character at position:8 isv
Character at position:9 isa
After insertion :Have a cup of Java
Modified String :Have a cup of*Java
Appended string :Have a cup of*Java* Its fantastic.
}
//inserting a string in the middle
String aString=new String(str.toString());
int pos=aString.indexOf("Java");
str.insert(4, " a cup of");
System.out.println("After insertion :"+str);
//modifying characters
str.setCharAt(13, '*');
System.out.println("Modified String :"+str);
//appending a string at the end
str.append("* Its fantastic.");
System.out.println("Appended string :"+str);
}
}
9







A stream ‘is’ a sequence of bytes.
When writing data to a stream, the stream is called an output strea.
When reading data from a stream, it is a buffered stream.
If a stream has a buffer in memory, it is a buffered stream.
Binary streams contain binary data.
Characters streams have character data and are used for storing and
retrieving text.
There are four types of streams:




InputStream
OutputStream
Reader
Writer
10

For better performance, use the buffered I/O classes:





BufferedInputStream
BufferedOutputStream
BufferedReader
BufferedWriter
The package is java.io used for I/O and file handling.
Class
Description
InputStream
The base class for byte stream input operations.
OutputStream
The base class for byte stream output operations.
BufferedInputStream
Buffers input from another stream in memory to make
the read operations more efficient.
11




You can use an InputStream to read binary data.
FileInputStream enables easy reading from a file.
BufferedInputStream provides data buffering that improves performance.
The ObjectInputStream class is used in object serialization:
 FileInputStream
 BufferedInputStream

The InputStream class defines three read method overloads, used to read
from stream:
 public abstract int read(int b)
 public int read(byte[] data)
 public int read(byte[] data, int offset, int length)
12
First overload method reads one byte and returns the byte that was read,
or -1 if it encounters that end of the input source.
 Second overload method read into an array of bytes and returns the actual
number of bytes read, or -1 at the end of the stream. The read method
reads at most b length bytes.
 Third overload reads into an array of bytes. The read method returns the
actual number of bytes read, or -1 at the end of the stream.
Where, b=The array into which the data is read off The offset into b
where the first bytes should be placed . The maximum number of bytes to
read.

13





A stream can be defined as a sequence of data.
A Stream is used to make input and output operation in java.
In general, a stream means continuous flow of data.
Java encapsulates Stream under java.io package. Java defines two types
of streams. They are,
Byte Stream : It provides a convenient means for handling input and
output of byte.

Character Stream : It provides a convenient means for handling input
and output of characters. Character stream uses Unicode.
14

Byte stream is defined by using two abstract class at the top of
hierarchy, they are InputStream and OutputStream.

These two abstract classes have several classes that handle various
devices such as disk files, network connection etc.
15
These classes define several key methods. Two most important are
read() : reads byte of data.
write() : Writes byte of data
16

Character stream is also defined by using two abstract class at the
top of hierarchy, they are Reader and Writer.

These two abstract classes have several classes that handle unicode
character.
17
18

We use the object of BufferedReader class to take inputs from the
keyboard.
19
 read() method is used with BufferedReader object to read characters.
As this function returns integer type value, we need to use
typecasting to convert it into char type.
 int read() throws IOException.
class charInput
{
public static void main( String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
char c = (char)br.read();
//Reading character
System.out.println(c);
}
}
20
 To read string we have to use readLine() function with
BufferedReader class's object.
 String readLine() throws IOException
class inputString
{
public static void main( String args[]) throws IOException
{
String text;
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
text = br.readLine();
//Reading String
System.out.println(text);
}
}
21
class readDataFromFile
{
public static void main( String args[]) throws IOException
{
try
{
System.out.println("Enter the file name");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String fileName=br.readLine();
File f=new File(fileName);
BufferedReader brf = new BufferedReader(new FileReader(f)) ;
String str;
while ((str=brf.readLine())!=null)
{
System.out.println(str);
}
brf.close();
}
catch (IOException e)
{
e.printStackTrace(); }
}
}
22
class writeDataToFile
{
public static void main( String args[]) throws IOException
{
try
{
File fl = new File("c:/tst.txt");
String str="Write this string to my file";
FileWriter fw = new FileWriter(fl) ;
fw.write(str);
fw.close();
}
catch (IOException e)
{ e.printStackTrace(); }
}
}
23
 A directory is a File that contains a list of other files & rectories.
 When you create a File object & it is a directory, the isDirectory()
method will return true. In this case list method can be used to extract the
list of other files & directories inside.
 The forms of list() method ispublic String[] list()
public String[] list(FilenameFilter filter)
String dirname=“c:/javaprg/demo";
File f1=new File(dirname);
if(f1.isDirectory())
{
String s[]=f1.list();
for(int i=0;i<s.length;i++)
{
File f=new File(dirname+"/"+s[i]);
if(f.isDirectory())
System.out.println(s[i]+" is a directory");
else
System.out.println(s[i]+" is a File");
}
}
24