Lecture1 Strings
Lecture1 Strings
Content
Package java.lang
Program Layout
The constructor and main Methods
The String Class
String Class Methods
Exception Handling
Package java.lang
Provides classes that are fundamental to the design of
the Java programming language.
The most important classes are Object, which is the
root of the class hierarchy, and Class, instances of
which represent classes at run time.
Package java.lang automatically gets called
Java program layout
Typical java program layout
Package
Class
Constructor method
Main method
example Package name
1. package forloopexercise;
2. /**
3. * Title: forLoopExercise
4. * Description: for loop to output a multiplication table of 2
5. * Copyright: Copyright (c) 2009
6. * Company: nus
7. * @author hobert
8. * @version 1.0
9. */ Class name
Comparing strings
Searching strings
Extracting substrings
Translating to uppercases and lowercases
String concatenation
String concatenation
Used to combine two or more Strings.
This is done by using the + symbol
Example
String tempString1=“Hello”;
String tempString2=“World”;
String tempString3;
tempString3=tempString1+tempString2
System.out.println(tempString3)
String.length() method
Used to return the number of characters in the String
Example Expected Output
int len1=temp1.length();
System.out.println(“len1 is “+ len1);
int len2=temp2.length()’;
System.out.println(“len2 is “+ len2);
int len3=temp3.length()’;
System.out.println(“len3 is “+ len3);
char String.charAt(int) method
Returns the char (character ) at the given element
position of the String
System.out.println(“rso = ”+rs0);
System.out.println(“rs1 = ”+rs1);
int String.compareTo(String) method
Used to compare two Strings
cv=temp1.compareTo(temp4);
System.out.println(“cv=“+cv);
cv=temp1.compareTo(temp2);
System.out.println(“cv=“+cv);
cv=temp3.compareTo(temp31;
System.out.println(“cv=“+cv);
Uppercase to Lowercase
Example
String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs
"HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs
"hello world"