Reputation: 677
public class UpLower {
public static void main(String[] args) {
String str = "HOW ARE YOU";
String upper_str = str.toLowerCase();
System.out.println("Original String: " + str);
System.out.println("String in uppercase: " + upper_str);
}
}
This program converts the string from upper to lower character. I can't understand this program.
My questions is
method toLowerCase() is in String class which is in lang package.In java, we need to create an object for the class to access the non-static
methods of that class. If that is the case, without creating object for the class String how can we directly access the method toLowerCase().
Upvotes: 1
Views: 619
Reputation: 1
String s1 = "Foo"; // initialize an object in Heap if "Foo" is not in Heap. String s2 = "Foo"; // first it check if the object exists in heap then it will return its reference, other wise it initialize new object with this value. so, when you first write String s1 = "Foo", internally it creates and initialize an String objects, that's why its allowing you to access its methods.
Upvotes: -1
Reputation: 1565
You are right about your understanding of static methods and instance methods.
toLowerCase() is infact an instance method of object which are of type String.
But in java String has a special handling. When you write String str = "How Are You"
str will be having reference to String object. So actually you are calling instance method toLowerCase() on the returned object only.
For starter you can think that String str = "How Are You";
is similar to String str = new String("How Are You");
.
But actually there are subtle differences in the two statements String s = "something" and String s = new String("something");
If you want to know reason, try reading about String pool and String immutability in Java.
Upvotes: 2
Reputation: 122008
No you cannot. Inorder to access any objects method, you need to create an instance of it.
If you want to copy the same functionality, you can have a look at the source code of it and create another function. But I don't think it makes sense, if you are trying to lowercase
a String
, that's itself a string object and you can call lowerCase on it. ehm ?
And you are confused by String initialisation, give a read How can a string be initialized using " "?
Upvotes: 1
Reputation: 2168
String is special. When you did: String str = "HOW ARE YOU";
, a new string object got created. Refer http://net-informations.com/java/cjava/create.htm
Upvotes: 1