Experiment5 (Lab5)
Experiment5 (Lab5)
Theory:
An object whose state cannot be changed after it is created is known as an Immutable object. String,
Integer, Byte, Short, Float, Double and all other wrapper class's objects are immutable.
String can be created in number of ways, here are a few ways of creating string object.
String literal is a simple string enclosed in double quotes " ". A string literal is treated as a String object.
String str1 = "Hello";
2) Using another String object
When we create a new string object using string literal, that string literal is added to the string pool, if it is not
present there already.
String str= "Hello";
And, when we create another object with same string, then a reference of the string literal already present
in string pool is returned.
String str2=str;
But if we change the new string, its reference gets modified.
str2=str2.concat("world");
Concatenating String
string s = "Hello";
string str = "Java";
string str2 = s.concat(str);
String str1 = "Hello".concat("Java"); //works with string literals too.
2) Using + operator
string str = "Rahul";
string str1 = "Dravid";
string str2 = str + str1;
string st = "Rahul"+"Dravid";
String Comparison
2. Using == operator
3. By CompareTo() method
equals() method compares two strings for equality. Its general syntax is,
boolean equals (Object str)
It compares the content of the strings. It will return true if string matches, else returns false.
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); //true
s.equals(s1) ; //false
Using == operator
== operator compares two object references to check whether they refer to same instance. This also, will
return true on successful match.
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false
By compareTo() method
compareTo() method compares values and returns an int which tells if the string compared is less than,
equal to or greater than th other string. Its general syntax is,
int compareTo(String str)
To use this function you must implement the Comparable Interface. compareTo() is the only function in
Comparable Interface.
String s1 = "Abhi";
String s2 = "Viraaj";
String s3 = "Abhi";
s1.compareTo(S2); //return -1 because s1 < s2
s1.compareTo(S3); //return 0 because s1 == s3
s2.compareTo(s1); //return 1 because s2 > s1
The following methods are some of the most commonly used methods of String class.
charAt()
charAt() function returns the character located at the specified index.
String str = "studytonight";
System.out.println(str.charAt(2));
Output : u
equalsIgnoreCase()
equalsIgnoreCase() determines the equality of two Strings, ignoring thier case (upper or lower case
doesn't matters with this fuction ).
String str = "java";
System.out.println(str.equalsIgnoreCase("JAVA"));
Output : true
length()
replace()
substring()
substring() method returns a part of the string. substring() method has two forms,
public String substring(int begin);
public String substring(int begin, int end);
The first argument represents the starting point of the subtring. If the substring() method is called with
only one argument, the subtring returned, will contain characters from specified starting point to the end
of original string.
But, if the call to substring() method has two arguments, the second argument specify the end point of
substring.
String str = "0123456789";
System.out.println(str.substring(4));
Output : 456789
System.out.println(str.substring(4,7));
Output : 456
toLowerCase()
toLowerCase() method returns string with all uppercase characters converted to lowercase.
String str = "ABCDEF";
System.out.println(str.toLowerCase());
Output : abcdef
valueOf()
Overloaded version of valueOf() method is present in String class for all primitive data types and for type
Object.
valueOf() function is used to convert primitive data types into Strings.
toString()
toString() method returns the string representation of the object used to invoke this method. toString() is
used to represent any Java Object into a meaningful string representation. It is declared in the Object
class, hence can be overrided by any java class. (Object class is super class of all java classes.)
public class Car {
public static void main(String args[])
{
Car c=new Car();
System.out.println(c);
}
public String toString()
{
return "This is my car object";
}
}
Output : This is my car object
Whenever we will try to print any object of class Car, its toString() function will be called. toString() can
also be used with normal string objects.
String str = "Hello World";
System.out.println(str.toString());
Output : Hello World
toUpperCase()
This method returns string with all lowercase character changed to uppercase.
String str = "abcdef";
System.out.println(str.toUpperCase());
Output : ABCDEF
trim()
This method returns a string from which any leading and trailing whitespaces has been removed.
String str = " hello ";
System.out.println(str.trim());
Output : hello
StringBuffer class
StringBuffer class is used to create a mutable string object. It represents growable and writable character
sequence. As we know that String objects are immutable, so if we do a lot of changes with String objects,
we will end up with a lot of memory leak.
So StringBuffer class is used when we have to make lot of modifications to our string. It is also thread
safe i.e multiple threads cannot access it simultaneously. StringBuffer defines 4 constructors. They are,
1. StringBuffer ( )
2. StringBuffer ( int size )
3. StringBuffer ( String str )
4. StringBuffer ( charSequence [ ]ch )
StringBuffer() creates an empty string buffer and reserves room for 16 characters.
stringBuffer(int size) creates an empty string and takes an integer argument to set capacity of the
buffer.
class Test {
public static void main(String args[])
{
String str = "study";
str.concat("tonight");
System.out.println(str); // Output: study
StringBuffer strB = new StringBuffer("study");
strB.append("tonight");
System.out.println(strB); // Output: studytonight
}
}
The following methods are some most commonly used methods of StringBuffer class.
append()
This method will concatenate the string representation of any type of data to the end of the
invokingStringBuffer object. append() method has several overloaded forms.
StringBuffer append(String str)
StringBuffer append(int n)
insert()
This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)
reverse()
This method replaces the string from specified start index to the end index.
StringBuffer str = new StringBuffer("Hello World");
str.replace( 6, 11, "java");
System.out.println(str);
Output : Hello java
capacity()
ensureCapacity()
StringBuilder class
StringBuilder is identical to StringBuffer except for one important difference it is not synchronized,
which means it is not thread safe. Its because StringBuilder methods are not synchronised.
StringBuilder Constructors
Example of StringBuilder
class Test {
public static void main(String args[])
{
StringBuilder str = new StringBuilder("study");
str.append( "tonight" );
System.out.println(str);
str.replace( 6, 13, "today");
System.out.println(str);
str.reverse();
System.out.println(str);
str.replace( 6, 13, "today");
}
}
Output :
studytonight
studyttoday
yadottyduts
Math Class
The Java class library is huge. We will not cover it all today. In fact, the remaining eight classes will focus
mostly on the class library. However, I do want to take this opportunity to look briefly at one useful class
in the library, java.lang.Math. This is a class which contains static methods for performing many
standard mathematical operations like square roots and cosines. You will need it for many of this weeks
exercises.
The Math class contains several dozen static methods. Recall that to use a static method from a class, you
just prefix its name with the name of the class followed by a period. For instance
double x = Math.sqrt(9.0);
You never need to instantiate the Math class directly. (In fact you can't. The Math() constructor is declared
private.)
int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;
// Comparison operators
The final keyword is used in several different contexts as a modifier meaning that what it modifies
cannot be changed in some sense.
final classes
You will notice that a number of the classes in Java library are declared final, e.g.
public final class String
This means this class will not be sub classed, and informs the compiler that it can perform certain
optimizations it otherwise could not. It also provides some benefit in regard to security and thread safety.
The compiler will not let you subclass any class that is declared final. You probably won't want or need
to declare your own classes final though.
final methods
You can also declare that methods are final. A method that is declared final cannot be overridden in a
subclass. The syntax is simple, just put the keyword final after the access specifier and before the return
type like this:
final fields
You may also declare fields to be final. This is not the same thing as declaring a method or class to
be final. When a field is declared final, it is a constant which will not and cannot change. It can be set
once (for instance when the object is constructed, but it cannot be changed after that.) Attempts to change
it will generate either a compile-time error or an exception (depending on how sneaky the attempt is).
Fields that are both final, static, and public are effectively named constants. For
instance a physics program might define Physics.c, the speed of light as
public class Physics {
In the SlowCar class, the speedLimit field is likely to be both final and static though
it's private.
public class SlowCar extends Car {
this.speed = speed;
Final arguments
Finally, you can declare that method arguments are final. This means that the method will not directly
change them. Since all arguments are passed by value, this isn't absolutely required, but it's occasionally
helpful.
class Student{
int rollno;
String name;
String college="ITS";
}
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
In this example, we have created an instance variable named count which is incremented in the constructor.
Since instance variable gets the memory at the time of object creation, each object will have the copy of
the instance variable, if it is incremented, it won't reflect to other objects. So each objects will have the
value 1 in the count variable.
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
}
}
Output:
1
1
1
As we have mentioned above, static variable will get the memory only once, if any object changes
the value of the static variable, it will retain its value.
class Counter2{
static int count=0;//will get memory only once and retain its value
Counter2(){
count++;
System.out.println(count);
}
}
}
Output:
1
2
3
2) Java static method
If you apply static keyword with any method, it is known as static method.
class Student9{
int rollno;
String name;
static String college = "ITS";
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
class Calculate{
static int cube(int x){
return x*x*x;
}
There are two main restrictions for the static method. They are:
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
class A{
int a=40;//non static
There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.
Comments/Conclusion: