Sei sulla pagina 1di 19

Experiment 5

String & Math Class, Static, Final & this Keyword


Exercise Objectives:
To understand the String class and also various math functions provided by built-in Math class. Also the
use of static, this and final keyword in Java.

Theory:

Introduction to String Handling


String is probably the most commonly used class in java library. String class is encapsulated
under java.lang package. In java, every string that you create is actually an object of type String. One
important thing to notice about string object is that string objects are immutable that means once a string
object is created it cannot be altered.

What is an Immutable object?

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.

Creating an Immutable class

public final class MyString


{
final String str;
MyString(String s)
{
this.str = s;
}
public String get()
{
return str;
}
}
In this example MyString is an immutable class. MyString's state cannot be changed once it is created.

Creating a String object

String can be created in number of ways, here are a few ways of creating string object.

1) Using a String literal

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

String str2 = new String(str1);

3) Using new Keyword

String str3 = new String("Java");

4) Using + operator (Concatenation)

String str4 = str1 + str2;


or,
String str5 = "hello"+ "Java";
Each time you create a String literal, the JVM checks the string pool first. If the string literal already
exists in the pool, a reference to the pool instance is returned. If string does not exist in the pool, a new
string object is created, and is placed in the pool. String objects are stored in a special memory area
known as string constant pool inside the heap memory.

String object and how they are stored

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

There are 2 methods to concatenate two or more string.


1. Using concat() method
2. Using + operator

1) Using concat() method

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

String comparison can be done in 3 ways.

1. Using equals() method

2. Using == operator

3. By CompareTo() method

Using equals() 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

String class function

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()

length() function returns the number of characters in a String.


String str = "Count me";
System.out.println(str.length());
Output : 8

replace()

replace() method replaces occurances of character with a specified new character.


String str = "Change me";
System.out.println(str.replace('m','M'));
Output : Change Me

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.

But for objects, valueOf() method calls toString() function.

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

toString() with Concatenation


Whenever we concatenate any other primitive data type, or object of other classes with a String
object,toString() function or valueOf() function is called automatically to change the other object or
primitive type into string, for successful concatenation.
int age = 10;
String str = "He is" + age + "years old.";
In above case 10 will be automatically converted into string for concatenation using valueOf() function.

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.

Example showing difference between String and String 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
}
}

Important methods of StringBuffer class

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)

StringBuffer append(Object obj)


The string representation of each parameter is appended to StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.append(123);
System.out.println(str);
Output : test123

insert()

This method inserts one string into another. Here are few forms of insert() method.
StringBuffer insert(int index, String str)

StringBuffer insert(int index, int num)

StringBuffer insert(int index, Object obj)


Here the first parameter gives the index at which position the string will be inserted and string
representation of second parameter is inserted into StringBuffer object.
StringBuffer str = new StringBuffer("test");
str.insert(4, 123);
System.out.println(str);
Output : test123

reverse()

This method reverses the characters within a StringBuffer object.


StringBuffer str = new StringBuffer("Hello");
str.reverse();
System.out.println(str);
Output : olleH
replace()

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()

This method returns the current capacity of StringBuffer object.


StringBuffer str = new StringBuffer();
System.out.println( str.capacity() );
Output : 16

ensureCapacity()

This method is used to ensure minimum capacity of StringBuffer object.


StringBuffer str = new StringBuffer("hello");
str.ensureCapacity(10);

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

1. StringBuilder ( ), creates an empty StringBuilder and reserves room for 16 characters.


2. StringBuilder ( int size ), create an empty string and takes an integer argument to set capacity of
the buffer.
3. StringBuilder ( String str ), create a StringBuilder object and initialize it with string str.

Difference between StringBuffer and StringBuilder class

StringBuffer class StringBuilder class


StringBuffer is synchronized. StringBuilder is not synchronized.

Because of synchronisation, StringBuffer operation is StringBuilder operates faster.


slower than StringBuilder.

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.)

Examples of java.lang.Math Methods


