Chapter 7 - A Closer Look On Methods and Classes
Chapter 7 - A Closer Look On Methods and Classes
class Factorial {
int fact(int n) {
if (n==1) return 1;
return fact(n-1) * n;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.print("Factorial of 5 is ");
System.out.println(f.fact(5));
} }
String Handling
• String is probably the most commonly used class in Java's class library.
The obvious reason for this is that strings are a very important part of
programming.
• The first thing to understand about strings is that every string you create
is actually an object of type String. Even string constants are actually
String objects.
• For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
• Java defines one operator for String objects: +.
• It is used to concatenate two strings. For example, this statement
• String myString = "I" + " like " + "Java.";
results in myString containing
"I like Java."
• The String class contains several methods that you can use. Here are a few.
You can
• test two strings for equality by using
equals( ). You can obtain the length of a string by calling the length( ) method.
You can obtain the character at a specified index within a string by calling
charAt( ). The general forms of these three methods are shown here:
• // Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +strOb1.length());
System.out.println ("Char at index 3 in strOb1: " + strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
}