Unit Iii1
Unit Iii1
This work is created by N.Senthil madasamy, Dr. A.Noble Mary Juliet, Dr. M. Senthilkumar and is licensed under a
Creative Commons Attribution-ShareAlike 4.0 International License
What is String?
3
What is String?
• A string is a sequence of characters
• The easiest way to represent a sequence of
characters in JAVA
char Array[ ] = new char [5];
– Using a character array char[] ch={'j','a','v','a'};
– Using String Class. String s="java";
4
Java String
• Strings in java are immutable.
• What is immutable?
14
String Constructors
1.Creates an empty string
String s = new String();
2. Creates a string with “value”
String s = new String(“value”); -
3. Creates a String with character array
String s = new String(char ch[10]);
4. Creates a string using subrange of a character array
String(char ch[], int startIndex, int numChars);
String s = new String(char ch[10],5,5);
5. Creates a string using other string object
15
Java String Example
Syntax:-
public void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
Eg:-
String s= "mesquite in your cellar"
s.replace('e', 'o') => ?
String Operations
• toLowerCase(): Converts all of the characters in a String to
lower case.
• toUpperCase(): Converts all of the characters in this String to
upper case.
Eg: “JAVA”.toLowerCase();=> ?
“mcet”.toUpperCase();=> ?
String Operations
• trim() - Returns a copy of the string, with leading and trailing
whitespace omitted.
public String trim()
Eg:
String s1="java string split method by javatpoint";
String[] words=s1.split("\\s");
//splits the string based on whitespace
System.out.println(words[0]) ?
Tutorial Problem
1.Write a java program to count no of vowels
presented in given string
Eg: “Welcome to Java”
o/p =>
a=2 e=2 i=0 o=2 u=0
Tutorial Problem
2. Write a java program to check whether the
given string is palindrome or not
• Hint: MALAYALAM is Palindrome
3. Write a program that computes your initials
from your full name and displays them.
• Hint : S.Raj Kumar=> SRK
• Character.isUpperCase(String.charAt(index))
Tutorial Problem
4.Write a java program to read two string S1,S2.
and check S2 is available in S1 or not.
Hints:
S1 =“Welcome to Java”
S2=“com ”
What is String Buffer?
StringBuffer
• A StringBuffer is like a String, but can be modified.
• Output
HiBye
StringBuffer Operations
Insert
Index specifies at which point the string will be inserted into the
invoking StringBuffer object.
StringBuffer Operations
• delete() - Removes the characters in a substring of this
StringBuffer. The substring begins at the specified start and
extends to the character at index end - 1 or to the end of the
StringBuffer if no such character exists. If start is equal to end,
no changes are made.
public StringBuffer delete(int start, int end)
Public StringBuffer deleteCharAt(int index)
StringBuffer Operations
• reverse() - The character sequence contained in this string buffer is
replaced by the reverse of the sequence.
Class test
{
public static void main(String ss[])
{
StringBuffer b=new StringBuffer(“Java”);
System.out.println(b.reverse());
}
} avaJ
StringBuffer Operations
• capacity() - Returns the current capacity of the String buffer. The capacity
is the amount of storage available for newly inserted characters.
class test
{
public static void main(String ss[])
{
StringBuffer s=new StringBuffer("Java is my favorite language");
System.out.println("Lenth =" +s.length());
System.out.println("Capacity = "+s.capacity());
}
}
StringBuffer Operations
similar to String
sb.charAt(1); e
sb.setCharAt(1,’i’); Hillo
sb.setLength(2); Hi
sb.append(“l”).append(“l”) Hill
o/p
• Infinity: true, false
• NaN: false, true
java.lang
Byte, Short, Integer, and Long
• Byte(byte num)
• Byte(String str) throws NumberFormatException
• Short(short num)
• Short(String str) throws NumberFormatException
• Integer(int num)
• Integer(String str) throws NumberFormatException
• Long(long num)
• Long(String str) throws NumberFormatException
• Methods are similar to Float/Double
Converting Numbers to and from Strings
import java.io.*;
class ParseDemo {
public static void main(String args[]) throws IOException
{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str; int I; int sum=0;
System.out.println("Enter numbers, 0 to quit.");
do {
str = br.readLine();
try {
i = Integer.parseInt(str);
} catch(NumberFormatException e) {
System.out.println("Invalid format");
i = 0;
}
sum += i;
System.out.println("Current sum is: " + sum);
} while(i != 0);
Character
Java.lang
• Character is a simple wrapper around a char.
• The constructor for Character is
– Character(char ch)
class IsDemo {
public static void main(String args[]) {
char a[] = {'a', 'b', '5', '?', 'A', ' '};
for(int i=0; i<a.length; i++) {
if(Character.isDigit(a[i])) System.out.println(a[i] + " is a digit.");
if(Character.isLetter(a[i])) System.out.println(a[i] + " is a letter.");
if(Character.isWhitespace(a[i])) System.out.println(a[i] + " is whitespace.");
if(Character.isUpperCase(a[i])) System.out.println(a[i] + " is uppercase.");
if(Character.isLowerCase(a[i])) System.out.println(a[i] + " is lowercase.");
}
}
java.lang
Void
• The Void class has one field, TYPE, which holds
a reference to the Class object for type void.
• Can’t create instances of this class.
java.lang
• Process
• The abstract Process class encapsulates a
process—that is, an executing program.
• It is used primarily as a superclass for the type of
objects created by exec( ) in the Runtime class,
or by start( ) in the ProcessBuilder class.
java.lang
• Process methods
java.lang
• Runtime
• The Runtime class encapsulates the run-time
environment.
• We can get a reference to the current Runtime
object by calling the static method
Runtime.getRuntime( ).
java.lang
exec() is method to execute the program you want to run as well as its input
parameters
class ExecDemo {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
Process p = null;
try {
p = r.exec("notepad");//you can Specify the path of Exe files
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
}
}
This program will open notepad and terminate its execution ,even notepad still
open.
java.lang
class ExecDemoFini {
public static void main(String args[]) {
Runtime r = Runtime.getRuntime();
Process p = null;
try {
p = r.exec("notepad");
p.waitFor();
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
System.out.println("Notepad returned " + p.exitValue());
}
}
This program will open notepad and wait for termination of notepad.
java.lang
Memory Management
• Java provides automatic garbage collection,
• sometimes we wants to know how large the object heap is and
how much of it is left.
• We can use this information, for example, to check our code for
efficiency or to approximate how many more objects of a certain
type can be instantiated.
System.arraycopy(a, 0, b, 0, a.length);