Here is an example program that exercises most of the routines in java.lang.Math. If your high school
math is a little rusty, don't worry if you don't remember the exact meaning of logarithms or cosines. Just
know that they're here in Java if you need them.
public class MathLibraryExample {

public static void main(String[] args) {

int i = 7;
int j = -9;
double x = 72.3;
double y = 0.34;

System.out.println("i is " + i);


System.out.println("j is " + j);
System.out.println("x is " + x);
System.out.println("y is " + y);

// The absolute value of a number is equal to


// the number if the number is positive or
// zero and equal to the negative of the number
// if the number is negative.

System.out.println("|" + i + "| is " + Math.abs(i));


System.out.println("|" + j + "| is " + Math.abs(j));
System.out.println("|" + x + "| is " + Math.abs(x));
System.out.println("|" + y + "| is " + Math.abs(y));

// Truncating and Rounding functions

// You can round off a floating point number


// to the nearest integer with round()
System.out.println(x + " is approximately " + Math.round(x));
System.out.println(y + " is approximately " + Math.round(y));

// The "ceiling" of a number is the


// smallest integer greater than or equal to
// the number. Every integer is its own
// ceiling.
System.out.println("The ceiling of " + i + " is " + Math.ceil(i));
System.out.println("The ceiling of " + j + " is " + Math.ceil(j));
System.out.println("The ceiling of " + x + " is " + Math.ceil(x));
System.out.println("The ceiling of " + y + " is " + Math.ceil(y));

// The "floor" of a number is the largest


// integer less than or equal to the number.
// Every integer is its own floor.
System.out.println("The floor of " + i + " is " + Math.floor(i));
System.out.println("The floor of " + j + " is " + Math.floor(j));
System.out.println("The floor of " + x + " is " + Math.floor(x));
System.out.println("The floor of " + y + " is " + Math.floor(y));

// Comparison operators

// min() returns the smaller of the two arguments you pass it


System.out.println("min(" + i + "," + j + ") is " + Math.min(i,j));
System.out.println("min(" + x + "," + y + ") is " + Math.min(x,y));
System.out.println("min(" + i + "," + x + ") is " + Math.min(i,x));
System.out.println("min(" + y + "," + j + ") is " + Math.min(y,j));

// There's a corresponding max() method


// that returns the larger of two numbers
System.out.println("max(" + i + "," + j + ") is " + Math.max(i,j));
System.out.println("max(" + x + "," + y + ") is " + Math.max(x,y));
System.out.println("max(" + i + "," + x + ") is " + Math.max(i,x));
System.out.println("max(" + y + "," + j + ") is " + Math.max(y,j));

// The Math library defines a couple


// of useful constants:
System.out.println("Pi is " + Math.PI);
System.out.println("e is " + Math.E);
// Trigonometric methods
// All arguments are given in radians
// Convert a 45 degree angle to radians
double angle = 45.0 * 2.0 * Math.PI/360.0;
System.out.println("cos(" + angle + ") is " + Math.cos(angle));
System.out.println("sin(" + angle + ") is " + Math.sin(angle));
// Inverse Trigonometric methods
// All values are returned as radians
double value = 0.707;
System.out.println("acos(" + value + ") is " + Math.acos(value));
System.out.println("asin(" + value + ") is " + Math.asin(value));
System.out.println("atan(" + value + ") is " + Math.atan(value));
// Exponential and Logarithmic Methods
// exp(a) returns e (2.71828...) raised
// to the power of a.
System.out.println("exp(1.0) is " + Math.exp(1.0));
System.out.println("exp(10.0) is " + Math.exp(10.0));
System.out.println("exp(0.0) is " + Math.exp(0.0));
// log(a) returns the natural
// logarithm (base e) of a.
System.out.println("log(1.0) is " + Math.log(1.0));
System.out.println("log(10.0) is " + Math.log(10.0));
System.out.println("log(Math.E) is " + Math.log(Math.E));
// pow(x, y) returns the x raised
// to the yth power.
System.out.println("pow(2.0, 2.0) is " + Math.pow(2.0,2.0));
System.out.println("pow(10.0, 3.5) is " + Math.pow(10.0,3.5));
System.out.println("pow(8, -1) is " + Math.pow(8,-1));
// sqrt(x) returns the square root of x.
for (i=0; i < 10; i++) {
System.out.println(
"The square root of " + i + " is " + Math.sqrt(i));
}
// Finally there's one Random method
// that returns a pseudo-random number
// between 0.0 and 1.0;
System.out.println("Here's one random number: " + Math.random());
System.out.println("Here's another random number: " + Math.random());
}
}
The final keyword

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:

public final String convertCurrency()

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 {

public static final double c = 2.998E8;


}

In the SlowCar class, the speedLimit field is likely to be both final and static though
it's private.
public class SlowCar extends Car {

private final static double speedLimit = 112.65408; // kph == 70 mph

public SlowCar(String licensePlate, double speed, double maxSpeed,


String make, String model, int year, int numberOfPassengers, int numDoors) {
super(licensePlate,
(speed < speedLimit) ? speed : speedLimit,
maxSpeed, make, model, year, numberOfPassengers, numDoors);
}

public void accelerate(double deltaV) {

double speed = this.speed + deltaV;

if (speed > this.maxSpeed) {


speed = this.maxSpeed;
}

if (speed > speedLimit) {


speed = speedLimit;
}

if (speed < 0.0) {


speed = 0.0;
}

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.

Java static keyword


The static keyword in java is used for memory management mainly. We can apply java static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than instance of
the class.
The static can be:

1. variable (also known as class variable)


2. method (also known as class method)
3. block
4. nested class

1) Java static variable

If you declare any variable as static, it is known static variable.


The static variable can be used to refer the common property of all objects (that is not unique for
each object) e.g. company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Understanding problem without static variable

class Student{
int rollno;
String name;
String college="ITS";
}

Example of static variable

//Program of static variable

class Student8{
int rollno;
String name;
static String college ="ITS";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student8 s1 = new Student8(111,"Karan");
Student8 s2 = new Student8(222,"Aryan");

s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS

Program of counter without static variable

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);
}

public static void main(String args[]){

Counter c1=new Counter();


Counter c2=new Counter();
Counter c3=new Counter();

}
}
Output:
1
1
1

Program of counter by static variable

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);
}

public static void main(String args[]){

Counter2 c1=new Counter2();


Counter2 c2=new Counter2();
Counter2 c3=new Counter2();

}
}
Output:
1
2
3
2) Java static method

If you apply static keyword with any method, it is known as static method.

A static method belongs to the class rather than object of a class.


A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.

Example of static method

//Program of changing the common property of all objects(static field).

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){System.out.println(rollno+" "+name+" "+college);}

public static void main(String args[]){


Student9.change();

Student9 s1 = new Student9 (111,"Karan");


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

Another example of static method that performs normal calculation

//Program to get cube of a given number by static method

class Calculate{
static int cube(int x){
return x*x*x;
}

public static void main(String args[]){


int result=Calculate.cube(5);
System.out.println(result);
}
}
Output:125

Restrictions for static method

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

public static void main(String args[]){


System.out.println(a);
}
}
Output:Compile Time Error

3) Java static block

1. Is used to initialize the static data member.


2. It is executed before main method at the time of class loading.
Example of static block
class A2{
static{System.out.println("static block is invoked");}
public static void main(String args[]){
System.out.println("Hello main");
}
}
Output: static block is invoked
Hello main
this keyword in java

There can be a lot of usage of java this keyword. In java, this is a reference variable that
refers to the current object.

Usage of java this keyword

Here is given the 6 usage of java this keyword.

1. this keyword can be used to refer current class instance variable.


2. this() can be used to invoke current class constructor.
3. this keyword can be used to invoke current class method (implicitly)
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this keyword can also be used to return the current class instance.

Comments/Conclusion:

Potrebbero piacerti anche